[Django]-Django form for many-to-many model. How do I fill a form from views/template?

3๐Ÿ‘

โœ…

I managed to make it work.

For anyone in the future by accident googling and getting on this page here is what I did.

1.Changed the form of CategoryByDayForm so it accepts only status and excludes day and category

forms.py

from django import forms
from today.models import CategoryByDay, Category, Day

class CategoryByDayForm(forms.ModelForm):
    status = forms.CharField(max_length=64, initial="0")
    class Meta:
        model = CategoryByDay
        exclude = ['day', 'category']
  1. In the template, added hidden form input sending current category iteration:

today.html

#...
{% for category, form in category_form_list %}
                <li>                   
                    {{ category.name }}
                    <form action="" method="post">
                        {% csrf_token %}
                        {{ form.non_field_errors}}
                        <input type="hidden" value="{{ category.name }}" name="category">
                        <div class="status">
                            {{ form.status }}
                            <input type="submit" value="Submit" />
                        </div>
                    </form>
                </li>
            {% endfor %}
# ...

Finally, in views, I manipulated the form I got, so I added missing elements (from form I have status, I still need to set day and category)

views.py

def today(request):
    t = datetime.date.today().strftime("%d/%m/%y")
    day = Day.objects.filter(name=t)
    if request.method == 'POST':
            form = CategoryByDayForm(request.POST)
        if form.is_valid():
            category_status = form.save(commit=False)
            category_status.day = day[0]
            category_name = request.POST['category']
            category_status.category = Category.objects.filter(name=category_name)[0]
            category_status.save()
            form.save_m2m()

โ€ฆ

Hope that it can help someone in the future.

๐Ÿ‘คqnsi

1๐Ÿ‘

Another solution
views.py:

class ViewIndex(TemplateResponseMixin, View):
    template_name = 'frontend/view_index.html'

    def dispatch(self, request, *args, **kwargs):
       FS = modelformset_factory(CategoryByDay, extra=1)
       queryset = CategoryByDay.objects.filter(day__date=datetime.date.today())

       if request.method == 'POST':
           formset = FS(request.POST, request.FILES)

           if formset.is_valid():
               formset.save()
               formset = FS(queryset=queryset)

       else:
           formset = FS(queryset=queryset)


       return self.render_to_response({'formset':formset})

frontend/view_index.html:

{% extends 'base.html' %}
{% block content_main %}
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ formset.management_form }}
    {% for form in formset %}
       {{ form }}
       <hr/>
    {% endfor %}

    <input type="submit">
</form>
{% endblock %}

and urls.py

urlpatterns = patterns('',
   url(r'^$', ViewIndex.as_view(), name='view_index'),
)
๐Ÿ‘คvadimchin

Leave a comment