如何在djangomodelform中自动将用户字段设置为当前用户

ztyzrc3y  于 2023-01-27  发布在  Go
关注(0)|答案(4)|浏览(179)

如何将当前登录用户设置为django模型的用户字段?在我的视图中,我使用的是函数基视图。我的模型是这样的。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)

下面是我的表单。我希望表单自动包含填写表单的登录用户的信息。这意味着用户字段应该自动包含登录用户的信息。这样我就可以轻松地查询和显示登录用户www.example.com创建的对象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})
rekjcdws

rekjcdws1#

你的看法,可能是这样的:

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装饰器,以便不允许未登录的用户创建对象。

siotufzp

siotufzp2#

使用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>
yc0p9oo0

yc0p9oo03#

所以我在www.example.com上解决了我的问题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)
djmepvbi

djmepvbi4#

在www.example.com中解决此问题的另一种方法views.py

if request.method == "POST":
        yourModel = YourModel(user_id = request.user.id)
        form = YourModelForm(request.POST, request.FILES, instance=yourModel)
        if form.is_valid():
            form.save()

相关问题