0

I want the users, once they are logged in, to be able to add information about their company including website, name, logo, etc.

I already have this model

user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, unique=True)
comp_name = models.CharField(max_length=120,default='', blank=True)
comp_site = models.URLField(default='', blank=True)
comp_logo = models.ImageField(default='', blank=True, upload_to='img/logos/')

in my views.py I have this:

if form1.is_valid():
    saveInfo = form1.save(commit=False)
    comp_name = form1.cleaned_data.get("comp_name")
    comp_site = form1.cleaned_data.get("comp_site")
    comp_logo = form1.cleaned_data.get("comp_logo")
    saveInfo.user = form1.user
    saveInfo.save()
    return redirect('/profil/')

What I'd like is that the program would automatically detects which user is currently logged in, and set the user field to that user.

How could I do this?

doniyor
  • 36,596
  • 57
  • 175
  • 260

3 Answers3

0
if form1.is_valid():
    saveInfo = form1.save(commit=False)
    comp_name = form1.cleaned_data.get("comp_name")
    comp_site = form1.cleaned_data.get("comp_site")
    comp_logo = form1.cleaned_data.get("comp_logo")
    saveInfo.user = request.user #<--- the authenticated user bound to the current request
    saveInfo.save()
    return redirect('/profil/')

request.user is the current user who is bound to the current request. You must (probably you already do) check if user is authenticated etc..

doniyor
  • 36,596
  • 57
  • 175
  • 260
0

The request attribute sent with any Django specifies the current user.

def myview(request):
    current_user = request.user

You can check if the user is logged in using the request.user.is_authenticated() method. What I would do here is redirect the login view to the view with your form. This should automatically happen if you are using @login_required on the form view.

As an aside, if you are extending the User model, you should use OneToOneField instead of ForiegnKey. Use ForiegnKeyonly if each user can have multiple companies.

Yash Tewari
  • 760
  • 1
  • 6
  • 19
0

You can associate the users to a model using one to one field as shown below

from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bio = models.TextField()
    organisation = models.CharField(max_length=300, default="")
    country = models.CharField(max_length=50, default="")
    display_pic = models.ImageField(upload_to="authors/profile", default="")

You can then get their info of user using 'Profile' and 'User'

Rakesh Gombi
  • 322
  • 1
  • 3
  • 10