Modifying the request.POST data that is received from a form; form is not getting validated then

35 views
Skip to first unread message

Anurag Baidyanath

unread,
Jun 10, 2014, 7:25:10 AM6/10/14
to django...@googlegroups.com
i am having difficulty in saving the form data to the database.

After the user submits the form; fields such as ticket_id , created_date, etc have to be added to the POST request which is generated as a result of the form submission. I have copied the POST data to another dictionary and appended the other fields. The form isn't getting validated when the is_valid() fn is called.

i am attaching the submit function in the views.py file and the forms.py file


def submit(request):
                context=RequestContext(request)
                if(request.method=="POST"):
                    print request.POST
                    print "________________________\n"
                    data = request.POST.copy()
                    #data=request.POST
                   
                    print "\n"
                    print request.user.email
                    data['created_date_time']=datetime.datetime.now()
                    data['overdue_date_time']=datetime.datetime.now()
                    Date=datetime.datetime.now()
                    Enddate=Date+datetime.timedelta(days=1)
                    data['overdue_date_time']=Enddate
                    data['closed_date_time']=Enddate
                    data['status']=0 # 0 means that the ticket is still open and not yet answered
                    data['reopened_date_time']=Enddate
                    data['topic_priority']=2 # 2 is the default priority of medium
                    data['duration_for_reply']=24 #in hours
                    if request.user.is_authenticated():
                        print request.user
                        data['user_id']=request.user.email
                        #returns a user object if the user is logged in. @login_required is thus necessary
                    else:
                        return HttpResponse("you need to be a valid user to submit a ticket. click <a href=''>here</a> to go to the login page")
#let the help topic remain the same
                    #category_selected=data['help_topic']
                    #data['help_topic']=Category.objects.get(category="android")#category_selected)#get is used to get a single object
                    from django.db.models import Max
                    last_ticket=int(Ticket.objects.all().aggregate(Max('ticket_id'))['ticket_id__max'])
                    data['ticket_id']=last_ticket+1
                    #if 'submit' in data: del data['submit']
                    #if 'csrfmiddlewaretoken' in data: del data['csrfmiddlewaretoken']
                   
                    #user_form=SubmitTicketForm(data)
                    print data
                    user_form=SubmitTicketForm(data)
                    #how to validate the form for yourself
                    if user_form.is_valid():
                     print user_form.cleaned_data
                  #   user_form=Ticket.objects.set(topic_id=data['user_id'])
                     user_form.save()
                     return HttpResponse("Saved successfully")
                    #else:
                     # print data
                      # return HttpResponse("Saved unsuccessfully")
                       # print "the errors are"
                        # print user_form.errors
                else:
                     user_form=SubmitTicketForm()
                     return render_to_response(
                        'submit.html',
                        {'user_form': user_form},
                        context)

from user_tickets.models import *
from django import forms
from django.contrib.auth.models import User
import datetime
from datetime import timedelta
from django.db.models import Max
class SubmitTicketForm(forms.ModelForm):
    status=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
    topic_priority=forms.IntegerField(widget=forms.HiddenInput(),initial=2)
    duration_for_reply=forms.IntegerField(widget=forms.HiddenInput(),initial=24)
    ticket_id=forms.IntegerField(widget=forms.HiddenInput(),initial=786)#(int(Ticket.objects.all().aggregate(Max('ticket_id'))['ticket_id__max']))+1)
    created_date_time=forms.DateTimeField(widget=forms.HiddenInput(),initial=datetime.datetime.now())
    overdue_date_time=forms.DateTimeField(widget=forms.HiddenInput(),initial=datetime.datetime.now())
    closed_date_time=forms.DateTimeField(widget=forms.HiddenInput(),initial=datetime.datetime.now())
    reopened_date_time=forms.DateTimeField(widget=forms.HiddenInput(),initial=datetime.datetime.now())
    class Meta:
        model=Ticket
        fields=('user_id','topic_id','message','ticket_id','status','topic_priority','duration_for_reply','created_date_time','overdue_date_time','closed_date_time','reopened_date_time')
        #'created_date_time','overdue_date_time','closed_date_time','reopened_date_time',
       

Daniel Roseman

unread,
Jun 10, 2014, 8:53:42 AM6/10/14
to django...@googlegroups.com
On Tuesday, 10 June 2014 12:25:10 UTC+1, Anurag Baidyanath wrote:
i am having difficulty in saving the form data to the database.

And we are having difficulty reading your code. If you can't be bothered to clean it up enough (eg removing all the commented-out lines) to make it easy to read before posting your question, you'll not find many people that can be bothered to answer it.

