I've created the famous Profile model for Django's User model and it has the following fields: [profile_picture, bio, slug]
I've registered the Profile model in User model as StackedInLine
I've created a view for editing Profile's fields using the slug in the URLconf
Now I'm trying to create an UpdateView for the User model in order to change the fields, But it's missing a slug, I tried setting the slug_field to self.profile.slug but it returns a string and not the field.
How can I create an UpdateView for the User model using User.profile.slug as the slug in the URLconf? Am I even taking the right approach?
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from .storage import OverwriteStorage
def get_upload_path(instance, filename):
extension = filename.split('.')[-1]
return f'{instance.user.username}/profile_picture.{extension}'
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(blank=True, null=True)
profile_picture = models.ImageField(upload_to=get_upload_path, blank=True, storage=OverwriteStorage)
slug = models.SlugField(blank=False, null=False)
def get_absolute_url(self):
return reverse('profile', kwargs={'slug': self.slug})
admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Profile
class ProfileInline(admin.StackedInline):
model = Profile
can_delete = False
verbose_name_plural = 'employee'
class UserAdmin(BaseUserAdmin):
inlines = (ProfileInline,)
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
views.py:
class UserAccountUpdateView(UpdateView):
model = User
form_class = UserAccountUpdateForm
template_name = 'auth/edit_account.html'
slug_field = 'username'
forms.py:
class UserAccountUpdateForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password')
def __init__(self, *args, **kwargs):
super(UserAccountUpdateForm, self).__init__(*args, **kwargs)
self.fields['first_name'].widget.attrs['class'] = 'form-control bg-dark border border-secondary text-light'
self.fields['last_name'].widget.attrs['class'] = 'form-control bg-dark border border-secondary text-light'
self.fields['email'].widget.attrs['class'] = 'form-control bg-dark border border-secondary text-light'
self.fields['username'].widget.attrs['class'] = 'form-control bg-dark border border-secondary text-light'
self.fields['password'].widget.attrs['class'] = 'form-control bg-dark border border-secondary text-light'