How create a custom form in django with database v

2019-07-23 20:23发布

问题:

model.py

class Venue(models.Model):
    venue_Name = models.CharField(max_length=100)
    place = models.CharField(max_length=50)
    rent = models.IntegerField()
    parking_area = models.IntegerField()


class Decoration(models.Model):
    rate = models.IntegerField()

I have printed the values in database as radio buttons what i want to do is that i want to get the total sum i.e venue.rent + decoration.rate and print it in another page What shoud i give in form action I'm not that familiar with forms.

html

 <form action="{%  %}" method="post">
 {% for venue in venues %}
 <input type="radio" name=venue value=venue.rent />{{  venue.venue_Name}}
 {% endfor %}

{% for decoration in decorations %}
<input type="radio" name=decor value=decoration.rate />{{  decoration.rating }}
{% endfor %}
<input type="submit" value=" " />
</form>

what should i write in view and urls to get the sum

回答1:

You can use Django's form for validation and parsing. For that you would set up a form like so:

forms.py

from django import forms

class TotalSumForm(forms.Form):
    venue = forms.ModelChoiceField(queryset=Venue.objects.all(), required=True)
    decoration = forms.ModelChoiceField(
        queryset=Decoration.objects.all(), required=True)

    def get_total(self):
        # send email using the self.cleaned_data dictionary
        return self.cleaned_data['venue'].rent +\
               self.cleaned_data['decoration'].rate

And then using a class based view, add the result to context upon submission.

views.py

from myapp.forms import TotalSumForm(
from django.views.generic.edit import FormView

class TotalCost(FormView):
    template_name = 'your_template.html'
    form_class = TotalSumForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        total_result = form.get_total()
        # return back to your_template.html with the total in context
        return self.render_to_response(self.get_context_data(
            form=form, total=total_result))

The urls are pretty simple:

urls.py

from django.conf.urls import patterns, url

import myapp.views

urlpatterns = patterns(
    '',
    url(r'^total_calc/$', myapp.views.TotalCost.as_view(), name='calculate_total'),
)

Your html could be modified like so

your_template.html

<html>
    <body>
        <h1>TEST SUCCESFULL!</h1>
            {% if total %}
        <p>Total cost for venue and decoration: {{ total }}</p>
    {% endif %}
        <form action="{% url 'calculate_total' %}" method="post">
            {{ form.as_p }}
            <input type="submit" value="Calculate Total" />
        </form>
    </body>
</html>