Data inside request.data not visible in Django Rest Framework - django

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!

Related

How to save a form which contains a container div with sub-divs that have been dynamically added in django

I am working on a job portal system. I provide users the chance to edit their profiles by adding and removing job experiences. The issue is I don't know how to send that data to the view so that it can retrieve all the fields and store them in the database accordingly. By retrieving, I mean for each job experience, retrieve their corresponding sub fields
Here is my template file:
<!--JOB EXPERIENCE-->
<div class="job_experience">
<h5>Experience</h5>
<hr>
<!--FORM-->
<form action="#" id="save_job_experience_form" method="POST">
{% csrf_token %}
<div class="job_container">
{% for job in job_experience %}
<div class="exp">
<label>Organisation</label>
<input type="text" class="form-control" name="organisation
placeholder="Organisation" value="{% if job.organisation %}
{{job.organisation}}{% endif %}" required>
<label>Job Title</label>
<input type="text" name="job_title" class="form-control" value="{% if job.job_title
%}{{ job.job_title }}{% endif %}" placeholder="Job Title e.g Backend Developer"
required>
<button style="margin-left:15px;" type="button" class="btn btn-danger
remove_job_exp"><strong>Delete Job Experience</strong></button>
</div>
<hr>
{% endfor %}
</div>
<!--BUTTONS-->
<input type="submit"value="Save">
<input type="button" id="add_job_experience"value="Add one">
</form>
</div>
<script>
$(document).on('click', '#add_job_experience',function(e){
e.preventDefault();
$(".job_container").append(`<div class="exp">
<!--IT GOES ON AS ABOVE -->
$(document).on('click', 'button.remove_job_exp', function(e){
e.preventDefault();
$(this).closest('div.exp').remove();
});
You can post multiple inputs with the same name like so:
<input type="text" name="job[]" value="job1"/>
<input type="text" name="org[]" value="org1"/>
<input type="text" name="job[]" value="job2"/>
<input type="text" name="org[]" value="org2"/>
Then in django you can parse the POST data like so:
#require_POST #require POST method or check if request method is POST
def add_jobs(request):
jobs = request.POST.getlist('job[]')
orgs = request.POST.getlist('org[]')
...
Or use Django Formsets: https://docs.djangoproject.com/en/3.2/topics/forms/formsets/

my model is not showing up in admin model data is getting visble in link bar in csrf middle ware token

{% block body %}
{% load static %}
<div class="container my-3">
<h3>Contact Us</h3>
<form action="/contact" method="post"> {% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name='name' placeholder="Enter Your Name">
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter Your Email">
</div>
<div class="form-group">
<label for="name">Phone</label>
<input type="tel" class="form-control" id="phone" name='phone' placeholder="Enter Your Phone Number">
</div>
<div class="form-group">
<label for="desc">Your requirements:-</label>
<textarea class="form-control" id="desc" name='desc' rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success">Contact</button>
</form>
</div>
def index(request):
return render(request, 'prop/home.html')
def contact(request):
if request.method=='POST':
name = request.POST['name']
email = request.POST['email']
phone = request.POST['phone']
desc = request.POST['desc']
contact=Contact(name=name,email=email,phone=phone,desc=desc)
contact.save()
return render(request, 'prop/contact.html')
result
"GET /prop/contact/?csrfmiddlewaretoken=npxCzACid026bcA0bYugZdAL1K2Ondqu2EtpzTuoDbnYivut9tsHJnh5Tq7NWOdU&name=yashi&email=hyashkzo%40gmail.com&phone=55645blbb&desc= HTTP/1.1" 200 8758
make following changes and try
<form action="{% url 'contact' %}" method="POST"> {% csrf_token %}
instead of button
<input type="submit" value="Contact" class="btn btn-success">
Provided you have a url with name contact

Authenticating Registrationn form in django

I have this html form that I want to use for signup of customers.
<form id='registration-form'>
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname" ><br>
<input type="text" class="form-control input-upper" id="username" placeholder="Username" name="username"><br>
<input type="email" class="form-control input-upper" id="email" placeholder="Email" name="email"><br>
<input type="text" class="form-control input-upper" id="organization" placeholder="Organization" name="organization"><br>
<input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password"><br>
<input type="password" class="form-control input-upper" id="password" placeholder="Confirm Password" name="password"><br>
<small>By registering you agree to our terms and conditions</small>
<button type="button" class="btn btn-primary btn-block btn-signup-form">SIGN UP</button>
<button type="button" class="btn btn-primary btn-block btn-sign-linkedin" href="{% url 'social:begin' 'linkedin-oauth2' %}?next={{ next }}">Sign up with LinkedIn</button>
<p class="text-already">Already have an account? LOGIN</p>
</div>
</form>
How do I make an validation of the data filled i.e the email and password and I want customers to be able to log in after signing up
I'm not sure what you mean by validating data but If i got you correctly you should go for Django built in functionality for user creation. Django comes with Auth module which can reduce your lot's of effort and takes care of most of the painful parts. Just have a look on this post https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html
If you want simple validations you can use clean methods of Django Form. write one form class with the same fields as you mentioned.
EX.
Class SignupForm2(forms.ModelForm ):
class Meta:
model = User
def clean(self):
self.cleaned_data = super(SignupForm2, self).clean()
if 'captcha' in self._errors and self._errors['captcha'] != ["This field is required."]:
self._errors['captcha'] = ["Please enter a correct value"]
return self.cleaned_data

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

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

Simple GET request returns empty

Here's my HTML code:
{% extends "base.html" %}
{% block content %}
<form class="form-horizontal" action="/application/" method="get">
<div class="control-group">
<label class="control-label" for="userid">User ID</label>
<div class="controls">
<input type="text" id="userid" placeholder="Email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="pass">Password</label>
<div class="controls">
<input type="password" id="pass" placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" value="Sign in">
<br>
Forgot password?
<br>
Change password?
</div>
</div>
</form>
{% endblock %}
Here's my function in my view:
def application(request):
print request.GET
message=[]
for key,value in request.GET:
message.append("%s:%s"%key,value)
return HttpResponse(message)
Here no matter what I input, my 'print request.GET' prints a <QueryDict: {}>.
I can't figure out how to debug this. Any clue?
none of your inputs have name attributes,
name attributes are what are used to populate data for GET request.
<input type="password" id="pass" name="pass" placeholder="Password">
The above will show up with key name in request.GET
You're returning the last message, I suppose you want to render the template instead?
Try render_to_response instead.