Jeevan Bodas Jeevan Bodas - 3 years ago 82
HTML Question

how to access Django form fields through HTML

I have created models.py, forms.py, views.py & registeration.html.
At the moment in registeration.html I am directly importing the django form like {{reg_form.as_p}}, I can also do it in following two ways: {{ form.as_table }} or {{ form.as_ul }}. what I want is to have a real control over the fields to be displayed. Meaning to say some fields may be tabular, some may be list etc with specific css.
What I tried in html to access the field is mentioned below:
id = {{form.id_FullName}} name={{form.FullName}}

In models.py I have
FullName = models.CharField(max_length = 100)

The above way didnt work, I want some way to access the django fields in HTML.

Answer Source

Add name and pass the modelname , Change like this,

<input type="text" id="id_FullName" value=""  name="FullName" />.

and submit your form.

Example , lets say signup form :

forms.py,

class SignUpForm(forms.ModelForm):
    email = forms.CharField(label='email', max_length=100)
    password = forms.CharField(label='password', max_length=100)

    def __init__(self, *args, **kargs):
        super(SignUpForm, self).__init__(*args, **kargs)

    class Meta:
        model = User
        fields = '__all__'

views.py,

def signup(request):
    form = SignUpForm(request.POST or None)
    if request.method == 'POST':
        form = SignUpForm(request.POST or None)
        if not form.is_valid():
            print form.errors
            return render(request, 'signup.html', {'form': form})
        else:
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            new_user = User.objects.create_user(email=email,
                                                password=password,
                                                     )
            new_user.is_active = True
            new_user.save()
            return redirect('login')
    else:
        return render(request, 'signup.html', {'form': form})

urls.py

url(r'^signup', views.signup, name='signup'),

Finally in your templates ie signup.html,

<form action="." method="post"> {% csrf_token %}     

              <div class="form-group">
                  <input type="text" class="form-control" name="email" id="inputUsernameEmail" placeholder="Email">
              </div>
              <div class="form-group">
                  <input type="password" name="password" class="form-control" id="inputPassword" placeholder="Password">
              </div>

              <input type="submit" name="Sign up" value="Sign up" id="Sign_up" class="button_drop outline">
          </form>    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download