Multiple Django Forms

171 views
Skip to first unread message

Stephanie Socias

unread,
Mar 30, 2015, 6:55:56 AM3/30/15
to django...@googlegroups.com
Hello,

I've been trying for days to get my form(s) going. I essentially have four separate forms and a formset that I am trying to submit with one submit button. I'm using django-crispy-forms. My first issue it that now my form "submit" button is not doing anything. Additionally, I need to be able to add/delete dynamically from my formset and, with one of the forms, I would like users to be able to select from a dropdown list of existing objects OR create a new object that gets added to the list (like "adding a new popup window outside the admin" in django-autocomplete-light).
I'm new to django and have been struggling at this for days. I would REALLY appreciate any help!

views.py:

def register(request):

    dataset_form
= DatasetForm()
    facility_form
= FacilityForm()
    contact_form
= FacilityContactForm()
    terms_form
= TermsForm()

    author_formset
= AuthorFormset()
    author_formset_helper
= AuthorFormsetHelper()

   
if request.method == 'POST':
        dataset_form
= DatasetForm(request.POST, request.FILES)
        facility_form
= FacilityForm(request.POST)
        author_form
= AuthorForm(request.POST)
        contact_form
= FacilityContactForm(request.POST)
   
   
return render(request, 'databank/register.html', {'dataset_form': dataset_form, 'facility_form': facility_form,
       
'author_formset': author_formset, 'author_formset_helper': author_formset_helper, 'contact_form': contact_form, 'terms_form': terms_form})

forms.py:
class AuthorForm(forms.ModelForm):
   
class Meta:
        model
= Author
        fields
= ['first_name', 'middle_initial', 'last_name', 'email', 'role']

    first_name
= forms.CharField(
        max_length
=96,
        required
=True,
   
)

    middle_initial
= forms.CharField(
        max_length
=96,
        required
=False,
   
)

    last_name
= forms.CharField(
        max_length
= 96,
        required
= True,
   
)

    email
= forms.EmailField(
        required
= True
   
)

    role
= forms.ModelMultipleChoiceField(
        queryset
= AuthorRole.objects.all(),
        widget
=forms.CheckboxSelectMultiple,
        required
= True,
   
)

class AuthorFormsetHelper(FormHelper):

   
def __init__(self, *args, **kwargs):
       
super(AuthorFormsetHelper, self).__init__(*args, **kwargs)
       
self.helper = FormHelper()
       
self.helper.form_tag = False
       
self.layout = Layout(
           
Fieldset(
               
"Author Information",
               
Div(
                   
Div('first_name', css_class='col-xs-4'),
                   
Div('middle_initial', css_class='col-xs-4'),
                   
Div('last_name', css_class='col-xs-4'),
                    css_class
='row'
               
),
               
Div(
                   
Div('email', css_class='col-xs-12 col-sm-6'),
                   
Div(
                       
Field(
                           
InlineCheckboxes('role'),
                       
),
                        css_class
='col-xs-12 col-sm-6'),
                    css_class
='row'
               
),
                css_class
= 'author_area'
           
),
       
)

AuthorFormset = formset_factory(AuthorForm, extra=3)

class FacilityForm(forms.ModelForm):
   
class Meta:
        model
= CollectionFacility
        fields
= ['facility_name', 'address_line1', 'address_line2', 'city', 'state_province', 'country', 'postal_code']

   
def __init__(self, *args, **kwargs):
       
super(FacilityForm, self).__init__(*args, **kwargs)
       
self.helper = FormHelper()
       
self.helper.form_tag = False
       
self.helper.layout = Layout(
           
Fieldset('Facility Information',
               
Div(
                   
Div('facility_name', css_class='col-xs-12 col-sm-4'),
                   
Div('address_line1', css_class='col-xs-6 col-sm-4'),
                   
Div('address_line2', css_class='col-xs-6 col-sm-4'),
                    css_class
='row',
               
),
               
Div(
                   
Div('city', css_class='col-xs-6 col-sm-3'),
                   
Div('state_province', css_class='col-xs-6 col-sm-3'),
                   
Div('country', css_class='col-xs-6 col-sm-3'),
                   
Div('postal_code', css_class='col-xs-6 col-sm-3'),
                    css_class
='row',
               
),
           
),
       
)

