在Django提交表单时如何传递当前登录的用户?

时间:2019-07-05 07:33:31

标签: python django python-3.x django-2.2

我正在尝试创建一个表单,该表单允许当前登录的用户提交数据。 该表单包含以下字段:金额,利率(利息),时间戳(自动提取)和当前登录的用户。

数据没有传递到数据库中,并给出了类似的错误-视图Investors.views.InvestView没有返回HttpResponse对象。它返回None。

views.py

def InvestView(request):
    if request.method == 'GET':
        investment_form = InvestorsForm(request.user)
        context = {'investment_form': investment_form}
        return render(request, 'investors/form.html', context)
    if request.method == 'POST':
        investment_form = InvestorsForm(request.POST or None, instance=request.user)
        if investment_form.is_valid():
            amount = investment_form.cleaned_data['amount']
            interest = investment_form.cleaned_data['rate']
            saving = investment_form.save(commit=False)

            # Passing Logged in user
            investor = request.user
            print(investor)
            saving.investor = request.user.id
            saving.save()
            messages.success(request, f'New Investment Done!')
            return redirect('/myinvest/')

forms.py

class InvestorsForm(forms.ModelForm):

    class Meta :
        model = Investment
        fields = ['amount', 'rate']

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(InvestorsForm, self).__init__(*args, **kwargs)

models.py

class Investor(models.Model):  
    name = models.CharField(max_length=99) 
    user = models.ForeignKey(User, on_delete=models.CASCADE)


    def __str__(self):
        return self.name


class Investment(models.Model):
    amount = models.FloatField(blank=False)
    rate = models.FloatField(blank=False)
    timestamp = models.DateField(default=datetime.now)
    investor = models.ForeignKey(Investor, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.investor)

必须将数据存储到数据库中,并将页面同时重定向到myinvest节。

4 个答案:

答案 0 :(得分:2)

此问题与添加用户无关。这是因为在验证失败的情况下您什么也不做。

您应该反方向旋转函数,以便在所有情况下都可以渲染。

def InvestView(request):
    if request.method == 'POST':
        investment_form = InvestorsForm(request.POST)
        if investment_form.is_valid():
            saving = investment_form.save(commit=False)
            saving.investor.user = request.user
            saving.save()
            messages.success(request, f'New Investment Done!')
            return redirect('/myinvest/')
    else:
        investment_form = InvestorsForm()
    context = {'investment_form': investment_form}
    return render(request, 'investors/form.html', context)

注意缩进。

实际的验证失败是因为您已将表单的签名更改为首先接受user参数,而不是预期的data。但是,不清楚为什么要执行此操作,因为您不使用该值,而是在视图中设置用户。您应该删除__init__方法。

答案 1 :(得分:0)

如果表单无效,则首先显示investment_form错误。

 if investment_form.is_valid():
        ................
 else:
    return HttpResponse(investment_form.errors)

尝试一下:

saving.investor.user = request.user

答案 2 :(得分:0)

您需要将saving.investor = request.user.id替换为saving.investor.user = request.user

答案 3 :(得分:0)

另一个错误:表单的__init__方法将user作为其第一个参数:

def __init__(self, user, *args, **kwargs):

对于GET请求,您可以正确传递它:

investment_form = InvestorsForm(request.user)

但是随后有了POST请求,您就忘记了它:

investment_form = InvestorsForm(request.POST or None, instance=request.user)

将request.user用作第一个参数也应该有所帮助。