保存django中帖子的外键

0dxa2lsx  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(112)

我在Post上的Infringer表中保存FK时遇到问题。我在添加记录时尝试保存客户ID。出于故障排除目的,我添加了几个打印行,这是输出。正如您在下面看到的,存在正确的客户ID,但客户为“无”,因此未保存到记录中。其他字段保存良好。请帮助!我是初学者。
的客户forms.py为2
forms.py 示例与客户一起保存无
的客户views.py为2
成功挽救www.example.com中的侵权者views.py及其客户无
views.py

@login_required(login_url='login') def createInfringer(request):
customer=request.user.customer.id
form = InfringerForm(customer=customer)
if request.method == 'POST':
    
   
    form = InfringerForm(customer, request.POST)
    if form.is_valid():   
        saved_instance = form.save(customer)
        print (f'customer in views.py is {customer}')
        print (f'Successfully saved the infringer in views.py with its customer {saved_instance.customer}')
        

    return redirect('infringer-list')

context ={'form': form}
return render (request, 'base/infringement_form.html', context)

forms.py

class InfringerForm(ModelForm):
   class Meta:
   model = Infringer
   fields = ['name', 'brand_name','status']  

def __init__(self, customer, *args, **kwargs):
    super(InfringerForm,self).__init__(*args, **kwargs)
    
    self.fields['status'].queryset = Status.objects.filter(customer=customer)

def save(self, customer, *args, **kwargs):
    instance = super(InfringerForm, self).save( *args, **kwargs) 
    if customer:
        print (f'customer in forms.py is {customer}')
        self.customer = customer
    
    instance.save()
    
    print (f' forms.py instance was saved with the customer {instance.customer}')
    return instance

models.py

class Infringer (models.Model):
   name = models.CharField(max_length=200)
   brand_name = models.CharField(max_length=200, null=True)
   updated = models.DateTimeField(auto_now=True)
   created = models.DateTimeField(auto_now_add=True)
   status = models.ForeignKey(Status, 
     on_delete=models.SET_NULL,null=True)
    customer = models.ForeignKey(Customer, 
     on_delete=models.SET_NULL,null=True)
class Meta:
    ordering = ['-updated', '-created']
def __str__(self):
    return self.name
xqkwcwgp

xqkwcwgp1#

它可能有助于简化表单,例如:

class InfringerForm(ModelForm):
   class Meta:
       model = Infringer
       fields = ['name', 'brand_name', 'status']  

    def __init__(self, customer, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.customer = customer
        self.fields['status'].queryset = Status.objects.filter(customer=customer)

    def save(self, *args, **kwargs):
        self.instance.customer = self.customer
        return super().save( *args, **kwargs)

完成后,我们还可以将视图逻辑简化为:

@login_required(login_url='login')
def createInfringer(request):
    customer = request.user.customer
    form = InfringerForm(customer=customer)
    if request.method == 'POST':
        form = InfringerForm(customer, request.POST, request.FILES)
        if form.is_valid():   
            saved_instance = form.save()
            print (f'customer in views.py is {customer}')
            print (f'Successfully saved the infringer in views.py with its customer {saved_instance.customer}')
            return redirect('infringer-list')

    return render (request, 'base/infringement_form.html', {'form': form})

因此,我们使用customer,而不是它的主键,并且不必再在.save()方法中传递customer。

相关问题