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']
- 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
- [Django]-Can't verify site with LetsEncrypt
- [Django]-Celery use wrong python version
- [Django]-Python catch previous exception in broad handler
Source:stackexchange.com