0

I am saving a form which has a random value generated for one of the field. I also have a manyToMany relation which can be null. What i want to accomplish is, to save the form when it is generated, and later retrieve it to update it.

When i save the form with the admin console, it does let me save without adding anything to it, because for all of my fields for the model have null=True and blank=True.

views.py

def event(request):
    if request.POST:
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
            del request.session['event_id']
            return HttpResponseRedirect('....')
    else:
        event_session = request.session.get('event_id')
        if event_session is not None:
            event_instance = EiEventType.objects.get(eventID = event_session)
            form = EiEventForm(instance=event_instance)
            form.save(force_update=True)
        else:
            form = EventForm()
            form.save()
            request.session['event_id'] = form['eventID'].value()
    args = {}
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('.....',args)

I tried with form.is_valid in the else code when i create a new form instance, but it doesn't enter the if condition itself (though not mentioned in the code).

With the current code it returns the error. "EventForm object has no attribute cleaned_data" but saves to the database..When I post(request.POST) with nothing in the form it does save flawlessly, I am not able to understand why is this the case ?

UPDATE: forms.py

class EventForm(forms.ModelForm):
    class Meta:
        model = EiEventType

models.py

class Event(models.Model):
    eventID = models.CharField(null=True,blank=True,default=random_eventID)
    start = models.DateTimeField(null=True, default=two_min_from_now)
    signal = models.ManyToManyField(Signal,null=True)
    ...
    ...
    ...

The random function is as defined below,

def random_eventID()
    return "event_" + str(uuid.uuid4())[:5]

def two_min_from_now()
    return datetime.datetime.now() + timedelta(minutes=2)
Akshay
  • 329
  • 1
  • 7
  • 19

2 Answers2

0

You cannot call form.save() unless you first call form.is_valid().

jproffitt
  • 6,225
  • 30
  • 42
  • I know it doesn't allow. I did mention in the question. i tried it with form.is_valid but it does not enter the "if" loop. What can be the reason for that ? – Akshay Oct 17 '13 at 04:49
  • Have you looked into what it does not pass the is_valid check? What's in `form.errors` after the check? – jproffitt Oct 17 '13 at 11:54
  • @jpproffitt It does say that some fields are required. But i have already initialized those fields with default values..then why does it still return False ? – Akshay Oct 17 '13 at 17:31
  • Good question. Could you post your form class and your model so I can take a look? – jproffitt Oct 17 '13 at 20:42
  • Have you tried adding `blank=True` to the model fields? That will allow blank values to be in the form. Read this for more details: http://stackoverflow.com/questions/8609192/differentiate-null-true-blank-true-in-django – jproffitt Oct 17 '13 at 23:40
  • Yes i have tried that as well. I forgot to mention in the code for the signal (the many-to-many field), i have blank=True as well..But i don't understand why is this happening...Do you think that if i have my m2m field as blank=True, it should give me the error, cleaned_data = form.cleaned_data ?? – Akshay Oct 17 '13 at 23:51
  • What are the actual error message you get after calling `is_valid()`. I know for sure you need to call `is_valid()` before calling `save()`. you need to just figure out why the validation is failing, and fix that. – jproffitt Oct 18 '13 at 00:10
  • Well, that's weird when i do if `form.is_valid():` it does not enter the loop, and outside the loop i print `form.errors` it displays an empty dictionary :/ – Akshay Oct 18 '13 at 00:29
  • What loop? You mean the if statement? I have no idea why it would be doing that. If I were you, I would step into the `is_valid()` with a debugger to see what's going on. – jproffitt Oct 18 '13 at 00:36
0

You have a form.save() method call with no data bound to the form:

    else:
        form = EventForm()
        form.save()
        request.session['event_id'] = form['eventID'].value()

Hence, as it's a modelform, it looks for the cleaned data, but it doesn't exist.

professorDante
  • 2,290
  • 16
  • 26
  • How can i save the form then as soon as i generate it ? What data can i pass it...I want to be able to store the form with whatever is already filled in the form..and later retrieve to update it..Any ideas on how should i proceed ? – Akshay Oct 17 '13 at 06:29
  • Why save a form with nothing in it? To save data entered in a form and retrieve it later, you need a model and a model form. It's all in the docs. – professorDante Oct 17 '13 at 15:44
  • Oh yes I know that, and i do have a model and a modelform is the one that I am using..the form has a random value for one of the fields, when I enter some data in the form and go to another page I want all the data to persist when I return to that page again. So, i wanted to save whatever is there in the form when i click on the link. I hope this helps! – Akshay Oct 17 '13 at 16:45
  • Is there a reason you dont have a field in the model to store this random value then? You can choose to display it or not when you return to the page. I'm not sure I see the problem here... – professorDante Oct 17 '13 at 17:21
  • Well i am storing the value in the field 'eventID', but the value changes everytime i return to the page ( which is what i don't want it to happen)...it is more like a form where you click on a link and when you come back, i want all the data entered, as it is there in the form so that i can continue updating the form. – Akshay Oct 17 '13 at 17:26