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

ventisk1ze

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.

Willem Van Onsem

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].

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Multiple USERNAME_FIELD in django user model

How do I show one page to logged-in user and another to a not-logged in user with Django?

how do i link a field to a multi valued field in django model

Django - How do I add a placeholder on a modelform that's the current field of the model?

How can I add the currently logged in User as a field in Firestore

Django - Take username of logged user as default value to another model

How do I keep a user logged in? Swift

How do I link a User with a django model as soon as the User is created?

Compare Django model field and request.user.username in HTML

Django: How do I get the username of the logged-in user in my class based view?

Add a field to the Django admin for a custom user model

How to set value of model field as currently logged user? Django

How can I get the username of the logged in user in Django?

How to add the logged in user's username with django

How can I fill a field in Django with the username?

How do I get the current Windows logged-in user's username?

Use logged in username as field value in django

How do i change the navigation bar from Login to the Username after the user logged in?

Putting username of logged in user as label in django form field

How do I add data from a model to a model with the same field?

How to Save Currently Logged in User to Model in Django

Django model owner field reading the log in user as None instead of the username

How can I get a username from django User Model

How do I reference a model via User model in Django?

Django - How to populate choices in a modelchoicefield with a field from another model filtered by logged in user

How to change the field of username to user_name in to django custom user model?

How do I access User Model field in the Serializer of extended User Model in Django Rest Framework?

How to assign model form field to a current logged in user in Django's class based views

How do I add a percentage field to a model in Django?

TOP Ranking

HotTag

Archive