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)