Saving data from ModelForm
Asked Answered
M

1

2

I am new to Django and I'm trying to save data using ModelForm. Template 'Vlozit' has a ModelForm and when submitted, I want the data saved in the DB and the redirect to base.html that actually loads the data from the DB and lists the output. The problem is that all works fine but the data is not saved. Please help me find what I am missing. Thank you.

Here's the model:

class Customer(models.Model):
    Name = models.CharField(max_length=30)
    Description = models.CharField(max_length=150)
    Creation_Date = models.DateField(default=datetime.now)
    Active = models.BooleanField(default=False)

def __unicode__(self):
    return self.Name

Customers = models.Manager()

Here's the ModelForm:

class CustomerForm(forms.ModelForm):
    Description = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Customer

Here's the view:

def vlozit(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=Customer)
        if form.is_valid():
            form.save(True) 
            return HttpResponseRedirect(reverse('Base.html'))
    else:
        form = CustomerForm()
        return render_to_response("Vlozit.html", {'form': form}, context_instance = RequestContext(request))

Here's the template 'Vlozit':

{% extends "base.html" %}

{% block head %}
    {{ form.media }}
    <script>
        $(function() {
            $( "#id_Creation_Date" ).datepicker();
        });
    </script>
{% endblock %}

{% block title %}{{block.super}} - Vlozit{% endblock %}
{% block content %}
<div id="content">
    <form method="POST" action="{% url url_home %}">
    {% csrf_token %}
        <table>
            <tr>
                <td>Name</td>
                <td>{{ form.Name }}</td>
            </tr>
            <tr>
                <td>Description</td>
                <td>{{ form.Description }}</td>
            </tr>
            <tr>
                <td>Creation Date</td>
                <td>{{ form.Creation_Date }}</td>
            </tr>
            <tr>
                <td>Active</td>
                <td>{{ form.Active }}</td>
            </tr>
        </table>
        <input type="submit" value="Vlozit">
    </form>
</div>
{% endblock content %}
Merited answered 24/10, 2012 at 9:34 Comment(3)
Are you sure that the form is validating? It looks like you haven't added any code to your template to display errors to it's likely that the is_valid is silently failingBenally
Add {{ form.Name.errors }} below {{ form.Name }} so that you will be able to see the errors and make sure that the form is being validated.Faruq
How can I display errors on the page? I am actually redirected to the base.html and that is only done after form validation which seems to result True. if the validation failed, I would expect to actually stay in the 'Vlozit.html' page.Merited
S
3

As Timmy says in the comments, you don't catch the case where the form is not valid. Not only do you not show errors in the template, but you also don't even redisplay the template if form.is_valid() is False. Move the last line of the view back one indentation level, and add {{ form.errors }} to the template.

Seawright answered 24/10, 2012 at 9:46 Comment(7)
I did what you advised but the form is still not saving anything.Merited
How are you determining that?Seawright
Could it be somehw relateed to the form action: <form method="POST" action="{% url url_home %}"> ? Maybe the request is just redirected and not really processed thorugh the view... ?Merited
I am looking into the DB through the admin to see if there is a new entry.Merited
Er, well, yes. If your view is posting to the home page instead of the form view, then naturally it won't get processed. The usual thing to do is just action="." to post back to the same URL for processing.Seawright
I changed the action to "." and now I am getting an error: Reverse for 'Base.html' with arguments '()' and keyword arguments '{}' not found.Merited
Yes, that's because you have that wrong in your view. I presume you mean to put reverse('url_home') there, like you had in the template.Seawright

© 2022 - 2024 — McMap. All rights reserved.