怎么做我自动将用户字段设置为django modelform中的当前用户

时间:2017-10-25 19:28:11

标签: django

如何将当前登录用户设置为django model的用户字段。在我看来,我正在使用功能库视图。我的模型是这样的。 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)
下面是我的表格。我希望表格能够自动获取填写表格的登录用户的信息。意味着用户字段应该自动获取用户登录信息。这样我就可以轻松查询和显示对象由登录用户创建 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})

3 个答案:

答案 0 :(得分:2)

您的观点可能如下:

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)

你需要调整一些部分,但总的来说应该是你的看法。您需要注意此视图需要login_required装饰器,以便不允许非登录用户创建对象。

答案 1 :(得分:0)

使用request.user。我不知道你的应用程序是如何工作的,但在创建时,请执行以下操作:

model = ModelName(user = request.user)
model.save()

我使用了ModelName,因为最佳做法是使用资本启动一个类名,而create模型中没有这样做。我建议你改变它。

您的观点中似乎也有错误,应该是request而不是reques

您的观点可能如此:

def index(request):
    form = FormName(request.POST or None)
    if form.is_valid():
        form.save()
    return render(request, "path/to/template", {"form": form})

您的模板可能是:

<form method="POST" action="">
    {{ form }}
    <input type="submit">
</form>

答案 2 :(得分:0)

所以我解决了我的问题  在我的model.py

class SetdistributorProfile(models.Model):
      user=modelss.foreignkey(settings.AUTH_USER_MODEL,null=True,unique=True)

views.py

def SetDistribution(request):
    if not requested.user.is_authenticated:
    return redirect('app_name:url_name)
    if request.method === 'POST':
       dis = MymodelForm(request.POST or None)
       if dis.is_valid():
       instance=dis.save(commit=False)
       instance.user=request.user
       instance.save()
       return redirect('myappname:urlname')
     else:
        instance=MymodelFomr()
     context={'intance':intance}
     return render(request,'page.hmtl',context)