Django==3.0.4
class LoginForm(forms.Form):
login = forms.CharField()
password = forms.CharField()
return_url = forms.CharField(widget=forms.HiddenInput())
class Login(FormView):
template_name = 'login/login.html'
form_class = LoginForm
success_url = "/"
<form method="post">{% csrf_token %}
{{ form.login }}
{{ form.password }}
<input type="hidden" name="return" value="{{ return_url }}" />
<input type="submit" value="Login">
</form>
The problem is that the form is invalid. In the picture it is visible what I input in the fields. Could you help me here?
Your form is required a field name return_url but you send it as return instead.
To access form error messages you can use Form.errors
Ref: https://docs.djangoproject.com/en/3.0/ref/forms/api/#django.forms.Form.errors
Related
How can I pass data to form fields in django templat ? , for example I have below code in my project:
<td class="col-3">
{{form.number|as_crispy_field}}
</td>
Can I use
<td class="col-3">
{{form.number}} = 10
</td>
in django template ?
#mosi -
<td class="col-3">
{{form.number}} = 10
</td>
No, you cannot use this. If you are planning to pass data from views to template then do something like this
Let's say you have a form something like this
forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
views.py
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # your logic here
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
template.html
<form method="post" novalidate>
{% csrf_token %}
{{ form.name }}
{{form.email}}
<button type="submit">Submit</button>
</form>
OR
Simply
<form method="post" novalidate>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
Now, if you want to set initial values to your form in template
Lets say you have the following
class ContactForm(forms.Form):
name = forms.CharField(max_length=30,initial='test')
Then in your template you do something like this
<form method="post" novalidate>
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<button type="submit">Submit</button>
</form>
Now, in case of an UpdateView where data is pulled in dynamically from the Database based on let's say product id. The following is just an example
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = (
"created_by",
"slug",
)
class ProductUpdateView(UpdateView):
# specify the model you want to use
model = Product
form_class = ProductForm
template_name = "catalog/product/update_product.html"
product_update.html
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
{{ form.as_p}}
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Or
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<input type="text" name="description" id="description" value="{{ form.description.value }}">
.........
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
On my Django website, I'm unable to submit my form. Although I have every field filled out, my password field continues to say "This field is required" even as I have typed something in the password field as well.
I have tried removing the required attribute for the password tag but that has not helped.
Here is my code.:
F
views.py: specifically for the function signup, the code never reaches within the if form.is_valid() block.
def signup(request):
#If user completes the form (hits the sign up button)
#Send form data to url /signup-complete/ (see signup.html)
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = User.objects.create(
username= form.cleaned_data['email'], #Note although there is an email field, we don't use it to prevent redundancy
first_name = form.cleaned_data['first_name'],
last_name = form.cleaned_data['last_name'],
password = form.cleaned_data['password'],
)
#Extended attribute, must be added seperately
user.user_extend.is_student = form.cleaned_data['is_student']
user.save()
print('user is now created')
return HttpResponseRedirect('')
#Render form
else:
form = SignUpForm()
return render(request, 'mainapp/signup.html', {'form': form})
signup.html
<!-- action="/signup_complete/"-->
<form action="" method="post">
<!--Security, Cross Site Request Forgery Protection -->
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form %}
<div class="form-group">
{{ field.errors }}
<!--or field.name == 'confirm_password'-->
{% if field.name == 'password' %}
{{ field.label_tag }}
<input name="{{ field.name }}" class="form-control" type="password" required>
{% elif field.name == 'email'%}
{{ field.label_tag }}
<input name="{{ field.name }}" class="form-control" type="email" required>
{% elif field.name == 'is_student'%}
<div class="float-right">
<input name="{{ field.name }}" type="checkbox">
{{ field.label_tag }}
</div>
<!--First and last name -->
{% else %}
{{ field.label_tag }}
<input name="{{ field.name }}" class="form-control" type="text" required>
{% endif %}
</div>
{% endfor %}
<!-- Sign up button -->
<button type="submit" class="btn btn-primary col-md-12" value="sign_up">Sign Up!</button>
</form>
models.py
class UserExtend(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_student = models.BooleanField(default=None)
SignUpForm (forms.py)
class SignUpForm(forms.Form):
first_name = forms.CharField(label='First Name', max_length=50)
last_name = forms.CharField(label='Last Name', max_length=50)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput, max_length=50)
is_student = forms.BooleanField(label="Are you a student? (Statistical purposes only)")
First i suggest you look the request carefully to find what field you pass through it.
you can show form simpler.
<form>
{{form.password.errors}}
<input name="password" class="classes">
</form>
Found my error. The problem is that my boostrap was displaying incorrectly that the password field ha an error when in actuality, the checkbox had an error because it did not have a default value.
When I click on ok button in add_tech.html then it will redirect me on upload_type.html.
But it show error while clicking on ok button.
ERROR -
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
My template(add_tech.html) -
<form action="/uploads/type/" method="post">
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
My Template(upload_type.html)-
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
</form>
My View.py -
def upload_type(request):
if request.method =='POST':
details = NameForm(request.POST)
if details.is_valid():
return render(request, "core/upload_type.html", {'form':details})
else:
details = NameForm()
return render(request, 'core/upload_type.html', {'form': details})
My Url.py -
urlpatterns = [
url(r'^uploads/type/$', views.upload_type, name='upload_type'),]
My form.py -
from uploads.core.models import Name
class NameForm(forms.ModelForm):
class Meta:
model = Name
fields = ('your_name', )
My Models.py-
class Name(models.Model):
your_name = models.CharField(max_length=100)
You need to have the csrf token like this for your post method in the django template
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
For POST request, csrf token is required. So in your template, add `{% csrf_token %}.
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
From the Docs:
Django ships with an easy-to-use protection against Cross Site Request
Forgeries. When submitting a form via POST with CSRF protection
enabled you must use the csrf_token template tag as in the preceding
example.
am working on a project with Django, i dynamically created an input field and am trying to submit it, but i could not do so, i searched online and i saw that it could be done with formset_factory but when i tried it, i got this error
CatName = int(float(request.POST.get('CatName')))
TypeError: float() argument must be a string or a number, not 'NoneType'
here is my code
the form.html
<form action="." method="post" id="PostCat__form">{% csrf_token %}
<input type="hidden" name="deyHidden" value="category_hidden">
{% comment %} {{ catForm | crispy }}
<input type="hidden" name="deyHidden" value="category_hidden"> {% endcomment %}
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<div class="form-group">
<h6 id="PostCat__show"></h6>
<img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostCat__img">
<button class="btn btn-outline-info" type="submit" id="PostCat__submit">Create</button>
</div>
</form>
the model.py
class Category(models.Model):
CatName = models.CharField(max_length=100)
the view.py
myFormCat = CatPostForm(request.POST)
CatName = int(float(request.POST.get('CatName')))
# print(CatName)
formset = formset_factory(FormsetForm, CatName=CatName)(request.POST)
if myFormCat.is_valid() and formset.is_valid():
for form_c in formset:
if not form_c.cleaned_data['CatName']:
Category.objects.get_or_create(CatName=CatName)
response_data = {
'SType': 'success',
'message': "Saved Successfully"
}
return HttpResponse(json.dumps(response_data), content_type="application/json")
the forms.py
class CatPostForm(forms.ModelForm):
class Meta:
model=Category
fields = ['CatName']
pls how can i do it so that i can successfully submit the form,
on your views.py
from django.forms import formset_factory
CatPostFormSet = formset_factory(CatPostForm)
catformset = CatPostFormSet() #this goes to your page context. do the validations here also after the post
on your form.html
<form method="post">
{{ formset.management_form }}
{{formset}}
</form>
I try to use Django forms but I have problems displaying all the fields on my Template.
I have created a form in the form.py file as:
class UploadCSVForm(forms.Form):
title = forms.CharField(max_length=255, help_text="Please type here", required=True)
csv_load = forms.FileField()
In my corresponding view I import the form as:
from myproject.myapp.forms import UploadCSVForm
and then in the specific view function I render the form as;
if request.method == 'GET':
....
....
form = UploadCSVForm()
ctx['form'] = form
return render_to_response(template, RequestContext(request, ctx))
Last in my template I call the form as:
<form id="file-uploader" method="post" enctype="multipart/form-data" action="{% url "layer" %}">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<button type="submit" id="upload-button" class="btn btn-danger">Upload</button>
</form>
I only get to see the csv_load but not the title.
What am I doing wrong here?