Using a html form from another project with Django - python

I am trying to use a html form from the internet with Django. However, after watching crazy amount of videos on youtube and reading through https://docs.djangoproject.com/en/1.10/topics/forms/ , I can't manage to make it work. When I click the submit button, Chrome tells me the "The form has submitted", but nothing else happens. It should log the user in and redirects to the index page.
registration_form.html
<div class="panel panel-info mt10 br-n bg-gradient-1 mw500 mauto">
<form id="contact" method="post" action="{% url 'feed:connection' %}">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="panel-body text-center p50 text-center">
<div class="section">
<p class="text-uppercase text-white ls100 fw700">Username</p>
{{ form.username.errors }}
<label for="username" class="field prepend-icon">
<input id="username" type="text" name="username" placeholder="Enter username" class="gui-input">
</label>
</div>
<div class="section">
<p class="text-uppercase text-white ls100 fw700">Password</p>
{{ form.password.errors }}
<label for="password" class="field prepend-icon">
<input id="password" type="password" name="password" placeholder="Enter password" class="gui-input">
</label>
</div>
<div class="panel-footer clearfix p10 ph15">
<button type="submit" class="button btn-primary mr10 pull-right text-uppercase text-white ls100 fw700">Sign In</button>
<!--<label class="switch ib switch-primary pull-left input-align mt10">
<input id="remember" type="checkbox" name="remember" checked="">
<label for="remember" data-on="YES" data-off="NO"></label> <span>Remember me</span>
</label> -->
</div>
<div class="section text-left pt20 pb10">Forget password?
<p><span class="text-white">Haven't yet registration? Sign up here</span></p>
</div>
<div class="section row">
<div class="col-md-6">Facebook</div>
<div class="col-md-6">Google +</div>
</div>
</div>
</form>
</div>
views.py
from django.views.generic.base import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
from .forms import LoginForm
# Pour faire afficher la page index
class IndexView(TemplateView):
template_name = 'feed/index.html'
# Pour se logger
class UserFormView(View):
form_class = LoginForm
template_name = 'feed/registration_form.html'
# display blank form
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# process form data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
user = form.save(commit=False)
# cleaned (normalized) data
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.username = username
user.save()
# returns User objects if credentials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('feed:index')
return render(request, self.template_name, {'form': form})
urls.py
from django.conf.urls import url, include
from . import views
app_name = "feed"
urlpatterns = [
# /feed/
url(r'^$', views.IndexView.as_view(), name='index'),
# /register/
url(r'^connection/$', views.UserFormView.as_view(), name='connection'),
]
forms.py
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput, min_length=8)
What is wrong with the code? Thank you for your time.

Related

How to select and save foreign key from templates in Django views?

I am new to Django and I was trying to select a foreign key from my html template and save it in my database. It worked fine in admin panel but when I created a template myself I could display all the keys but I got error while posting the form.
Here is the model, views and html code.
# urls.py
from django.contrib import admin
from django.urls import path
from Home import views
urlpatterns = [
path('', views.home, name="Home"),
path('postBlog', views.postBlog, name="Post-Blog"),
]
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from Home.models import Blog, User
# from Home.forms import BlogForm
# Create your views here.
def home(request):
return render(request, 'Home/HomePage.html')
def postBlog(request):
if request.method == 'POST':
title = request.POST.get('title')
author = request.POST.get('author')
blog = request.POST.get('blog')
date = request.POST.get('date')
time = request.POST.get('time')
form = Blog(title=title, author=author, body=blog, date=date, time=time)
form.save()
return render(request, 'Home/HomePage.html', {'dic': form})
else:
users = User.objects.all()
dic = {'users': users}
return render(request, 'Forms/Post-Blogs.html', dic)
# models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import forms
from django.forms import Form
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateField(default='2022-12-31')
time = models.TimeField(default='06:00:00')
def __str__(self):
return self.title
# html
<form action="/postBlog" method="post">
{% csrf_token %}
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput" placeholder="Enter title" name="title">
<label for="floatingInput">Title</label>
</div>
<div class="mb-3">
<select class="form-select" aria-label="Default select example" name="author">
<!-- <option selected>Gender</option> -->
{% for authors in users %}
<option value= {{authors.pk}}> {{authors}} </option>
{% endfor %}
</select>
</div>
<div class="form-floating mb-3">
<textarea class="form-control" placeholder="Enter blog" id="floatingTextarea2" style="height: 150px" name="blog"></textarea>
<label for="floatingTextarea2">Blog</label>
</div>
<div class="form-floating mb-3">
<input type="date" class="form-control" id="floatingdate" placeholder="Enter date" name="date">
<label for="floatingdate">Date</label>
</div>
<div class="form-floating mb-3">
<input type="time" class="form-control" id="floatingtime" placeholder="Enter time" name="time">
<label for="floatingtime">Time</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I got this error: Cannot assign "'2'": "Blog.author" must be a "User" instance.

