2

I am using a bootstrap variant to help style a model form. There is a certain class I would like one of the fields to be and I have read around on the subject and the general consensus is to add a widget to the ModelForm's meta, like I tried below:

forms.py

class EmailForm(forms.ModelForm):
    class Meta:
        model = MarketingEmails
        fields = ['messageid','subject','body','name','altsubject','utm_source','utm_content','utm_campaign',]
        widgets = {
            'body': Textarea(attrs={'class': 'summernote'}),
        }

However this doesn't seem to render onto my template, which is:

<div class="row">
<div class="col-sm-6">
    <form method="POST" class="post-form" action ="">
    {% csrf_token %}        
        <p><label for="id_subject">Subject</label>
        <input class="form-control" id="id_subject" type="text" name="subject" maxlength="1000" value="{{rows.subject}}"required /></p>

        <p><label for="id_name">Name</label>
        <input class="form-control" id="id_name" type="text" name="name" maxlength="1000" value="{{rows.name}}"required /></p>

        <p><label for="id_body">Body</label>
        <input class="form-control" id="id_body" type="text" name="body" maxlength="1000" value="{{rows.body}}"required /></p>

        <p><label for="id_altsubject">Alt Subject</label>
        <input class="form-control" id="id_altsubject" type="text" name="altsubject" maxlength="1000" value="{{rows.altsubject}}"required /></p>

        <p><label for="id_utm_source">utm_source</label>
        <input class="form-control" id="id_utm_source" type="text" name="utm_source" maxlength="1000" value="{{rows.utm_source}}"required /></p>

        <p><label for="id_utm_content">utm_content</label>
        <input class="form-control" id="id_utm_content" type="text" name="utm_content" maxlength="1000" value="{{rows.utm_content}}"required /></p>

        <p><label for="id_utm_campaign">utm_campaign</label>
        <input class="form-control" id="id_utm_campaign" type="text" name="utm_campaign" maxlength="1000" value="{{rows.utm_campaign}}"required /></p>

        <button type="submit" class="save btn btn-default">Save</button>

    </form>
</div>

Is there another way to do this or is there something I have done wrong in my code?

UPDATE I have followed the suggested of Jacek and now it is styled but the information is no longer displaying, this is my new code:

forms.py:

class EmailForm(forms.ModelForm):
subject = forms.CharField(
    label = 'Subject',
    max_length = 2000,
    required = True,
    widget = forms.TextInput(
        attrs = {'class': 'summernote', 'name': 'subject'}
        )
    )

... 
class Meta:
    model = MarketingEmails
    fields = ['messageid','subject','body','name','altsubject','utm_source','utm_content','utm_campaign',]

views.py:

def emailinfo(request, pk):
if request.session.has_key('shortname'):
    shortname =  request.session['shortname']
    form = MarketingEmails.objects.filter(messageid =pk).get()
    if request.method == 'GET':
        form = EmailForm(instance=form)
        return render(request, 'marketingemails/emailinfo.html',{'shortname': shortname, 'form': form})

    else:
        form = EmailForm(request.POST,instance=form)
        if form.is_valid():
            return redirect('marketingemails:emailinfo', pk = form.messageid)

    return render(request, 'marketingemails/emailinfo.html',{'shortname': shortname, 'form': form})
else:
    return HttpResponseRedirect(reverse('common:login'))    

html:

<div class="row">
<div class="col-sm-6">
    <form method="POST" action ="">
    {% csrf_token %}        
    {% for field in form %}
        {{ field.label_tag }}
        {{ field }}

        {% if field.help_text %}
            {{ field.help_text }}
        {% endif %}

        {% for error in field.errors %}
            {{ error }}
        {% endfor %}

    {% endfor %}
    <button type="submit" class="btn btn-primary">Submit</button>

    </form>
</div>

3 Answers 3

5

In my templates I use Widget Tweaks You can add CSS classes or twitter-bootstrap classes. Its really useful

<form method='POST' action="/" enctype='multipart/form-data'>
 {% load widget_tweaks %}
 {% csrf_token %}
 {{ form.first_name |add_class:"customCSS1 customCSS2" }}
 {{ form.second_name |add_class:"form-control customCSS4" }}
</form>
{{ form.media.js }}

with this plugin you can style the form as you wish. You could add your form-control class or use a personal CSS class like

.customCSS1{
  width60%;
  border-radius:5px;
 }
Sign up to request clarification or add additional context in comments.

Comments

4

Try this:

forms.py

class EmailForm(forms.ModelForm):
    ...
    subject = forms.CharField(
        label = 'Subject',
        max_length = 1000,
        required = True,
        widget = forms.TextInput(
            attrs = {'class': 'summernote', 'name': 'subject'}
        )
    )   

    body = forms.CharField(
        label = 'Body',
        max_length = 1000,
        required = True,
        widget = forms.TextInput(
            attrs = {'class': 'summernote', 'name': 'body'}
        )
    )   
    ...

    class Meta:
        model = MarketingEmails
        fields = ('messageid','subject','body','name', ... )

view.py

from django.shortcuts import render
from your_app_path.forms import EmailForm

def fname(request):
    ...
    marketing = MarketingEmails.objects.get(...)

    form = EmailForm(instance=marketing) 
    ...

    return render(request, 'yourview.html', { 'form': form })

yourview.html

<form action="" method="post">
  {% csrf_token %}
  {% for field in form %}
    {{ field.label_tag }}
    {{ field }}

    {% if field.help_text %}
      {{ field.help_text }}
    {% endif %}

    {% for error in field.errors %}
      {{ error }}
    {% endfor %}

  {% endfor %}
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

1 Comment

I have set the code up like suggested, and now it is styled but the information is not being displayed on the webpage like it was previously, I have added an update on my code - do you know why this is?
2

Not exactly answer for your question but directly related and I think people looking for it might land here: You can pass a class attr to a Model Form (not just Form) but you have to watch out not to put it in the class Meta:

class EmailForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EmailForm, self).__init__(*args, **kwargs):
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'
    class Meta:
        model = MarketingEmails
        fields = __all__ # or a list of ones you actually want to see
    


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.