For loop for ModelForm in Django

750 views
Skip to first unread message

Ali khan

unread,
Oct 2, 2016, 7:02:16 AM10/2/16
to django...@googlegroups.com
I need to iterate the form to get Boolean values in a single line. Please help me to figure out a way to iterate through model forms.
Also I generally need to understand how to iterate through modelforms.

App Model:

class ProjectDetails(models.Model):
 type = models.CharField(max_length=120)
 tools = models.CharFiled(max_length=120, choices=tools)
 reporting = models.BooleanField(defautl=False)
 weekly_meeting = BooleanField(default=True)
 def __unicode__(self):
  return self.project_tools

App Form:  
def ProjectDetailForm(forms.ModelForm):
 class Meta:
 model = ProjectDetails
 fields = ["project_type", "project_tools", "reporting", "weekly_meeting"]

App view:
def project_info(request):
    template = 'project.html'
    form = ProjectDetailForm(request.POST or None)
    if form.is_valid():
        form.save(commit=True)
    return render(request, template, context={'form':form})


App html file:
<form actio="", method="post">
{% csrf_token %}
{{ form }}
<input type='submit' class='btn btn-danger' value='Send' />
</form>


Ali

Andromeda Yelton

unread,
Oct 4, 2016, 10:16:29 AM10/4/16
to django...@googlegroups.com
https://docs.djangoproject.com/en/1.10/topics/forms/#looping-over-the-form-s-fields

That said, testing for Boolean vs. non-Boolean fields is really more logic than belongs in a template. You can manually lay out the form in the template, specifying where each field should go and surrounding them with your desired HTML, or you can use crispy forms (https://django-crispy-forms.readthedocs.io/en/latest/) on the back end if you want to be manipulating a lot of logic (and then let crispy take care of generating HTML and making it look nice).

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAXvsY%3Df3QRBpuOvQMcyRQND8H_Ds8%2Bv-3LREOJVhPzo_0qRPw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.



--
Andromeda Yelton
Vice President/President-Elect, Library & Information Technology Association: http://www.lita.org
Reply all
Reply to author
Forward
0 new messages