class DatasetForm(forms.Form):
    DATA_TYPES
= models.get_datatypes()
    RELEASE_CHOICES
= models.get_releasechoices()
    LABS
= models.get_labs()

   
# Dataset Fields
    lab
= forms.ChoiceField(
        label
="SBGrid Laboratory",
        choices
= BLANK_CHOICE_DASH + list(LABS),
        required
= True,
   
)

    sample
= forms.CharField(
        label
="Biological Sample",
        widget
=forms.TextInput(attrs={'placeholder': 'e.g. complexA'}),
        max_length
= 50,
        required
= True,
   
)

    dataset_type
= forms.ChoiceField(
        label
="Dataset Type",
        choices
=BLANK_CHOICE_DASH + list(DATA_TYPES),
        required
= True,
   
)

    subject_type
= forms.ModelMultipleChoiceField(
        label
="Subject",
        queryset
= Subject.objects.all(),
        widget
=forms.CheckboxSelectMultiple(attrs={'class':'checkbox_style'}),  # styling is not working yet
        required
= True,
   
)

    dataset_description
= forms.CharField(
        widget
= forms.Textarea(attrs={'rows':'1', 'placeholder': 'a brief description'}),
        required
= True,
   
)

    dataset_image
= forms.ImageField(
        label
="Dataset Image",
        required
=False,
   
)

    processing_notes
= forms.CharField(
        widget
= forms.Textarea,
        required
= False,
   
)

    date_collected
= forms.DateField(
        widget
=forms.TextInput(attrs={'class': 'datepicker', 'placeholder': 'select a date'}),
        help_text
="Leave blank if unknown."
   
)

    release_date
= forms.DateField(
        label
= "",
        widget
=forms.TextInput(attrs={'class': 'datepicker', 'placeholder': 'select a date'}),
        required
= False
   
)

    release_asap_or_tbd
= forms.ChoiceField(
        label  
= "Release Date",
        choices
= RELEASE_CHOICES,
        required
= True,
   
)

    pdb_code
= forms.CharField(
        widget
=forms.TextInput(attrs={'placeholder': 'PDB code'}),
        required
= False
   
)

    publication_link
= forms.URLField(
        widget
=forms.TextInput(attrs={'placeholder': 'DOI'}),
        required
= False
   
)

   
def __init__(self, *args, **kwargs):
       
super(DatasetForm, self).__init__(*args, **kwargs)
       
self.helper = FormHelper()
       
self.helper.form_tag = False
       
self.helper.layout = Layout(
           
Fieldset(
               
"Dataset Information",
               
Div(
                   
Div('lab', css_class='col-xs-6'),
                   
Div('sample', css_class='col-xs-6'),
                    css_class
='row'
               
),
               
Div(
                   
Div('dataset_type', css_class='col-xs-6 col-md-4'),
                   
Div(AppendedText('date_collected', '<span class="glyphicon glyphicon-calendar" aria-hidden="true"></span>'),css_class='col-xs-6 col-md-4'),
                   
# Field('is_approximate', css_class='col-xs-2',),
                   
Div(InlineCheckboxes('subject_type'), css_class='col-xs-12 col-md-4'),
                    css_class
='row'
               
),
               
Field(
                   
'dataset_description',
                    rows
='2',
               
),
               
Field('dataset_image',),
               
Field('release_asap_or_tbd', template="databank/radio-check-buttons.html"),
               
Div(
                   
Div(AppendedText('release_date', '<span class="glyphicon glyphicon-calendar" aria-hidden="true"></span>' ), css_class='col-xs-6 set_date',),
                    css_class
='row'
               
),
               
Div(
                   
Div('pdb_code', css_class='col-xs-6'),
                   
Div('publication_link', css_class='col-xs-6'),
                    css_class
='row'
               
),
           
),
       
)

class FacilityContactForm(forms.ModelForm):
   
class Meta:
        model
= FacilityContact
        fields
= ['title', 'first_name', 'middle_initial', 'last_name', 'email']

   
def __init__(self, *args, **kwargs):
       
super(FacilityContactForm, self).__init__(*args, **kwargs)
       
self.helper = FormHelper()
       
self.helper.form_tag = False
       