Django is not recongizing a users password when login is attempted

When trying to create a simple web page with login and sign up i ran into the issue of django not recognzing the created user. In views.py i created a simple message that displays "Incorrect password or email" if user does not exist. I created a user and made sure that the password was correct when i inputed it into the login form however it still gave me the message of "Incorrect password or email". Instead of redirecting to home like a created user should it errored and i could not figure out why it is not accepting the password/email in the form.
views.py
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.models import User
def home(request):
return render(request, 'home.html')
def signup(request):
if request.method == "POST":
email = request.POST['email']
password = request.POST['password']
myuser = User(email=email)
myuser.set_password(password)
myuser.save()
messages.success(request, "Your account has been successfully created ")
return redirect('signin')
return render(request, 'signup.html')
def signin(request):
if request.method == "POST":
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, email = email, password = password)
if user is not None:
login(request, user)
email = user.email
messages.success(request, "Successfully Logged In")
return redirect ('home')
else:
messages.info(request, "Email or Password is Incorrect")
return render(request, 'signin.html')
return render(request, 'signin.html')
def signout(request):
pass
urls.py
from django.urls import path
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('', views.home, name = "home"),
path('signin', views.signin, name = "signin"),
path('signup', views.signup, name = "signup"),
]
urlpatterns += staticfiles_urlpatterns()
signup.html
<h1>Sign up</h1>
<form action = "/signup" method = "POST">
{% csrf_token %}
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name = "email" aria-describedby="emailHelp" placeholder = "example#example.com">
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name = "password">
</div>
<button type="submit" class="btn btn-primary">Sign up</button>
</form>
signin.html (login page)
<h1>Login</h1>
{%if messages%}
{%for message in messages%}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>Hey,</strong> {{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
<form action = "/signin" method = "POST">
{% csrf_token %}
<div class="row mb-3">
<label for="inputEmail3" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name = "email">
</div>
</div>
<div class="row mb-3">
<label for="inputPassword3" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id = "password" name = "password">
</div>
<div class="col-sm-10">
</div>
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
What is the status of your user. An inactive user is one that has its is_active field set to False. The default backend ModelBackend and RemoteUserBackend prohibits the inactive users from authenticating. You didn't specify user status. So please check the user status also.
You can improve this part as following:
myuser = User(email=email, is_active=True)
myuser.set_password(password)
myuser.save()
To set password you have to use set_password function.

Django users can't login after I create an account but admin can and i didnt create any registration form by only manually can add users

I've created a login page as a homepage and only by adding manually in Django administration can create a user. I didn't create a registration form and message error else statement in home viwes.py is working on the admin panel. If I login by user, I get CSRF token error
homepage
views.py
from django.shortcuts import redirect, render
from loginapp.models import Register
from django.contrib import messages
from django.contrib.auth import authenticate, login , logout
def home(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request,username=username, password=password)
if user is not None:
login(request, user)
return render(request, "home.html")
else:
messages.error(request, "Bad Creds!!")
return redirect('/')
return render(request, "home.html")
login page views.py
def index(request):
return render(request, "index.html")
login page name as index.html
<form id="stripe-login" method="POST" action="{% url 'home' %}">
{% csrf_token %}
<div class="trick" style="padding-bottom: 10px;">
<input type="text" name="username" required>
<label for="email">Username</label>
</div>
<div class=" trick" style="padding-bottom:10px;">
<input type="password" name="password" required>
<label for="password">Password</label>
</div>
<div class="field" style="padding-bottom:10px; padding-top: 10px;">
<input type="submit" name="submit" value="Continue">
</div>
<div class="reset-pass" style="padding-top: 20px;">
Forgot your password?
</div>
<div class="footer-link text-light" style="padding-top:10px;">
<span>
Don't have an account?
<a href="{% url 'signup' %}">
Request for a new account
</a>
</span>
</div>
</form>
for creating user you must use
User.objects.create_user() method
Ex: User.objects.create_user(username=username,email=email,password=password)

Django | can't see form {{form.username}}

I can't render form username on the template. like I want to to render the form fields automatically which I defined in forms.py file but it's not working. here you go below for my detailed files
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
My views
from .forms import CreateUserForm
Registration
def regPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'web/car-finder-home.html')
html
<form class="needs-validation" method="POST" action="">
{% csrf_token %}
<div class="mb-4">
<label class="form-label text-light" for="signup-name">Username</label>
{{ form.username }}
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-email">Email address</label>
<input class="form-control form-control-light" type="email" id="signup-email" placeholder="Enter your email" required />
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-password">Password <span class="fs-sm opacity-50">min. 8 char</span></label>
<div class="password-toggle">
<input class="form-control form-control-light" type="password" id="signup-password" minlength="8" required />
<label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label>
</div>
</div>
<div class="mb-4">
<label class="form-label text-light" for="signup-password-confirm">Confirm password</label>
<div class="password-toggle">
<input class="form-control form-control-light" type="password" id="signup-password-confirm" minlength="8" required />
<label class="password-toggle-btn" aria-label="Show/hide password"> <input class="password-toggle-check" type="checkbox" /><span class="password-toggle-indicator"></span> </label>
</div>
</div>
<div class="form-check form-check-light mb-4">
<input class="form-check-input" type="checkbox" id="agree-to-terms" required />
<label class="form-check-label" for="agree-to-terms">
<span class="opacity-70">By joining, I agree to the</span> Terms of use <span class="opacity-70">and</span> Privacy policy
</label>
</div>
<button class="btn btn-primary btn-lg w-100" type="submit">Sign up</button>
</form>
views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .forms import CreateUserForm
def regPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
# consider adding a redirect page here this is a good approach
else:
context = {'form':form}
return render(request, 'web/car-finder-home.html',context) # your forgot to add context
Now inside your template you can access the form...
I didn't add in core urls.py
from my_app_name import urls
urlpatterns = [
path('cars/', views.regPage, name="register"),
]
xD

How do I save form response as an object in Django's database?

I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.
class Chain(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User, on_delete=models.CASCADE)
year = models.CharField(max_length=10, default="20XX")
sem = models.CharField(max_length=30, default="Default Semester")
code = models.CharField(max_length=10, default="SUB-CODE")
slot = models.CharField(max_length=10, default="EX+EX")
last_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
This is my view in views.py file.
#login_required(login_url='/')
def create_course(request):
if request.method == 'GET':
return render(request, 'create_course.html', {})
elif request.method == 'POST':
name=request.POST['name']
year=request.POST['year']
sem=request.POST['sem']
code=request.POST['code']
slot=request.POST['slot']
newchain = Chain(
name=name,
year=year,
sem=sem,
code=code,
slot=slot,
)
newchain.user = request.user
newchain.save()
return redirect('success')
This is my HTML code for the form.
{% extends 'authmain.html' %}
{% block content %}
<h3> <p class="text-center"> Create a new Course Blockchain: </p> </h3>
<div class="card border-dark mb-3 mx-auto" align="center" style="width: 40rem;">
<div class="card-body">
<h5 class="card-title">
<form method='POST'>
{% csrf_token %}
<label for="year">Year: </label>
<input type="text" id="year" name="year" value=""><br>
<label for="code">Course Code: </label>
<input type="text" id="code" name="code" value=""><br>
<label for="name">Course Name: </label>
<input type="text" id="name" name="name" value=""><br>
<label for="slot">Slot: </label>
<input type="text" id="slot" name="slot" value=""><br>
<label for="sem">Semester: </label>
<input type="text" id="sem" name="sem" value=""><br>
<button class="btn btn-outline-primary" type="Submit"> Create </button>
</form>
</h5>
</div>
</div>
{% endblock %}
This is my urls.py.
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('register/', views.register, name="register"),
path('logout/', views.logoutuser, name="logoutuser"),
path('dashboard/', views.dashboard, name="dashboard"),
path('create_course/', views.create_course, name="create_course"),
path('success', views.success, name="success"),
]
This is the view function for success.
#login_required(login_url='/')
def success(request):
return render(request, 'success.html', {})
The issue is that you are not closing form tag in the authmain.html.
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<form action="{% url 'logoutuser' %}" method='POST'>
{% csrf_token %}
<button class="btn btn-outline-info mb-auto" type="submit">Logout</button>
----- CLOSING FORM TAG MISSING HERE ---
</li>
</ul>
and when you submit the form at Create Course, you actually trigger this form, which logs out the user. Add closing tag to the logout form and you'll fix your problem.
Sometimes debugging can be a bit tricky.
To save directly in the database in Django use Model.objects.create()
Chain.objects.create(user=request.user, name=name, year=year, sem=sem,
code=code, slot = slot)
You need to use a model form to achieve this
class MyForm(ModelForm):
class Meta:
model = MyModel
fields = []
And then you can do something like this:
form = MyForm(request.POST)
if form.is_valid():
new_item = form.save()
...
And it will save directly to the database.

Categories

Resources