ventisk1ze
ventisk1ze

Reputation: 91

How do I add username of logged in user to model field in django

How to add username of currently logged in user to field in my model? For example, I need to store info about user like name, email and so on in model, other than default Django user model, but I still use default one to store credentials. I want to establish relationship between those, so I created username field in my model. How do I fill it with current user's username upon saving the corresponding form? My model

class ApplicantProfile(models.Model):
    name = models.CharField(max_length = 50)
    dob = models.DateField()
    email = models.EmailField()
    description = models.TextField()
    username = <something>

What do I change <something> with?

My form

class ApplicantProfileEdit(forms.ModelForm):
class Meta:
    model = ApplicantProfile
    fields = [
        'name',
        'dob',
        'email',
        'description',
    ]

My view

def ApplEditView(request):
    form = ApplicantProfileEdit(request.POST or None)
    if form.is_valid():
       form.save()
       form = ApplicantProfileEdit()
    context = {
       'form':form
    }
    return render(request, "applProfileEdit.html", context)

P.S. I tried to import models straight to my views.py, and assign request.user.username to username field of the model in my view, but it didn't work, just left that field empty. I had username as CharField when I tried this.

Upvotes: 2

Views: 4014

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

It is not a good idea to save the username itself, or at least not without a FOREIGN KEY constraint. If later a user changes their name, then the username now points to a non-existing user, if later another user for example changes their username to thatusername, then your ApplicantProfile will point to the wrong user.

Normally one uses a ForeignKey field [Django-doc], or in case each ApplicantProfile points to a different user, a OneToOneField [Django-doc]:

from django.conf import settings
from django.db import models

class ApplicantProfile(models.Model):
    name = models.CharField(max_length = 50)
    dob = models.DateField()
    email = models.EmailField()
    description = models.TextField()
    # maybe a OneToOneField
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

In the view:

from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def appl_edit_view(request):
    if request.method == 'POST':
        form = ApplicantProfileEdit(request.POST)
        if form.is_valid():
            form.instance.user = request.user
            form.save()
            return redirect('some-view-name')
    else:
        form = ApplicantProfileEdit()
    context = {
        'form':form
    }
    return render(request, 'applProfileEdit.html', context)

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.

 

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].

Upvotes: 6

Related Questions