views:

56

answers:

1

In my view for editing friends I'm checking if form is valid, and then save the form. But somehow the data are not updated. Why my updated form is not saved ? It is 100% valid, since I've checked it earlier.

My form :

class FriendForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), label="First name")
    last_name = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), label="Last name")
    pid = forms.RegexField(regex=r'^\d{11}', max_length=11 ,widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)))
    image = forms.ImageField(label="Image", required=False)
    street = forms.CharField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=50)), label="Street")
    number = forms.CharField(widget=forms.TextInput, label="House/flat number")
    code = forms.RegexField(regex=r'^\d{2}[-]\d{3}', max_length=6, widget=forms.TextInput(attrs=attrs_dict), label="Postal code")
    city = forms.CharField(widget=forms.TextInput, label="City")

The view :

def edit_friend(request, id):
    userprofile = UserProfile.objects.get(user=request.user)
    friend = get_object_or_404(Friend, id=id)
    if friend.friend_of.id!=userprofile.id:
        raise Http404 
    if request.method == 'POST':
        form = FriendForm(request.POST, request.FILES, instance=friend)
        if form.is_valid(): 
            form.save()           
        return HttpResponseRedirect(reverse('user_profile',))
    else:
        form = FriendForm(instance=friend)
    return render_to_response('user/data_operations/edit_friend.html', {
            'form':form, 'user':request.user,
            }, context_instance=RequestContext(request))

Template :

<form method="post" action="." enctype="multipart/form-data">
    <table>           
        {{ form.as_table }}
        <tr>
            <td>&nbsp;</td>
            <td>
                <input type="submit" class="submit" name="submit" value="Save" />
            </td>
        </tr>
    </table>
</form>
+1  A: 

I'd need to see the full code for your form to really answer this (can you include it?) but here are some initial thoughts:

Is FriendForm a subclass of django.forms.ModelForm? If so, there's no need to override the save method -- especially since all you're doing here is getting the returned new object, saving it (again), and returning it (again) -- additional processing with no additional benefit.

If FriendForm isn't a subclass of ModelForm, how is it bound to database data? What class is it inheriting from?


UPDATE:
ModelForms aren't connected directly to the database -- they are a shortcut for creating HTML forms for interacting with database models -- i.e. classes inheriting from django.models.Model. You do that by creating a Meta class within your ModelForm.

With a ModelForm, you don't need to manually specify the fields (django does that automatically for you) unless you want to override specific behaviors. You do have to tell django which database Model you're like to use. If you've already defined a database Model, use it; if not, try this:

# in models.py
from django import models

class Friend(models.Model):
    first_name = models.CharField( "see <http://docs.djangoproject.com/en/dev/ref/models/fields/&gt; to adjust your syntax" )
    ... your other fields ...


# in forms.py
from django.forms import ModelForm
from my_project.my_app.models import Friend

class FriendForm(ModelForm):
    class Meta:
        model = Friend

That's it! Now your FriendForm should work properly. See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/ for more information on using ModelForms.

Alternatively, you don't need to use a ModelForm at all. You could add the following save method to your existing FriendForm:

def save(self):
    if self.is_valid():
        from myproject.myapp.models import Friend
        new_friend = Friend(**self.cleaned_data)
        new_friend.save()
        return new_friend

... the essence here is that you're importing the Friend model, which encapsulates the database storage behaviors. This is basically what the ModelForm creates automatically for you, but not as robust -- so I recommend using ModelForm.

Benj
The first solution doesn't change anything. Still updated data are not saved. With second solution problem is that in edit mode I'm not able to send instance to form since it's not a ModelForm.
muntu
I have an updated question with both methods : http://stackoverflow.com/questions/3169274/forms-for-instances-not-saved
muntu