Django - Form is not saving to Db - python-3.x

I'm using for authentication extended AbstractUser and ModelForm. When I write on HTML page only {{ form }} everything works fine, the form is submitting, but in the following case I've added some stylings, but now nothing works. Please, help me find the reason.
HTML:
<form method='POST'>
{% csrf_token %}
<div class="sign-up-user">
<div class="sign-up-user-container">
<div class="sign-up-user-left">
<label for="">{{form.username.label}}</label>
{{form.username}}<br>
<label for="">{{form.password.label}}</label>
{{form.password}}<br>
<label for="">{{form.branch.label}}</label><br>
{{form.branch}}<br>
<label for="">{{form.license_number.label}}</label>
{{form.license_number}}<br>
<label for="">{{form.fin_number.label}}</label>
{{form.fin_number}}<br>
<label for="">{{form.voen_number.label}}</label>
{{form.voen_number}}<br>
</div>
</div>
<input type="submit" value="Register User" class="sign-up-btn">
</div>
</form>

Include two lines to your HTML to understand whats going wrong:
{{ form.errors }}
{{ form.non_field_errors }}
This will display any errors that are associated with the form. If they dont then in your views do the following:
form = YourForm()
if form.is_valid():
// Do things
else:
print (form.errors)
print(form.non_field_errors)
This will display some other errors that you are missing.

Related

Flask Jinja User Checkbox List of Items

I'm stumped at the moment on what to do here. I have a Flask server where an app.route has a list called "addresses" that gets passed to rendered page customeraddresses.html to be displayed.
The goal is to show the user the list displayed by checkboxes so they can check the ones they would like to remove from the list. Currently I'm displaying a list of checkboxed items for the user to check, but I'm not sure how to grab everything that the user wants to remove.
How can I pass everything to app.route /removelistitems that the user checked?
Any assistance would be greatly appreciated.
app.py
from flask import Flask, render_template, request
import requests
import json
app = Flask(__name__)
...
...
#app.route('/customeraddresses', methods=["POST"])
def currentaddresses():
customername = request.form.get("customername")
addresses = ['1.1.1.1', '2.2.2.2', '3.3.3.3', '4.4.4.4']
return render_template("/customeraddresses.html", customername=customername, addresses=addresses)
#app.route('/removelistitems', methods=["POST"])
def removeitems():
thingstoremove= request.form.get('thingstoremove')
currentaddresses.html
...
...
<form action="/removelistitems" method="POST">
<div class="row">
<div class="col">
</div>
<div class="col-md-11">
{% for address in addresses %}
<div class="form-group">
<label for="existing_{{address}}" class="control-label col-sm-2">{{address}}</label>
<input type="checkbox" name="existing_{{address}}"/>
<br/>
</div>
{% endfor %}
<button type="submit" [disabled]="!name" class="btn btn-secondary">Submit</button>
</div>
<div class="col">
</div>
</div>
</form>
...
...

Django Form issue

I am using Django to select language. One option works fine, but the other won't work
Option (1) Works fine .
<select name="language"
onchange="this.form.submit()" >
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% for lang in LANGUAGES %}
<option value="{{ lang.0 }}" {% if lang.0 == LANGUAGE_CODE %} selected="selected"{% endif %} >{{ lang.1 }} ({{ lang.0 }})</option>
{% endfor %}
</select>
Option 1 : Not working using (form Submit Button )
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="LanForm">
{% csrf_token %}
<input class="lang" id="language" name="language" type="hidden" value="ar">
<input class="lang" id="setl" name="setl" type="submit" value="Go">
</form>
The select option works fine and change the language and redirect properly . But if I use the "Go" button , nothing is changing . I am wondering what is issue.
Firstly you do not set more than one node with the same id.
Secondly, you have kept the name of both submit and hidden inputs same i.e, 'language'.
Use the below snippet and test again
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="language">
{% csrf_token %}
<input class="lang" id="language" name="language" type="hidden" value="ar">
<input class="lang" type="submit" value="Go">
</form>
I managed to fix this issue by modfing the form as follows,
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="LanForm">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />
<input name="language" type="hidden" value="ar" />
<input class="lang" name="language2" type="button" value="Go" onclick=" document.getElementById('LanForm').submit();" >
</form>
No ids no names in the input field

Integrating normal HTML form with Django form

What I am trying to do is have a form that has this HTML:
<form method="post" action="">
{% csrf_token %}
<label>Pick a class:</label>
<select id="schedClass" name="schedClass" >
<option>Select one</option>
{% for i in classes %}
<option value="{{ i.id }}">{{ i.name }}</option>
{% endfor %}
</select>
</select>
{{ form }}
<input type="submit" value="reload">
</form>
The problem is that for some reason when I submit, the select schedClass doesn't appear in the link. I think it comes from the fact that it's integrated with a django form, but I have no idea.
For clarification, what I am trying to do is have a form that creates an instance of a specific model, and one of the categories is schedClass which is a ManyToManyField, but I can't use a ModelForm since I need the items in the selections to be only ones that are also linked to the user with another ManyToMany.
Is there anything to do?

Cannot pass variables to Django 3 method from HTML template

