Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add info to request.POST?

Tags:

python

django

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)

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)

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.

like image 772
egidra Avatar asked Jan 18 '23 06:01

egidra


1 Answers

    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'))

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

like image 92
Zain Khan Avatar answered Jan 25 '23 05:01

Zain Khan