Also, you should read the very useful documentation on using a form in a view (https://docs.djangoproject.com/en/1.6/topics/forms/#using-a-form-in-a-view) and compare it with your view code, which might give you a hint as to where you are going wrong.
--
DR.

Anurag Baidyanath

unread,
Jun 10, 2014, 1:00:54 PM6/10/14
to django...@googlegroups.com
sorry for the unreadable code!
I have cleaned it up as suggested and posted it below.

the user is displayed only email,subject,help_topic and message fields. rest all the fields are hidden. when the form is submitted; in the submit_ticket() in views.py i have copied the request.POST into a dictionary and have overwritten the blank values which were in the POST request with dynamically generated values.

interestingly, The form validates now but upon save i get blank values in the database, i.e. values for all the fields are blank!

Please help me out.
P.S. earlier the form was not getting validated due to reasons i am ignorant with


i am attaching the submit function in the views.py file and the forms.py file

forms.py file



from django import forms
from django.contrib.auth.models import User
from ac.models import UserProfile, Category
import datetime
from ac.models import *
from datetime import timedelta
class SubmitTicketForm(forms.ModelForm):
                email=forms.EmailField(max_length=128,help_text="please enter your email address")
                ticket_id=forms.IntegerField(widget=forms.HiddenInput())
                subject=forms.CharField(max_length=100,help_text="subject")
                help_topic=forms.ChoiceField(choices=[(x['category'], str(x['category'])) for x in Category.objects.values('category')],help_text="please enter the category of your problem")
                message=forms.CharField(max_length=500,help_text="message")
                created_date_time=forms.DateTimeField(widget=forms.HiddenInput())
                overdue_date_time=forms.DateTimeField(widget=forms.HiddenInput())
                closed_date_time=forms.DateTimeField(widget=forms.HiddenInput())
                status=forms.IntegerField(widget=forms.HiddenInput())
                reopened_date_time=forms.DateTimeField(widget=forms.HiddenInput())
                topic_priority=forms.IntegerField(widget=forms.HiddenInput())
                duration_for_reply=forms.IntegerField(widget=forms.HiddenInput())
                class Meta:
                        model=Ticket#all the fields are included
                        fields=('email','subject','help_topic','message')


view where the form is handled


def submit(request):
                context=RequestContext(request)
                if(request.method=="POST"):
                    data = request.POST.copy()

                    print "\n"
                    print request.user.email
                    data['created_date_time']=datetime.datetime.now()
                    data['overdue_date_time']=datetime.datetime.now()
                    Date=datetime.datetime.now()
                    Enddate=Date+datetime.timedelta(days=1)
                    data['overdue_date_time']=Enddate
                    data['closed_date_time']=Enddate
                    data['status']=0 # 0 means that the ticket is still open and not yet answered
                    data['reopened_date_time']=Enddate
                    data['topic_priority']=2 # 2 is the default priority of medium
                    data['duration_for_reply']=24 #in hours
                    if request.user.is_authenticated():
                        print request.user
                        data['user_id']=request.user.email
                    else:
                        return HttpResponse("you need to be a valid user to submit a ticket. click <a href=''>here</a> to go to the login page")t

                    from django.db.models import Max
                    last_ticket=int(Ticket.objects.all().aggregate(Max('ticket_id'))['ticket_id__max'])
                    data['ticket_id']=last_ticket+1
                    user_form=SubmitTicketForm(data)
                    if user_form.is_valid():

                         user_form.save()
                         return HttpResponse("Saved successfully")
                    else:

                          return HttpResponse("Saved unsuccessfully")
                          print user_form.errors
                else:
                     user_form=SubmitTicketForm()
                     return render_to_response(
                        'submit.html',
                        {'user_form': user_form},
                        context)

the model upon which the form is based

class Ticket(models.Model):
    user_id=models.EmailField()
    topic_id=models.CharField(max_length=100,help_text="enter topic id")
    message=models.TextField()
    ticket_id=models.IntegerField()
    file_uploads=models.FileField(upload_to='tickets/file' , blank=True)
    created_date_time=models.DateTimeField(auto_now_add=True)
    overdue_date_time=models.DateTimeField(auto_now_add=True)
    closed_date_time=models.DateTimeField(auto_now_add=True)
    status=models.IntegerField()
    reopened_date_time=models.DateTimeField(auto_now_add=True)
    topic_priority=models.IntegerField()
    duration_for_reply=models.IntegerField()
        def __unicode__(self):
        return unicode(self.user_id)
Reply all
Reply to author
Forward
0 new messages