Django doesn't read form - python

I have form:
<form id="contact-form" class="contact__form" method="POST" action="{% url 'backcall' %}">
{% csrf_token %}
<span class="text-color">Send letter</span>
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" placeholder="Phone (+380)" pattern="[\+][3][8][0]\d{9}" minlength="13" maxlength="13" />
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" placeholder="Email">
</div>
<div class="form-group-2 mb-4">
<textarea name="message" class="form-control" rows="4" placeholder="Your letter"></textarea>
</div>
<button class="btn btn-main" name="submit" type="submit">Send</button>
</form>
views.py:
def backcall(request):
backcall = BackCall(name = request.POST['name'], phone = request.POST['phone'], email=request.POST['email'] , message = request.POST['message'])
backcall.save()
return redirect('thanks')
models.py
class BackCall(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=13)
email = models.EmailField()
message = models.TextField(default=None)
datetime = models.DateTimeField(auto_now_add=True)
When I fill out the form and submit nothing happens. When I follow the link 'backcall/' I get an error.
What the problem can be connected with and how to fix it?

Please, search more, exist the solution
Use the MultiValueDict's get method. This is also present on
standard dicts and is a way to fetch a value while providing a default
if it does not exist.
def backcall(request):
backcall = BackCall(name = request.POST.get('name'), phone = request.POST.get('phone'), email=request.POST.get('email') , message = request.POST.get('message'))
backcall.save()
return redirect('thanks')
You should check whether or not the record exists in your database, I think, a quick example would be:
def backcall(request):
obj, created = BackCall.objects.get_or_create(email=request.POST.get('email'),
defaults={'phone': request.POST.get('phone'),
'name': request.POST.get('name'),
'message': request.POST.get('message')}
if created:
return redirect('thanks')
return ...

Related

Django doesn't redirect to the same page

I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page.
Views.py class.
def showIndex(request):
if request.method == 'POST':
contact = Contact()
name = request.POST.get('name')
email = request.POST.get('email')
message = request.POST.get('message')
contact.name = name
contact.email = email
contact.message = message
print('yes and no ')
messages.success(request, 'Profile details updated.')
contact.save()
return render(request,'index.html')
return render(request,'index.html')
and this is the codes in index.html. I have created the form here.
<form method="POST" class="u-clearfix u-form-spacing-30 u-form-vertical u-inner-form" style="padding: 10px">
{% csrf_token %}
<div class="u-form-email u-form-group u-form-partition-factor-2">
<label for="email-319a" class="u-label u-text-body-alt-color u-label-1">Email</label>
<input type="email" placeholder="Enter a valid email address" id="email-319a" name="email" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" />
</div>
<div class="u-form-group u-form-name u-form-partition-factor-2">
<label for="name-319a" class="u-label u-text-body-alt-color u-label-2">Name</label>
<input type="text" placeholder="Enter your Name" id="name-319a" name="name" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" />
</div>
<div class="u-form-group u-form-message">
<label for="message-319a" class="u-label u-text-body-alt-color u-label-3">Message</label>
<textarea placeholder="Enter your message" rows="4" cols="50" id="message-319a" name="message" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required=""></textarea>
</div>
<div class="u-align-left u-form-group u-form-submit">
Submit
<input type="submit" value="submit" class="u-form-control-hidden" />
</div>
</form>
<div>
{%for message in messages%}
{{message}}
{%endfor%}
</div>
You have to pass the messages variable to the render method:
render(request,'index.html', {'messages': messages})

Django - pass multiple HTML form inputs into a view

I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None
HTML:
<div id="form_content">
<form action="" method="post">
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
views.py
def home(request):
form_response = request.GET.get("form_content")
print(form_response)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
first you need to add csrf_token in your code for post method and also give a name for each input like this :
<div id="form_content">
<form action="" method="post">
{% csrf_token %}
<section class="form_inputs">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
</section>
<section class="form_inputs">
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
</section>
<section class="form_inputs">
<label for="email">Email:</label>
<input type="text" name="email" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
and then:
def home(request):
first_name = request.POST['first_name']
last_name = request.POST['last_name']
email = request.POST['email']
print(first_name, last_name, email)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
In your input tags, you have not passed the name parameter. Pass the name parameter in your input tags, as Django collects the data from the name tags.
For example, in your case, it must be:
<input type="text" id="id_first_name" name="first_name">
<input type="text" id="id_last_name" name="last_name">
<input type="text" id="id_email" name="email">

URL is adding automatically - Django

I have got a problem while redirecting to the edit form.
SO what I am doing is that whenever user clicks on edit button it redirects to "editadmin/{{admin.id}}" using form action = "editadmin/{{admin.id}}" in HTML.
URL path is
path("editadmin/<int:id>", views.editadmin, name="editadmin")
path("update/<int:id>", views.updateadmin, name="updateadmin")
Views.py
#csrf_exempt
def editadmin(request, id):
admin = Admin.objects.get(id=id)
return render(request, "editadmin.html", {"admin": admin})
#csrf_exempt
def updateadmin(request, id):
if request.method == "POST":
admin_id = request.POST["admin_id"]
admin_id = str(admin_id).strip().upper()
name = request.POST["name"]
name = str(name).strip()
if db_name equals to name:
messages.error(request, "Admin name already exists")
return redirect("editadmin/" + str(id))
editadmin.html
<form method="post" class="post-form" action="/update/{{admin.id}}">
<input type="hidden" name="id" id="id" required maxlength="20" value="{{ admin.id }}"/>
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Admin ID : </h4></label>
<div class="col-sm-4">
<input type="text" name="admin_id" required style="margin-left:20px; height:38px; width:300px;
border-radius: 5px" id="admin_id" value="{{ admin.admin_id }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Name : </h4></label>
<div class="col-sm-4">
<input type="text" name="name" style="margin-left:20px; height:38px;
border-radius: 5px; width:300px" required id="name" value="{{ admin.name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success" style="margin-left:210px">Submit</button>
</div>
</div>
So what I want is that Whenever user submits invalid name in editadmin.html (URL - editadmin/1 ), it should redirect to the same URL editadmin/1 but what it does is it appends update/ which redirects to update/editadmin/1
How to fix this? I dont want update/ to get appended after redirecting to same form.
update/ is appending because you mentioned your form action to this URL. So instead of mentioning action in your form, you can do something like this.
#csrf_exempt
def updateadmin(request, id):
if request.method == "POST":
admin_id = request.POST["admin_id"]
admin_id = str(admin_id).strip().upper()
name = request.POST["name"]
name = str(name).strip()
# asuming you are checking if admin with this name already exists in database
if db_name equals to name:
messages.error(request, "Admin name already exists")
return redirect("editadmin/" + str(id))
# It mean user enter a unique name
else:
# your logic to save the incoming user here.
message.success(request, "Your success message")
return redirect(f'/update/{admin_id}')
and make sure to update your form from this:
<form method="post" class="post-form" action="/update/{{admin.id}}">
to this:
<form method="post" class="post-form" action="">

django ModelForms and normal form in POST request

Hi i just have a small doubt can we create a HTML template which will have the Django form and normal HTML form together.
I created a HTML template which has both normal HTML input tag and Django forms.
I am getting the following error when i do a form.save(commit=False)
could not be created because the data didn't validate.
My view.py
if request.method == 'POST':
form_value = request.POST.copy()
print form_value
form = InfoForm(data=request.POST)
post_val = form.save(commit=False)
my HTML
<div class="form-row">
<div class="form-group col-md-4">
{{form.name}}
</div>
<div class="form-group col-md-4">
{{form.number}}
</div>
<div class="form-group col-md-4">
{{form.location}}
</div>
</div>
<div class="form-group">
<label for="Feedback">Feedback</label>
<div id="Feedback" class="optionBox1">
<div class="input-group my-add-div">
<input type="text" class="form-control" name="feedback" required>
<input type="text" class="form-control" name="feedback" required>
<input type="text" class="form-control" name="feedback" required>
</div>
</div>
</div>
my form.py
class InfoForm(forms.ModelForm):
name = forms.CharField(label='Project Name',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Click to enter text',}))
number = forms.DecimalField(label='Project #',widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter the ID',}))
location = forms.CharField(label='Location',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter the Location',}))
class Meta:
model = Info
field = ('name','number','location',)
My Model.py
name = models.CharField(max_length=200,blank=True , null=True)
number = models.IntegerField(blank=True , null=True)
location = models.CharField(max_length=200,blank=True , null=True)
feedback = ArrayField(ArrayField(models.CharField(max_length=200,blank=True,null=True)))
Thanks in advance
You need to first call form.is_valid() to use save method on the form.
All what you need to create any form in template you want, example:
``
<form action="." method="post">
{% csrf_token %}
<input type="text" name="first_name">
<p><input type='submit' value="Change"></p>
</form> ``
then, in your view call
first_name = request.POST['first_name']
and it will be works fine.

Data not appearing in database after form submission

I have created an HTML form trying to do simple registration.
The problem is that after clicking submit button no error appears but when I chech database the data from fields is not there.
signup.html
<form action="\polls\Registration" method="POST">
<div class="form-group mb15">
<input type="text" class="form-control" name="userName" placeholder="Enter Your Username" required>
</div>
<div class="form-group mb15">
<input type="password" class="form-control" name="password" placeholder="Enter Your Password">
</div>
<div class="form-group mb15">
<input type="text" class="form-control" name="fullName" placeholder="Enter Your Full Name">
</div>
<div class="form-group mb20">
<label class="ckbox">
<input type="checkbox" name="checkbox">
<span>Accept terms and conditions</span>
</label>
</div>
<div class="form-group">
<button class="btn btn-success btn-quirk btn-block">Create Account</button>
<br>
Already a member? Sign In Now!
</div>
</form>
forms.py
class RegistrationForm(forms.Form):
userName= forms.CharField(label='Username',max_length=100)
password = forms.CharField(label='Password', max_length=100)
fullName= forms.CharField(label='Full Name', max_length=100)
myview.py
def reg(request):
if request.method == 'POST':
the request:
form = forms.RegistrationForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/polls/signin')
else:
form = forms.RegistrationForm()
return render(request, 'signup.html', {'form': form})
urls.py
urlpatterns = [
url(r'^Registration', myview.reg,name='Registration'),
]
[SOLVED]
What I did is that I created a model to handle form processing.I also used modelForm instead of forms. For anyone having same issue check this

Categories

Resources