Django:get field values using views.py from html form - django

Hello everyone I have an HTML form as follows:
<body class="">
<div class="navbar navbar-static-top navbar-inverse"></div>
<div style="height:20%; width:30%; margin-top:12%; margin-left:40%;">
<div class="list-group">
<form role="form">
<br/>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-circle-o-notch" ></i></span>
<input type="text" name="Username" class="form-control" placeholder="Username" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" name="first_name" class="form-control" placeholder="FIRST_NAME" />
</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" name="last_name" class="form-control" placeholder="LAST_NAME" />
</div>
...
...
POST
</form>
</div>
</div>
</body>
and after clicking on post i am redirecting it to views.py. can any one tell me how to get the field values of all the fields of the form into views.py. thanks in advance

Each input should have a name attribute:
<input type="text" name="username" class="form-control"
placeholder="Desired Username" />
And then in your view you can access that data using request.POST or request.GET dictionary-like objects (it depends on the method attribute of the <form> tag):
def register(request):
username = request.POST['username']
...
But you shouldn't render/handle forms this PHPish way. Learn the django forms.

To catch the data in python backend
for POST request:
def register(request):
username = request.POST.get('username')
for GET request
def register(request):
username = request.GET.get('username')
.get was missing on earlier answer

Related

Data inside request.data not visible in Django Rest Framework

I am using DRF for CRUD operations. In my Project, I have function-based view taking request as parameter. I am aware of the fact that request.data is only applicable for DRF-Specific requests. I am also aware of the fact that it is a QueryDict.
I am taking input from HTML form as name, roll and city of a Student. But when I print the request.data (aka QueryDict), I only get csrfmiddlewaretoken and its value and found that other key-value pairs are missing. Where is my other data (i.e roll, name and city)
e.g {"csrfmiddlewaretoken": "JSACyyvAPqNcCPXNZQsNzPcca7ah3N7arkhFM9CuqpNammk6f43wQ4GyGg5QwU6w"}
forms.html (Template):
<form class="form" action="/save-data/" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" class="form-control" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="roll">Roll:</label>
<input type="number" id="roll" class="form-control" placeholder="Enter your Roll Number">
</div>
<div class="form-group">
<label for="city">City</label>
<input type="text" id="city" class="form-control" placeholder="Enter your City">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Views.py
#api_view(['POST', 'GET'])
def save_data(request):
requested_data = request.data
print(requested_data)
return HttpResponse("Success", content_type='application/json')
It was supposed to contain other data fields as well!

RuntimeError at /signup: Change your form to point to 127.0.0.1:8000/signup/ , or set APPEND_SLASH=False in your Django settings

RuntimeError at /signup
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
I got this problem while using forms. Please help
I have used bootstrap for styling
<form action="/signup/" method = "post" >
{% csrf_token %}
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">#</span>
<input type="text" class="form-control" placeholder="Username" name = "username" aria-label="Username" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Firstname" name="fname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Lastname" name="lname" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3">
<input type="email" class="form-control" placeholder="Recipient's email" name="email" aria-describedby="basic-addon2">
<span class="input-group-text" id="basic-addon2">#gmail.com</span>
</div>
<div class="input-group mb-3">
<input type="password" placeholder="password" name = "password" class="form-control">
</div>
<div class="input-group mb-3">
<input type="password" placeholder="confirm password" name = "con_password" class="form-control">
</div>
<div class="input-group mb-3">
<button type="submit" class="btn btn-primary">Signup</buttpn>
</div>
</form>
</div>
Views.py
def signup(request):
if (request.method == "POST"):
username = request.POST.get("username")
fname = request.POST.get("fname")
lname = request.POST.get("lname")
email = request.POST.get("email")
password = request.POST.get("password")
con_password = request.POST.get("con_password")
User.objects.create_user(username=username, first_name=fname, last_name=lname, email=email, password=password)
User.save()
messages.success(request, "Account created successfully")
return redirect("login")
Should Redirect to login Page
Either add APPEND_SLASH=False in settings.py. Or change form action="/signup/" to form action="/signup"

How to force this field to submit data?

I have a form that looks like
I am trying to add a product. The description of which will be entered through this form. But my textarea dont send data to product
html:
<div class="col-12">
<div class="mb-2">
<label class="form-label">Текст новости</label>
<div id="blog-editor-wrapper">
<div id="blog-editor-container">
<div class="editor">
<textarea name="text" class="form-control" id="text" rows="3" required>TEXT</textarea>
</div>
</div>
</div>
</div>
</div>
vievs:
def create(request):
if (request.method == 'POST'):
obj, created = Posts.objects.get_or_create(title=request.POST.get("title"))
obj.text=request.POST.get("text")
obj.preview=request.POST.get("preview")
obj.date=request.POST.get("date")
obj.image=request.POST.get("image")
obj.save()
models:
text = models.TextField('Текст статьи')
Мy other fields (not custom) look like this
<label class="form-label" for="blog-edit-title">Заголовок</label>
<input type="text" id="blog-edit-title" class="form-control" value="" name="title" />

