根据变量使用其他形式

时间:2019-05-06 16:43:51

标签: django

我有一个“产品”字段,我想用它来确定要显示的表单。我正在尝试在视图中执行此操作,但想知道是否应该在模板中执行此操作。我尝试了以下操作,但是if语句未分配“ form”。我在做什么错了?

@login_required
def update_message(request, pk):
    message = get_object_or_404(Submission, pk=pk)
    author = message.author
    date_posted = message.date_posted
    product = message.product
    message_obj = Submission.objects.get(pk=pk)
    program_type = message.program_type

if author == request.user:

    if request.method == 'POST':
        if product == 'Apple':
            form = AppleForm(request.user, request.POST, instance=message)

        if product == 'Orange':
            form = OrangeForm(request.user, request.POST, instance=message)


        if form.is_valid():
            message_sub = form.save(commit=False)
            message_sub.author = request.user
            message_sub.date_posted = timezone.now()
            message_sub.save()
            form.save_m2m()
            messages.success(request, 'Message updated')
            return redirect('submission-list')
    else:
        if product == 'Apple':
            form = AppleForm(request.user, instance=message)

        if product == 'Orange':
            form = OrangeForm(request.user, instance=message)

else:
    messages.warning(request, 'You can't do that.')
    return redirect('message-submission-list')

return render(request, 'programs/submission_create_form.html', {'product':product,'form': form, 'message_obj': message_obj,'program_type':program_type})

MessageSubmission(models.Model)类:

message = models.CharField(max_length=5000)
author = models.ForeignKey(User, on_delete=models.CASCADE)
date_posted = models.DateTimeField(default=timezone.now)
program_code = models.ManyToManyField(Program)
program_type = models.CharField(max_length=30, blank=True)
product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True)
production_cycle = models.ManyToManyField('ProductionCycle', null=True)

def get_absolute_url(self):

    return reverse('submission-list')

def __str__(self):

    return self.message

2 个答案:

答案 0 :(得分:1)

在视图中执行此操作没有错。如果未在这些if语句之后定义表单,则意味着product的值不是AppleOrange,而是其他。我会仔细检查product的值以解决此问题。


由于Product是一个类,因此您应该引用一个字段。您没有发布代码,例如

if form == product.name

如果有一个name字段。

答案 1 :(得分:1)

正如我在评论中提到的那样,问题是product是另一个模型的ForeignKey。在模板中,FK将使用该模型的__str__方法显示,但这并不能使其等于显示值。您应该与目标模型上的相关字段进行显式比较:

if product.fruit_type == 'Orange'   # or whatever the field is

(或者,您可以做if str(product) == 'Orange',但这比较脆弱,并且以不太好用的方式耦合显示逻辑。)