英文:
How to access foreign key depends on current active user in django
问题
models.py
class Shop(models.Model):
shop_name = models.CharField(max_length=100, blank=True)
slug = AutoSlugField()
logo = models.ImageField(upload_to='restaurant_profile', blank=True)
related_user = models.ForeignKey(User, on_delete=models.CASCADE)
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
slug = models.SlugField()
created_by = models.ForeignKey(Shop, on_delete=models.DO_NOTHING, default="")
forms.py
class AddProductForm(forms.ModelForm):
name = forms.CharField(widget=TextInput(attrs={
'class': 'form-control input-md',
'style': 'width: 100%; display: inline;',
}), required=True)
price = forms.CharField(widget=TextInput(attrs={
'class': 'form-control input-md',
'style': 'width: 100%; display: inline;',
}), required=True)
category = forms.ModelChoiceField(queryset=ProductCategory.objects.all(), widget=Select(attrs={
'class': 'form-control input-md',
'style': 'width: 100%; display: inline;',
}), required=True)
class Meta:
model = Product
fields = [
'name',
'price',
'category',
'is_published',
'created_by',
]
每个商店都有一个相关联的用户,当创建产品时,Product模型中的created_by字段需要填充为:
created_by = models.ForeignKey(Shop.filter(related_user=request.user))
如何在使用类视图创建产品时分配这个值?
英文:
models.py
class Shop(models.model):
shop_name = models.CharField(max_length=100, blank=True)
slug = AutoSlugField()
logo = models.ImageField(upload_to='restaurant_profile', blank=True)
related_user = models.ForeignKey(User, on_delete=models.CASCADE)
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
slug = models.SlugField()
created by = models.ForeignKey(Shop, on_delete=models.DO_NOTHING, default="")
forms.py
class AddProductForm(forms.ModelForm):
name = forms.CharField(widget=TextInput(attrs={
'class': 'form-control input-md',
'style': 'width: 100%; display: inline;',
}), required=True)
price = forms.CharField(widget=TextInput(attrs={
'class': 'form-control input-md',
'style': 'width: 100%; display: inline;',
}), required=True)
category = forms.ModelChoiceField(queryset=ProductCategory.objects.all(), widget=Select(attrs={
'class': 'form-control input-md',
'style': 'width: 100%; display: inline;',
}), required=True)
class Meta:
model = Product
fields = [
'name',
'price',
'category',
'is_published',
'created_by',
]
each shop has a related user, when a product is created, created_by field in Product models needs to fill with
created_by = models.ForeignKey(Shop.filter(related_user = request.user)
how to assign this value when creating a product from this form
I am using class-based views
答案1
得分: 1
如果您想要在表单中更改created_by
的值(不是在视图中,如您在注释中提到的),您应该将request
,或者更好地说,将request.user
传递给表单,并在保存之前添加它:
class AddProductForm(forms.ModelForm):
# ...
fields = [
'name',
'price',
'category',
'is_published',
# 'created_by' 移除这一行
]
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(AddProductForm, self).__init__(*args, **kwargs)
def save(self, commit=True, *args, **kwargs):
instance = super().save(commit=False, *args, **kwargs)
instance.created_by = self.user
instance.save()
return instance
最后一步是在视图中,每当您实例化表单时,包括user
:
views.py:
my_form = AddProductForm(user=request.user)
英文:
If you want to change the value of created_by
in the form (not in the view, as you mentioned in the comments), you should pass the request
, or even better, the request.user
to the form and add that before saving:
<pre><code>class AddProductForm(forms.ModelForm):
#...
fields = [
'name',
'price',
'category',
'is_published',
<b># 'created_by' Remove this</b>
]
def __init__(self, *args, **kwargs):
<b>self.user = kwargs.pop('user')</b>
super(UserProfileUpdateForm, self).__init__(*args,**kwargs)
def save(self, commit=True, *args, **kwargs):
instance = super().save(commit=False, *args, **kwargs)
<b>instance.created_by = self.user</b>
instance.save()
return instance</code></pre>
The final step is to include user
in views, whenever you instantiate the form:
views.py:
my_form = AddProductForm(user=request.user)
答案2
得分: 1
在视图中的有效表单方法中,您可以将已登录用户添加为创建者用户,示例为基于类的视图:
def form_valid(self, form):
form.instance.created_by = Shop.objects.get(related_user=self.request.user)
valid_data = super(ProductCreateView, self).form_valid(form)
return valid_data
英文:
in a form valid method in your views, you can add the logged in user as created by user, example shown is for a class based view
def form_valid(self, form):
form.instance.created_by = Shop.objects.get(related_user=self.request.user)
valid_data = super(ProductCreateView, self).form_valid(form)
return valid_data
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论