how to creater a signup register form with my own reqired field form in django?

Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
Im new to django i want create signup form with my own feild ,i dont want to signup form in default that is in user table i want to created own custom sign up forn any can hepl plz
here is my example how my form feild look like
[enter link description here][1]
<form id="contact-form" method="post" action="/addyourschool/" role="form">
<input type="hidden" name="csrfmiddlewaretoken" value="vhcAZ5w1HpK2mUXMhdqHR1to9Yv2LeOB85E2kR7Z1ZsPo5fjtWZ5P7o23kj8lDsk">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_name">School Name</label>
<input type="text" name="schoolname" id="product" class="form-control ui-autocomplete-input" placeholder="Type few letter & select from down *" required="required" data-error="Lastname is required." autocomplete="off">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="form_cfschp">Can't find your School *</label>
<input id="form_cfschp" type="text" name="form_cfschpool" class="form-control" placeholder="Can't find your School *" required="required" data-error="Can't find your School">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Pessonname">Contact person Name *</label>
<input id="Pessonname" type="text" name="Pessonname" class="form-control" placeholder="Contact person Name *" required="required" data-error="Contact person Name ">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="DesignationatSchool">Designation at School(job title at this section) *</label>
<select id="DesignationatSchool" name="DesignationatSchool" class="form-control" required="required" data-error="Designation at School">
<option value=""></option>
<option value="Request principal">Principal</option>
<option value="Request quotation">Founder</option>
<option value="Request order status">Management</option>
<option value="Request copy of an invoice">Teachers</option>
<option value="Other">Others</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Enter your Password *" required="required" data-error="password">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="pwd">Confirm Password *</label>
<input id="pwd" type="password" name="password" class="form-control" placeholder="Confirm Password *" required="required" data-error="Lastname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="email">Email *</label>
<input id="email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="tel">Mobile No. *</label>
<input id="tel" type="tel" name="phone" class="form-control" placeholder="Please enter your Mobile No *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="text-center"> <input type="submit" class="btn btn-success btn-send" value="Register"></div>
<div class="text-center">Aready Register / have an account ? Login here</div>
</div>
</div>
</form>
from django import forms
class RegisterForm(forms.Form):
username = forms.CharField(max_length=50)
email = forms.EmailField(max_length=50)
subject = forms.CharField(max_length=50)
message = forms.CharField(widget=forms.Textarea)
You have to first create the forms.py file in your app as e.g(contact_us)
from django.shortcuts import render
from django.core.mail import send_mail
from .forms import RegisterForm
from django.http import HttpResponse
Create your views here.
def contact_us(request):
#request for POST
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
sender_name = form.cleaned_data['username']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message'])
send_mail('New Enquiry', message, sender_email, ['example#gmail.com'])
return HttpResponse('Thanks for Contacting US')
else:
form = RegisterForm()
return render(request, 'Contactus/contact.html', {'form': form})
After created the forms you have to insert the forms class name in views.py to display the custom form on browser.
#Create Your Template
<form id="contactform" method="POST">
{% csrf_token %}
<div class="column one-second">
{{ form.username }}
</div>
<div class="column one-second">
{{form.email }}
</div>
<div class="column one">
{{ form.subject }}
</div>
<div class="column one">
{{ form.message }}
</div>
<div class="column one">
<input type="submit" value="submit">
</div>
</form>
After this you have to call the form in template. To display your own custom form.
As i did above.

Sign up View in Django with Bootsrap

I am a self learned programmer (beginner) trying to write a Signup Class Based View. Through some tutorials I have been able to write a code which as follows:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views import generic
from django.views.generic import View
from .forms import UserForm
class UserFormView (View):
form_class = UserForm
template_name = "signup.html"
#display signup blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
#process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
#cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
# Returns User objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("home")
return render(request, self.template_name, {'form': form})
Here is the forms.py:
from django.contrib.auth.models import User
from django import forms
class UserForm (forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password' ]
Now, I have a signup.html page designed using bootstrap. I am now stuck how to integrate my views to the html page. Using {{ form }} in a plane html is working bt not in bootstrap designed page. Please help
signup.html:
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3" style="margin-top: 70px">
<form role="form" method="post" action="">{% csrf_token %}
<h2>Welcome to Artivism <small>Sign up</small></h2>
<hr class="colorgraph" style="height: 7px; border-top: 0; background: grey; border-radius: 5px;">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6">
{% for field in form %}
<div class="form-group">
<input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1" value="{{User.first_name}}">
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2" value="{{User.last_name}}">
</div>
</div>
</div>
<div class="form-group">
<input type="text" name="user name" id="user_name" class="form-control input-lg" placeholder="User Name" tabindex="3" value="{{User.username}}">
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4" value="{{User.email}}">
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5" value="{{User.password}}">
</div>
</div>
<span class="help-block">By clicking Sign Up, you agree to our Terms and that you have read our Data Use Policy, including our Cookie Use.</span>
<hr class="colorgraph" style="height: 7px; border-top: 0; background: grey; border-radius: 5px;"">
<div class="row">
<div class="col-xs-12 col-md-6 col-md-offset-3"><input type="submit" value="Sign Up" class="btn btn-primary btn-block btn-lg"></div>
</div>
</form>
</div>
Include the following form in your signup.html page and let me know if it works for you:
<form method="post" action="{% url 'signup' %}" class="form-horizontal">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label class="col-sm-2 control-label" for="id_{{ field.name }}">{{ field.label }}</label>
<div class="col-sm-10">
<input class="form-control" type="{{ field.field.widget.input_type }}"
name="{{ field.name }}"
id="id_{{ field.name }}"
value="{{ field.value }}" >
</div>
</div>
{% endfor %}
<input type="submit" value="Sign Up" class="btn btn-primary pull-right">
</form>
In your case, the simple solution would be to replace your form inputs with the following ones (this should work if your form fields are ['first_name', 'last_name', 'username', 'email', 'password']):
<input type="text" name="first_name" id="id_first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">
<input type="text" name="last_name" id="id_last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">
<input type="text" name="username" id="id_username" class="form-control input-lg" placeholder="Username" tabindex="3">
<input type="email" name="email" id="id_email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
<input type="password" name="password" id="id_password" class="form-control input-lg" placeholder="Password" tabindex="5">