Adding values to formdata of ModelForm before saving

3,331 views
Skip to first unread message

Schmidtchen Schleicher

unread,
May 30, 2012, 4:56:58 PM5/30/12
to django...@googlegroups.com
Is it possible to put missing data into the data of a form before calling form.save() ?
I want to add the calendar-id (calid/in_calendar) before saving to the model.

 http://susepaste.org/23451355

I tried adding it after instantiating the form with form.in_calendar_id = kalender but it didn't work
I don't want to use hidden fields because manipulating them is easy

Maybe https://groups.google.com/forum/?fromgroups#!topic/django-users/F5yHH-G5QLM describes how to solve it but I didn't understand it.

PS: If you find very ugly code please correct me -- I'm a beginner

Jonathan Baker

unread,
May 30, 2012, 5:03:49 PM5/30/12
to django...@googlegroups.com
Yes, it is possible:

obj = form.save(commit=False)
obj.in_calender-id = kalender
obj.save()



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/v0GYTeLYPAsJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



--
Jonathan D. Baker
Developer
http://jonathandbaker.com

Schmidtchen Schleicher

unread,
May 31, 2012, 2:09:05 PM5/31/12
to django...@googlegroups.com
Thank you for your quick answer, but it doesn't really work. It raises the exception "can't assign to operator"
My view now looks like this:

@login_required
def create_termin(request, calid, year=None, month=None, day=None):
    kalender = get_object_or_404(Kalender,pk=int(calid))
    if request.method == "POST":
        print(request.POST)
        form = NewTerminForm(request.POST)

        if form.is_valid():
            formdata = form.cleaned_data
            if formdata['participants']:
                form.participants = request.user.id
            form.save(commit=False)
            form.in_calendar-id = kalender
            form.save()
            return HttpResponse(pprint.pformat(formdata) + pprint.pformat(inspect.getmembers(form['participants'])) + "\n\n" + pprint.pformat(inspect.getmembers(request.user)),mimetype="text/plain")

    else:
        date = datetime.date(month=int(month), day=int(day), year=int(year)) if day else None
        print("viewdate",date)
        form = NewTerminForm(initial={'date':date,})
    return render_to_response("kalender/new_termin.html", dict(debug=1, calid=calid,form=form, ),context_instance=RequestContext(request))

Am Mittwoch, 30. Mai 2012 23:03:49 UTC+2 schrieb jondbaker:
Yes, it is possible:

obj = form.save(commit=False)
obj.in_calender-id = kalender
obj.save()


On Wed, May 30, 2012 at 2:56 PM, Schmidtchen Schleicher <spiol...@googlemail.com> wrote:
Is it possible to put missing data into the data of a form before calling form.save() ?
I want to add the calendar-id (calid/in_calendar) before saving to the model.

 http://susepaste.org/23451355

I tried adding it after instantiating the form with form.in_calendar_id = kalender but it didn't work
I don't want to use hidden fields because manipulating them is easy

Maybe https://groups.google.com/forum/?fromgroups#!topic/django-users/F5yHH-G5QLM describes how to solve it but I didn't understand it.

PS: If you find very ugly code please correct me -- I'm a beginner

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/v0GYTeLYPAsJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

bruno desthuilliers

unread,
May 31, 2012, 8:23:34 PM5/31/12
to Django users
On 31 mai, 20:09, Schmidtchen Schleicher <spiolli...@googlemail.com>
wrote:
> Thank you for your quick answer, but it doesn't really work. It raises the
> exception "can't assign to operator"
> My view now looks like this:
>
> @login_required
> > def create_termin(request, calid, year=None, month=None, day=None):
> >     kalender = get_object_or_404(Kalender,pk=int(calid))

You don't need the int conversion here

> >     if request.method == "POST":
> >         print(request.POST)
> >         form = NewTerminForm(request.POST)
>
> >         if form.is_valid():
> >             formdata = form.cleaned_data
> >             if formdata['participants']:
> >                 form.participants = request.user.id
> >             form.save(commit=False)
> >             form.in_calendar-id = kalender

"in_calendar-id" is not a valid Python identifier. It's parsed as
"form.in_calendar - id = kalender"

Kurtis Mullins

unread,
May 31, 2012, 8:47:11 PM5/31/12
to django...@googlegroups.com
Hey,

I tried re-writing your view and form for you -- but I ran into a snag. I don't read German so other than code-wise (and a couple of obvious words, like kalender and participants) I'm not really sure what you're trying to accomplish.

I do see one obvious issue, though. Participants is a many-to-many field in your Model and you're also using the same attribute in your form. Here's something you could try in your form and view:

View:
--------
if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        form.save(request)

Form:
---------
def save(self, request, kalender, commit=True):

    # Get an Instance of the Termin object.
    obj = super(Termin, self).save(commit=True)
  
    # Add the user as a participant if 'add_me' = True
    if self.cleaned_data['add_me']:
        obj.participants.add(request.user)

    # Set the Calendar, Save, and return
    obj.in_calendar = kalender
    obj.save()
    return obj

Hopefully I didn't just confuse you more :) Good luck!

Kurtis Mullins

unread,
May 31, 2012, 8:48:04 PM5/31/12
to django...@googlegroups.com
One minor edit to that:
form.save(request) -> form.save(request, kalender)

Schmidtchen Schleicher

unread,
Jun 1, 2012, 12:03:23 PM6/1/12
to django...@googlegroups.com
Thank you for your effort, as far as I can see you understood my problem right and your solution could work... if there wouldn't be that error:

TypeError at /kalender/1/new_termin/

super(type, obj): obj must be an instance or subtype of type

Termin is a model class, NewTerminForm is a modelformclass (Termin is german for appointment). This is the first time I use super() so I don't know how to solve this problem

Peter of the Norse

unread,
Jun 4, 2012, 12:29:18 AM6/4/12
to django...@googlegroups.com
Super is one of python’s greatest mistakes. http://docs.python.org/library/functions.html#super The form is
class class_name(parent_class):
    def method(self, *args, **kwargs):
        super(class_name, self).method(*args, **kwargs)

It’s better in Python 3, but Django hasn’t been ported over yet.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/WyKASDjYNEgJ.

To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Peter of the Norse



Reply all
Reply to author
Forward
0 new messages