B
B
blackbb2016-03-13 03:17:08
Django
blackbb, 2016-03-13 03:17:08

How to make a userprofile in django?

Hello! There are models:

class UserProfile(models.Model):  
     user = models.OneToOneField(User)

class Project(models.Model):
     title = models.CharField(max_length=200, verbose_name=u'Название')
     slug = models.SlugField(unique=True, verbose_name=u'URL')
     user = models.ForeignKey(UserProfile, verbose_name=u'Пользователь')

There is a page for adding a project (project models), it can be added by registered users, its view:
class ProjectCreate(CreateView):
    model = Project
    template_name = 'add_project.html'
    form_class = AddProjectForm
    success_url = '/project/success'
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(ProjectCreate, self).form_valid(form)

The user field in the form is hidden and I want to add the current user by default when adding a project. But it gives this error:
Cannot assign "<SimpleLazyObject: <User: galkinav>>": "Project.user" must be a "UserProfile" instance.

I understand that userprofile should be used instead of user, but I can't figure out how. Help me please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-03-14
@blackbb

The process of creating a profile is elementary.

profile = UserProfile(user=request.user)
profile.save()

A little more room for creativity in exactly where to create it.
Option #2 in the same models.py where the profile model is declared:
@receiver(post_save, sender=User, dispatch_uid="create_profile")
def update_profile(sender, instance, **kwargs):
    if kwargs["created"]:
        UserProfile.objects.create(user=instance)

If something like django-registration is used, then its signals can be used.
Option #3 in auth.py (if using your own authentication mechanism):
class SomeAuthBackend(ModelBackend):
    def get_user(self, user_id):
        try:
            user = User.objects.select_related('profile_set').get(pk=user_id)
            try:
                user.profile_set
            except UserProfile.DoesNotExist:
                UserProfile.objects.create(user=user)
            return user
        except User.DoesNotExist:
            return None

The profile will be created when the user logs in.
Option #4 in admin.py:
admin.site.unregister(User)

class UserProfileInline(admin.StackedInline):
    model = UserProfile

@admin.register(User)
class UserProfileAdmin(UserAdmin):
    inlines = [ UserProfileInline ]

    def save_model(self, request, obj, form, change):
        super(UserProfileAdmin, self).save_model(request, obj, form, change)
        if not change:
            UserProfile.objects.create(user=obj)

The profile will be created when creating a user in the admin panel.
And it is possible in some special view.

D
Dmitry Voronkov, 2016-03-13
@DmitryVoronkov

self.request.user.userprofile

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question