如何访问外键取决于Django中当前活动的用户

huangapple go评论69阅读模式
英文:

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 = [
    &#39;name&#39;,
    &#39;price&#39;,
    &#39;category&#39;,
    &#39;is_published&#39;,
    &lt;b&gt;# &#39;created_by&#39; Remove this&lt;/b&gt;
]

def __init__(self, *args, **kwargs):
    &lt;b&gt;self.user = kwargs.pop(&#39;user&#39;)&lt;/b&gt;
    super(UserProfileUpdateForm, self).__init__(*args,**kwargs)

def save(self, commit=True, *args, **kwargs):
    instance = super().save(commit=False, *args, **kwargs)
    &lt;b&gt;instance.created_by = self.user&lt;/b&gt;
    instance.save()
    return instance&lt;/code&gt;&lt;/pre&gt;

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

huangapple
  • 本文由 发表于 2020年1月3日 14:02:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定