django inserting data into db using html template - html

I'm new in django. I'm trying to connect already made an html file to django backend without rebuilding whole file.
Already created forms and views in python but have no idea what to put into html file.
view class:
class signup(View):
template = loader.get_template('signup.html')
form_class = UserRegistrationForm
def get(self, request):
form = self.form_class(None)
return render(request, 'signup.html', {'form': form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
current_user = form.save(commit=False)
email = form.cleaned_data['email']
password = form.cleaned_data['password']
current_user.set_password(password)
current_user.save()
userToAuthenticate = authenticate(email=email, password=password)
if userToAuthenticate is not None:
if userToAuthenticate.is_active:
login(request, userToAuthenticate)
return redirect('siteViews:index')
return render(request, 'signup.html', {'form': form})
form code:
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['email', 'password']
and html code:
<div id="registersquare">
<div id="panel">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="email">Email adress:</label>
<input type="email" id="username" name="email}">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<label for="password">Repeat password:</label>
<input type="password" id="password" name="repeatedpassword">
<label class="control-label col-sm-2" for="password">{{ field.label_tag }}</label>
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox"><a style="color: #999999;" href="#">I Accept Website Terms And Conditions.</a></label>
<input type="submit" value="Sign up">
</div>
</form>
</div>
</div>
anyone can explain how to do it?
cheers

You hav already created a Form, which is not Django's form, so you dont actually have to write anything in forms.py, as the purpose of it is to create an form based on the model structure and perform validations according to the fields defined.
Now you have to fetch data from form and perform the validation and checks by yourself in views. So the post would be
def post(self, request):
email = request.POST.get('email') # get value in name="email" field
password = request.POST.get('password')
repeatedpassword = request.POST.get('repeatedpassword')
if password == repeatedpassword: # manual validation to check if both string are same
# Other Validations code here and
# Register or Login etc functions here
return render(request, 'signup.html', {'form': form})

You need to delete the labels and inputs from your html file and add this tag after the {% csrf_token %}, {{form.as_p}}, that's a start. You are also using an older version of Django, the way I can tell is because when you defined your ModelForm you wrote forms.ModelForm when it has been changed to just ModelForm, to upgrade write
pip install -U Django
You essentially created two forms, one with just html and one with Django only you did not apply your ModelForm to your html file instead you just made a html form instead of a html rendered Django ModelForm.

Related

I am trying to create authentication system in Django. My code is failing to authenticate the user

<form method="post" action="/" class="mb-2">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Your Username" Required>
</div>
<div class="form-group">
<label for="pass1">Password</label>
<input type="password" class="form-control" id="pass1" name="pass1" placeholder="Enter Your Password" Required>
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
This is the form from home.html
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
user = authenticate(username=username, pass1=pass1)
if user is not None:
login(request, user)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
this is home view from views.py in 'main' app.
so as u can see from the home view if user is present or signuped it should redirect user to room.html page but when i try to do it it redirects to signup page which shouldnt happen if user is already present in data base. i am kind of lost here as i dont know what kind of solution i should search for. from what i have observed i think home view is not able to get data from the form in home.html
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns=[
path("",views.home,name="home"),
path("signup",views.signup,name="signup"),
path("rooms",views.rooms,name="rooms"),
]
for reference here is the urls.py from 'main' app
Change this,
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
user = authenticate(username=username, pass1=pass1)
if user is not None:
login(request, user)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
to this:
def home(request):
if request.method == 'POST':
username = request.POST.get('username')
pass1 = request.POST.get('pass1')
auth = authenticate(username=username, password=pass1)
if auth:
login(request, auth)
return render(request,"main_tem/room.html")
else:
return redirect('signup')
return render(request,"main_tem/home.html")
You should be go to go.

CSRF verification failed. Request aborted [New] 2021

I am completely tired with the csrf issue. I have created a sign in form and register form.
I am able to login and logout, even register a user.
The main problem I am facing is the refresh-after-signin.
After signing in, if I refresh the page it simply gives a csrf verification failed error.
I have literally searched for it since past two days with no solution, all the answers are almost 4-5 years older, which are not helping.
This is the views.py signin function.
def signin(request):
if request.method=="POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password)
if user is not None:
login(request,user)
messages.success(request,"Logged in Successfully!")
return render(request,'authtest/index.html')
else:
messages.error(request,"Bad Credentials")
return redirect('index')
return render(request,'authtest/signin.html')
This is the HTML form that is returning POST request
<form action="{% url 'signin' %}" method="POST">
<!-- I have no idea what this thing does -->
{% csrf_token %}
<!-- I have no idea what this thing does end -->
<input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
<label for="username">UserName</label>
<input type="text" name="username" id="username" required>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<button type="submit">SignIn</button>
</form>
Due to some security issues to keep each user's session safe, it is not possible to authenticate and render the url in the same view functions.
Therefore, you must perform the rendering operation in another URL after redirecting
something like this
def signin(request):
if request.method=="POST":
........
if user is not None:
..........
return redirect ('dashboard')\
and that dashboard func is like this
def dashboard(request):
.......
return redirect ('dashboard')

How to pass data from html to django view to use in URL?

I'm getting an error while working with django urls. I want to pass the value of Name input field after i hit the submit button.
Let's say I've this html form-
<form method='POST' action="{% url 'submittedform' slug=[firstname] %}">
{% csrf_token %}
<div>
<label for="name">Name</label>
<input type="text" name="firstname" id="name">
</div>
<div>
<label for="email">Email</label>
<input type="email" name="useremail" id="email">
</div>
<div>
<label for=phone>Phone</label>
<input type="text" name="phonenumber" id="phone" maxlength="12" pattern="[0-9]{10}">
</div>
<input type="submit" name="" id="btn" value="Submit">
</form>
Here's my view that handling it-
def submittedform(request, slug):
if request.method == 'POST':
# do something here
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')
and here's my view that's handling it-
urlpatterns = [
path('index/',views.index ,name='index'),
path('welcome/<slug:slug>/',views.submittedform, name='submittedform')
]
I'm not using django forms. How can i get welcome/name working.
If you want to pass a variable to an URL you need redirect with the value:
from django.shortcuts import redirect
return redirect("/welcome/%s/" % slug)
Change the following line
<!-- Removed the bracket -->
<form method='POST' action="{% url 'submittedform' slug=firstname %}">
<!-- Children tags here -->
</form>
Now the variables are accessible in view like
def submittedform(request, slug):
if request.method == 'POST':
name = request.POST['name']
# and more variables as you need
# do something here
# do redirect here or give some message that their form has been
# submitted for their confirmation
return render(request,'myapp/welcome.html')
return render(request,'myapp/welcome.html')

creating forms in django - error in output

I have the following code in various places to attempt to produce a form in Django that takes data and writes it to the database
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import TeacherSignup
"""def teachers(request):
return render(request,'teachers/teachers.html')
"""
def teachers(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = TeacherSignup(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = TeacherSignup()
return render(request, 'teachers/teachers.html', {'form': form})
teachers.html (this is the html page that contains the form)
<form action="/teachers/" method="post" style="border:1px solid #ccc">
{% csrf_token %}
{{ form }}
<div class="container">
<label><b>Email</b></label>
<input id="email" input type="text" placeholder="Enter Email" name="email" required>
<label><b>Centre/School Name</b></label>
<input id="school_name" input type="text" placeholder="Enter School or Centre Name" name="school_name" required>
<label><b>Password</b></label>
<input id="password" input type="password" placeholder="Enter Password" name="password" required>
<label><b>Repeat Password</b></label>
<input id="password_repeat" input type="password" placeholder="Repeat Password" name="password_repeat" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</html>
forms.py
from django import forms
class TeacherSignup(forms.Form):
email=forms.CharField(label='email',max_length=100)
school_name=forms.CharField(label='school_name',max_length=100)
password=forms.CharField(label='password',max_length=100)
password_repeat=forms.CharField(label='password_repeat',max_length=100)
On running the server however, it produces TWO forms: The form I've created in the html and the one presumably created in the forms.py.
How do I use the form in teachers.html (which is at the end of the page) and use this created form to write data to the database, or does Django require that I created it using the forms.py?
A detailed explanation would be appreciated, with examples if possible.
In your template you can render field by field of your form
Something like this in teachers.html
<form action="/teachers/" method="post" style="border:1px solid #ccc">
{% csrf_token %}
<div class="container">
<label><b>Email</b></label>
{{ form.email }}
<label><b>Centre/School Name</b></label>
{{ form.school_name }}
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
and do the same thing for the rest
if you want to add placeholder attribute you need to add widget param to your fields and the same if you want that your passwords fields could hide text
forms.py
from django import forms
class TeacherSignup(forms.Form):
email=forms.CharField(label='email',max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter Email'})
school_name=forms.CharField(label='school_name',max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter School or Centre Name'})
password=forms.CharField(label='password',max_length=100, widget=forms.PasswordInput)
password_repeat=forms.CharField(label='password_repeat',max_length=100, widget=forms.PasswordInput)

Form error in a Django form with Bootstrap tagsinput plugin

I am using Bootstrap/Tagsinput for adding tags in a Django input form.
Problem
The first field is where I want the tags added and the second field is a simple text field. I am able to add the tags in the first field and a normal text in the second field. But, when I submit the form the input values get removed and am returned to the original form. The django form.errors indicates that the second field is empty with a This field is required message even though I had entered a text! What am I missing?
form.errors
Is returning
<ul class="errorlist"><li>experiments<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Here are the related files
tags_add.html
I am using a custom html rather than the django's forms.as_table. All required css and min.js have been added in the html file.
<form id="defaultForm" method="post" action="" class="form-horizontal">{% csrf_token %}
<div class="form-group">
<label class="col-lg-3 control-label">Tags:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="aa" class="form-control" value="" data-role="tagsinput" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Experiments:</label>
<div class="col-lg-5">
<input type="text" name="tags" id="exp_id" class="form-control" value="" />
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-3">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
forms.py
class TagsForm(ModelForm):
tags = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'add tags'}), required=True )
experiments = forms.CharField( widget=forms.TextInput(attrs={'size':'20', 'placeholder':'expid'}), required=True )
def __init__(self, *args, **kwargs):
super(TagsForm, self).__init__(*args, **kwargs)
class Meta:
model = Tags
fields = '__all__'
views.py
def view_tags(request,formtype):
form_type = formtype
if request.method == "POST":
form = form_type(request.POST or None)#, extra=extra_additives)
if form.is_valid():
instances = form.save(commit=False)
temp_str= str(instances)
print temp_str
experiment_tags = temp_str
return HttpResponse(experiment_tags)
else:
print "from view_tags {0}".format(form.errors)
return HttpResponse(form.errors)
else:
form = TagsForm()
return render(request, 'tags_add.html', {'form': form})
models.py
class Tags(models.Model):
tags = models.CharField(max_length=1000)
experiments = models.CharField(max_length=1000)
def __str__(self):
return ':'.join([self.tags, self.experiments])
I got it working by adding the following to a scripts tag in the html file:
$("input[name='tags']").tagsinput({
confirmKeys:[13] //-- Only enter
});