Django ModelForm排除数据保存

时间:2018-03-03 14:17:36

标签: django

尝试使用登录用户保存数据。试过如下。

models.py

class MyModel(TimeStamped):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    title = models.CharField(max_length=250)

forms.py

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        exclude = ['user']

views.py

def add(request):
    if request.method == 'GET':
        form = MyForm()
    else:
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=False)
            form.save()
            messages.success(request, 'Message Sent Successfully')
            redirect('home')
    return render(request, "add.html", {'form': form})

它保存了数据。但问题是用户没有设置登录用户。尝试在视图form.user = request.user中添加。仍然没有储蓄。

1 个答案:

答案 0 :(得分:0)

试试这个。

def add(request):
    if request.method == 'GET':
        form = MyForm()
    else:
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            messages.success(request, 'Message Sent Successfully')
            redirect('home')
    return render(request, "add.html", {'form': form})