Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do i automatically set the user field to current user in django modelform

Tags:

django

How can i set the current login user to the user field of django model .In my view ,i am using function base view .My model is something like this . Model.py

class DistributionProfile(Abstract_Class):
      Distributortype =(
                   ('B2B1','b2b'),
                   ('b2c','b2c'),
                   ('c2c','c2c'),
                   ('govt4','govt'), 
                 )
      ManufacturerType=(('Machine1','Machines'),
                  ('Pharmaceutical2','Pharmaceutical'),
                  ('Jewelries3','Jewelries'),
                  ('Furniture4','Funitures'),
                  ('Electronics5','Electronics'),('Textile6','Textile'),
                  ('Constructionmaterials7','ConstructionHardware'),
                  ('Beverages8','Beverages'),
                  ('Cosmetics9','Cosmetics'),
                  ('Convectionaries10','Convectionaries'),
                  ('AgriculturalProduce11','AgriculturalProduce'),
                  ('RawMaterials12','RawMaterials'),
                  ('CrudOil13','CrudOil'),
                  ('SeaFood14','SeaFood'),

                  )
    title =models.CharField(choices=Distributortype ,null=True,max_length=250,blank=False)
    ManufacturerOfInterest =MultiSelectField(choices=ManufacturerType,null=True,blank=False,max_choices=14)
    verified = models.BooleanField(default=False,blank=True)
    promot=models.BooleanField(default=False,blank=False) 
    slug = models.SlugField(default='')

    user=models.ForeignKey(User,null=True,on_delete=models.CASCADE)

bellow is my form.I would love the form to automatically have the information of the login user filling the form .Meaning the user field should automatically have the information of the login in user .So that i can easily query and display objects created by the login user form.py

class   DistributionProfileForm(forms.ModelForm):
    class Meta:
         model= DistributionProfile


         exclude=  ['slug','user','CreatedTime','verified','promot','UpdatedTime']
         widgets ={
         'CompanyRegisteredName':forms.TextInput(attrs={'class':'distributorform','placeholder':'Name of your company','autofocus':'True'}),
         'CompanyRegisteredState':forms.TextInput(attrs={'class':'distributorform','placeholder':' StateOfRegistry'}),
         'CompanyRegisteredAddress':forms.TextInput(attrs={'class':'distributorform','placeholder':'Company Address'}),
         'CompanyRegisteredCity':forms.TextInput(attrs={'class':'distributorform','placeholder':'Company registered city'}),
         'CompanyWebsiteLink':forms.TextInput(attrs={'class':'distributorform','placeholder':'www.mycompany.com'}),
         'RegisteredCompanyType':forms.Select(attrs={'class':'distributorform '}),
         'Country':forms.Select(attrs={'class':'distributorform'}),
         'ManufacturerOfInterest ':forms.CheckboxSelectMultiple(attrs={'class':'multiple_select'}),


    }
         fields=['CompanyRegisteredName',
            'CompanyRegisteredState',
            'CompanyRegisteredAddress',
            'CompanyRegisteredCity', 
            'CompanyWebsiteLink',
            'RegisteredCompanyType',
            'Country','title',
            'ManufacturerOfInterest'

            ]

view.py

def SetUpDistributor(request):
if not request.user:
    return HttpResponse('login to access this page ')
if request.method =='POST':

    distributor = DistributionProfileForm(request.POST,request.FILES)
    if distributor.is_valid():
        distributor.save(commit=False)
        distributor.user=request.user
        distributor.save()
        messages.success(request,'Distributor profile created ')
        return redirect('gbiz1990:distributor_profile_setup')
    else:
        messages.error(request,'Something went wrong')
else:
    distributor=DistributionProfileForm()
return render(request,"gbiz1990/User_function_pages/distributors.html",{'distributor':distributor})
like image 537
Scofield Avatar asked Jan 27 '26 05:01

Scofield


1 Answers

Your views, may looks like that:

def your_view(request):
    form = YourForm(request.POST or None)

    if form.is_valid():
        your_object = form.save(commit=False)
        your_object.user = request.user
        your_object.save()
        return redirect('your_success_url')

    context = {'form': form}
    return render(request, 'your_template.html', context)

You need to adapt some parts, but in the general the should be your view. You need to pay attention to that this view needs a login_required decorator in order to not allow non-logged users to create objects.

like image 113
Luan Fonseca Avatar answered Jan 29 '26 18:01

Luan Fonseca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!