self.helper.layout = Layout(
           
Fieldset(
               
"Facility Contact Information",
               
Div(
                   
Div('title', css_class='col-xs-12 col-sm-2'),
                   
Div('first_name', css_class='col-xs-4 col-sm-4'),
                   
Div('middle_initial', css_class='col-xs-4 col-sm-2'),
                   
Div('last_name', css_class='col-xs-4 col-sm-4'),
                    css_class
='row'
               
),
               
Div(
                   
Div('email', css_class='col-xs-12 col-sm-6'),
                   
Div(
                       
Field(
                           
InlineCheckboxes('role'),
                       
),
                        css_class
='col-xs-12 col-sm-6'),
                    css_class
='row'
               
),
                css_class
= 'author_area'
           
),
       
)

class TermsForm(forms.Form):
    terms_of_use
= forms.BooleanField(
        label
=mark_safe('Agree to the <a data-toggle="modal" class="termConditionsModal"> Terms and Conditions</a>'),
        required
= True
   
)
   
def __init__(self, *args, **kwargs):
       
super(TermsForm, self).__init__(*args, **kwargs)
       
self.helper = FormHelper()
       
self.helper.form_tag = False
register.html:
<form action="{% url 'stuff:register' %}" method="post" enctype="multipart/form-data">
        {{ dataset_form.media }}
        {% crispy dataset_form %}
        {% crispy facility_form %}
        {% crispy contact_form %}
        {% crispy author_formset author_formset_helper %}
        {% crispy terms_form %}
<a role="button" class="btn btn-lg btn-default" href="{% url 'stuff:my_home' %}">Cancel</a>
<input type="submit" class="btn btn-lg btn-success pull-right" value="Proceed to Step 2">




François GUÉRIN

unread,
Mar 30, 2015, 7:47:48 AM3/30/15
to django...@googlegroups.com
1/ use generic views : ProcessFormView by example
2/ use prefixes in your forms with there name (it's a param in form cctor)
3/ in your template, use the <form>{%for form in forms %}{% form.as_p %}{%endfor %}<button type='submit'/></form> if you put your forms into a list form forms

Good coding !
 

Stephanie Socias

unread,
Mar 30, 2015, 1:43:50 PM3/30/15
to django...@googlegroups.com
Thank you for your suggestions!

Unfortunately, as I am verrrrry green at the moment, I nee more help to implement all of these new techniques. Given that what I'm trying to accomplish requires more extensive Django and javascript knowledge, is there anyone who would be willing to do a video screen share with me to help me out?? I can pay you!

Thank you,
Stephanie

François GUÉRIN

unread,
Mar 31, 2015, 3:35:01 AM3/31/15
to django...@googlegroups.com
Hi Stephanie,

Maybe you are french ? I'm sorry, but I've no time to make a screencast video. But the django doc is very good and in multiple languages : french is available if you change /en/ > /fr/ in the doc url.

1/ For generic views : https://docs.djangoproject.com/en/1.7/topics/class-based-views/

2/ For formsets : https://docs.djangoproject.com/en/1.7/topics/forms/formsets/

3/ For templates, you'd better to get a custom base_form.html. I use this one :

https://gist.github.com/frague59/5c5450bf4d02643bc547

The code snippets depends on other templates, but they are not difficult to figure out.

Bye and good luck
François

Bill Blanchard

unread,
Mar 31, 2015, 7:12:22 AM3/31/15
to django...@googlegroups.com

Hi Stephanie,
Ping me offline, I might be able to help you out.

--
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...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9d1c60b2-a194-40ef-8ef1-5065c1c8184e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Luis Zárate

unread,
Apr 4, 2015, 1:28:40 PM4/4/15
to django...@googlegroups.com
mmm Maybe you should use form wizard if you have too many forms
https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/





For more options, visit https://groups.google.com/d/optout.



--
"La utopía sirve para caminar" Fernando Birri


Stephanie Socias

unread,
Apr 7, 2015, 10:54:52 AM4/7/15
to django...@googlegroups.com

Thank you all for you suggestions/help. I was finally able to get this working by using django-dynamic-formset
Bill Blanchard helped me figure it out! I will post a more detailed solution in my other post here on this forum ("Help with Dynamically Adding Forms to a Formset!!")
Reply all
Reply to author
Forward
0 new messages