Django中未设置初始表单字段

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

Initial form field doesn't set in Django

问题

我有以下设置。

模型:

class Feedbacks(models.Model):
    user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    feedback = models.TextField()
    rating = models.IntegerField()

表单:

class FeedbackModelForm(ModelForm):
    class Meta:
        model = Feedbacks
        exclude = ['user_id']

视图:

@login_required
def feedbackPage(request):
    username = request.user.id
    if request.method == 'POST':
        form = FeedbackModelForm(request.POST, initial={'user_id': username})
        if form.is_valid():
            form.save()
            return redirect('feedback_success')
    else:
        form = FeedbackModelForm()

    context = {'form': form}
    return render(request, 'feedback.html', context)

打印(username)显示当前已认证用户的ID。

在保存过程中,它不会保存user_id字段(它是NULL)。

我需要从已认证的用户中保存user_id字段。

英文:

I have following set up.

Model:

class Feedbacks(models.Model):
    user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    feedback = models.TextField()
    rating = models.IntegerField()

Form:

class FeedbackModelForm(ModelForm):
    class Meta:
        model = Feedbacks
        exclude = ['user_id']

View:

@login_required
def feedbackPage(request):
    username = request.user.id
    if request.method == 'POST':
        form = FeedbackModelForm(request.POST, initial={'user_id': username})
        if form.is_valid():
            form.save()
            return redirect('feedback_success')
    else:
        form = FeedbackModelForm()

    context = {'form': form}
    return render(request, 'feedback.html', context)

Print(username) shows current current authenticated user ID.

During the save procedure it doesn't save user_id field (it's NULL).

I need that user_id field saved from authenticated user.

答案1

得分: 2

看起来问题出在你在视图函数中创建对象时如何设置用户ID。你的代码将一个名为 'user_id' 的表单设置为来自请求对象的用户ID,但这样做是行不通的,因为在你的 FeedbackModelForm 类中已经排除了 'user_id'。

尝试直接在对象上设置 user_id 字段,然后手动保存它,而不是尝试为表单设置初始值。像这样:

views.py

@login_required
def feedbackPage(request):
    if request.method == 'POST':
        form = FeedbackModelForm(request.POST)
        if form.is_valid():
            feedbackObj = form.save(commit=False)  # commit=False 意味着表单尚未保存到数据库中
            feedbackObj.user_id = request.user  # 将用户设置为当前用户
            feedbackObj.save()  # 将表单保存到数据库中
            return redirect('feedback_success')
    else:
        form = FeedbackModelForm()

这应该解决问题。(至少,我认为会的)

英文:

It looks like the issue is how you are setting the user id when you create the object in your view function. Your code is setting a form called 'user_id' to the user id from the request object but that won't work because you have already excluded 'user_id' in your FeedbackModelForm class.

Instead of trying to set an initial value for the form, try setting the user_id field on the object directly and then saving it manually. Like so:

views.py

@login_required
def feedbackPage(request):
    if request.method == 'POST':
        form = FeedbackModelForm(request.POST)
        if form.is_valid():
            feedbackObj = form.save(commit=False)  # commit=False means that the form is not saved to the database yet
            feedbackObj.user_id = request.user  # set the user to the current user
            feedbackObj.save()  # save the form to the database
            return redirect('feedback_success')
    else:
        form = FeedbackModelForm()

That should fix the issue. (well at least, I think it will)

huangapple
  • 本文由 发表于 2023年6月26日 18:36:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555884.html
匿名

发表评论

匿名网友

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

确定