如何添加信息到request.POST? [英] How to add info to request.POST?

查看:90
本文介绍了如何添加信息到request.POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户使用表单创建内容时,所有信息都通过表单提交,该表单通过AJAX调用发送到以下视图:

When a user creates something using a form, all of the info is submitted through a form which is sent through an AJAX call to the following view:

def goal_create(request):
  if request.method == 'POST':
    user = request.user
    request.POST[user] = user.id
    errors = form_validate(request, AddGoalForm, Goal)

尝试时出现错误修改request.POST字典并将用户的ID添加到模型实例。我想添加它,所以在下一步(当它进入form_validate时),它将为我创建一个新的模型实例。
这是form_validate,它根据ModelForm验证表单。

I get an error when I try to modify request.POST dict and add a user's id to the model instance. I want to add it, so in the next step (when it goes to form_validate), it will create a new model instance for me. Here is form_validate, which validates the form according to a ModelForm.

def form_validate(request, form, model):
  form = form(request.POST)
  if form.is_valid():
    new = form.save()
  else:
    return form.errors.items()

这是我正在使用的模型:

Here is the model I'm working with:

class Goal(models.Model):
  goal_name = models.CharField(max_length=200, blank=False)
  user =  models.ForeignKey(User, null=True, blank=True)
  created_at = models.DateField(auto_now_add=True)
  updated_at = models.DateField(auto_now=True)

另一个问题是,即使goal_name的属性为blank = False,并且我用空的goal_name创建了一个新目标,但它表示形式为is_valid( )并保存表单。

Another issue is that even though goal_name has attribute blank=False, and I create a new goal with a blank goal_name, it says that the form is_valid() and saves the form.

推荐答案

    if request.method == 'POST':

        user = request.user
        post_values = request.POST.copy()

        post_values['user'] = user.id
        form = MyForm(post_values)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('success'))
        return HttpResponseRedirect(reverse('error'))

ps 这是一种快速解决方法,但不是一种非常优雅的使用方法。虽然什么时候使用这个都没有问题

p.s This is a quick fix but not a very elegant method to use. Though there are no issues when you would use this

这篇关于如何添加信息到request.POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