I am a Django newbie who is trying to convert an existing HTML based website to Django 3. The only complex piece of this page is a call to a Django method that uses the django.core.mail package and everything works, but, I am trying to pull some data off of the HTML template and pass it to this method.
The method works, only it sends a blank email. I am trying to pass contact information that the end user would fill out on the form. If I hard code the data into the method it works.
I have tried passing the data through urls.py, but, everything I try fails to even parse when I call the method. When I use a request.GET.get everything seems to work, just no data.
I was hoping to use something similar to JQuery like the following in the method.
name = str(request.GET.get('Name:', '').strip())
email = str(request.GET.get('Email:', '').strip())
msg1 = str(request.GET.get('Message:', '').strip())
with the fields being in the HTML form.
I am going to include some of the relevant configuration items below.
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from . import views
app_name = 'willdoit'
urlpatterns = [
path('', views.index),
#url(r'^contact/(?P<name>\.+)/(?P<email>\.+)/(?P<msg1>\.+)/?$', views.contact, name='contact'),
path('contact/', views.contact, name='contact'),
]
views.py
def contact(request):
name1 = request.GET.get('name', '')
email1= request.GET.get('email', '')
msg1 = request.GET.get('message1', '')
subject = 'Work needed'
from_email = settings.DEFAULT_FROM_EMAIL
message = name + ' ' + email + ' ' + msg1
recipient_list = ['pkustra914#gmail.com']
send_mail(subject, message, from_email, recipient_list, fail_silently=False)
return HttpResponse('Success')
Relevant HTML Template section
<div class="contact_content">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="contact_message wow fadeInLeft" data-wow-duration="1.5s">
<form action="#" id="formid">
<form action="#" id="formid">
<div class="form-group"> <input class="form-control" name="name"
placeholder="Name" required="" type="text"> </div>
<div class="form-group"> <input class="form-control" name="email"
placeholder="Email" required="" type="email"> </div>
<div class="form-group">
<div class="Descrizione"> <label for="InserisciDescrizione"
class=""><b>Message</b></label> <textarea class="form-control"
id="message" placeholder="Type message:" name="message1" rows="6" cols="50"
title="Message"></textarea> </div>
<a id="submit" href="{% url 'willdoit:contact' %}" class="btn btn-primary">Submit</a>
I would prefer to use the request.GET.get method, but, there is a lot more documentation passing it through the urls.
Thanks.
Your code request.GET.get('Name:', '') returns empty string when the key 'Name:' is not found.
To fix this, use request.GET.get('name', '') request.GET.get('email', '') request.GET.get('message', '') instead.
Details
I see that you are using a with template tag for nothing. The following line of code does not change the name attribute string to PascalCase. See with template tag (Docs)
{% with Name=name Email=email Message=message %}
Even if it worked, your code should be calling request.GET.get('Name', '') instead of request.GET.get('Name:', ''). But it won't work, as with would not modify the attribute names in the GET request.
#EDIT1
There are apparently more bugs in your html code. I have reformatted your code and listed up some obvious bugs.
<!--REFORMATTED CODE-->
<form action="#" id="formid"> <--------------DUPLICATES, remove one
<form action="#" id="formid"> <--------------DUPLICATES, remove one
<div class="form-group"> <input class="form-control" name="name"
placeholder="Name" required="" type="text"> </div>
<div class="form-group"> <input class="form-control" name="email"
placeholder="Email" required="" type="email"> </div>
<div class="form-group">
<div class="Descrizione">
<label for="InserisciDescrizione" class=""><b>Message</b></label>
<textarea class="form-control" id="message"
placeholder="Type message:" name="message1" rows="6" cols="50"
title="Message"></textarea>
</div>
<a id="submit" href="{% url 'willdoit:contact' %}"
class="btn btn-primary">Submit</a>
<-------- MISSING DIV END TAG
<-------- MISSING FORM END TAG
Furthermore, you are calling the server by url directly using the following code:
<a id="submit" href="{% url 'willdoit:contact' %}" class="btn btn-primary">Submit</a>
This does not tell the page which form you want to submit (there are cases where there are multiple forms).
You have two choices:
Replace the tag with standard html form submit button <input type="submit">, and add the url to the action attribute of the form. Use the following code to do so:
<form action="{% url 'willdoit:contact' %} id="formid">
...
...
<input id="submit" type="submit" class="btn btn-primary" value="Submit"/>
</form>
This solution will by default use the GET method to send a request to the server, and you will be able to get the inputted values by calling request.GET.get(name).
If you are using JQuery, you can replace the with the following:
Submit
This is however not recommended. Please use the standard html form input tag for the submit button.
Great. Moving the method call to the form tag worked great.
Thanks! You guys are the best.

How can I get the value of an input in twig and reuse in an url that exists in the same page twig without the use jquery

<div class="product-btns">
<div class="qty-input">
<span class="text-uppercase">QTY: </span>
<input name="quantite" class="input" type="number">
</div>
{% if app.user != null %}
<a id="test" href="{{path('commande'{'id_product':listProduct.id ,'id_user':app.user.id,'quantite': })}}" class="primary-btn add-to-cart">
<i class="fa fa-shopping-cart"></i>
Add to Cart
</a>
{% else %}
I want to get value of input name="quantite" and reuse in path of parameter 'quantite'.
Have you tried ?
{{ form.vars.value.quantite }}

Resources