以表格形式获取当前用户

时间:2020-05-18 06:41:19

标签: django django-forms django-views

im尝试使用ForeignKey在表单字段中获取当前登录用户,但是im下拉菜单中列出数据库中的所有用户

view.py

@login_required
def user_request(request):

    if request.method == 'POST':
        form = UserRequest(request.POST or None)

        if form.is_valid():
            data = form.save(commit=False)
            data.user = request.user
            form.save()
            messages.success(request, 'Success')
            return redirect('home')
    else:
        form = UserRequest()
        print(form)
    context = {
        'form': form,
    }

    return render(request, 'users/request.html', context)

models.py

class UserRequestModel(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product_id = models.FloatField()
    email = models.EmailField()
    status = models.CharField(default='Pending', max_length=20)
    date = models.DateField()
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.user

form.py

class UserRequestForm(forms.ModelForm):

    class Meta:
        model = UserRequestModel
        fields = ['user']


class UserRequest(UserRequestForm):
    date = forms.DateField()
    product_id = forms.IntegerField()

    class Meta(UserRequestForm.Meta):
        fields = UserRequestForm.Meta.fields + ['date', 'product_id']

缺少当前用户而不是所有用户列表的即时消息是什么

1 个答案:

答案 0 :(得分:0)

ModelForm docs显示ForeignKey的默认字段类型为ModelChoiceField,这将在HTML中呈现<select>。这样可以选择单个模型对象。

如果您想保留所有用户的<select>并预先选择当前用户,则可以通过传递initial value在您的视图中进行此操作:

# Bound form
form = UserRequest(request.POST or None, initial={'user': request.user})
# Unbound form
form = UserRequest(initial={'user': request.user})

如果您想让表单字段为其他值(例如纯HTML <input>),且其值为当前用户ID,则您需要传递上述初始值,还需要传递{{ 3}}在您的forms.py中:

class UserRequest(UserRequestForm):
    date = forms.DateField()
    product_id = forms.IntegerField()

    class Meta(UserRequestForm.Meta):
        fields = UserRequestForm.Meta.fields + ['date', 'product_id']
        widgets = {
            'user': forms.TextInput(),
        }