My sign up form is not working with django python - python

I have a problem with my application the sign up is not creating profiles on the backend.
I have tried to use the django forms but I didnt like how they render so I wanted to use custom form but once I click button submit, nothing happens and I check on backend there's no profile.
My forms.py file looks like this
from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Gig
class GigForm(ModelForm):
class Meta:
model = Gig
fields = ['title','category','description', 'price', 'photo', 'status']
class SignUpForm(forms.ModelForm):
first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password' )
Models.py File like this
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.CharField(max_length=500)
about = models.CharField(max_length=500)
location = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.user.username
signup.html looks like this
<div class="container1">
<img src="{% static 'img/home-banner.jpg' %}" class="banner">
<form action="#" name="myForm" method="post" onsubmit="return(validate());">
{% csrf_token %}
<div class="container-fluid">
<div class="row">
<div class="well center-block">
<div class="well-header">
<h1 class="text-center "><b>Sign Up</b></h1>
</br>
<hr>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="glyphicon glyphicon-user"></i>
</div>
<input type="text" placeholder="First Name" class="form-control"
name="{{ form.first_name.name }}"
id="{{ form.first_name.id_for_label }}"
{% if form.name.value != None %}value="{{ form.first_name.value|stringformat:'s' }}"{% endif %}
maxlength="{{ form.first_name.field.max_length }}"
{% if form.name.field.required %}required{% endif %}>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="glyphicon glyphicon-user"></i>
</div>
<input type="text" placeholder="Last Name" name="txtlname" class="form-control"
name="{{ form.last_name.name }}"
id="{{ form.last_name.id_for_label }}"
{% if form.name.value != None %}value="{{ form.last_name.value|stringformat:'s' }}"{% endif %}
maxlength="{{ form.last_name.field.max_length }}"
{% if form.name.field.required %}required{% endif %}>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="glyphicon glyphicon-user"></i>
</div>
<input type="text" placeholder="User Name" name="txtlname" class="form-control"
name="{{ form.username.name }}"
id="{{ form.username.id_for_label }}"
{% if form.name.value != None %}value="{{ form.username.value|stringformat:'s' }}"{% endif %}
maxlength="{{ form.username.field.max_length }}"
{% if form.username.field.required %}required{% endif %}>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="glyphicon glyphicon-lock"></i>
</div>
<input type="password" minlength="8" maxlength="20" placeholder="Password" name="txtpass" class="form-control"
name="{{ form.password.name }}"
id="{{ form.password.id_for_label }}"
{% if form.password.value != None %}value="{{ form.password.value|stringformat:'s' }}"{% endif %}
maxlength="{{ form.password.field.max_length }}"
{% if form.password.field.required %}required{% endif %}>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="glyphicon glyphicon-envelope"></i>
</div>
<input type="email" class="form-control" name="txtmail" placeholder="E-Mail"
name="{{ form.email.name }}"
id="{{ form.email.id_for_label }}"
{% if form.password.value != None %}value="{{ form.email.value|stringformat:'s' }}"{% endif %}
maxlength="{{ form.email.field.max_length }}"
{% if form.password.field.required %}required{% endif %}>
</div>
</div>
</div>
</div>
<div class="row widget">
<div class="col-md-12 col-xs-12 col-sm-12">
<button class="btn btn-warning btn-block"> Submit </button>
</div>
</div>
</div>
</div>
</div>
</form>
Views.py looks like this
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
user.refresh_from_db()
username = form.cleaned_data.get('username')
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home.html')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})

Profile model has different fields from those you are passing in the signup form
in your Profile Model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.CharField(max_length=500)
about = models.CharField(max_length=500)
location = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.user.username
did you forget to create these fields in your forms.py
this link will help you

Related

Not able send data to the database in Django

I wanna create a appointment system but its not working now. I'dont have a error actually i just have a error and it's coming from views.py (messages.warning(request,"ERROR!")). When i opened the page its coming anyway i just wanna send my informations.
models.py: I created models but im not sure for policlinic and doctor because it doesn't seems like charfield text. It's a option field in HTML.
class Randevu(models.Model):
STATUS = (
('New', 'Yeni'),
('True', 'Evet'),
('False', 'Hayır'),
)
policlinic=models.ForeignKey(Policlinic,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE)
doctor=models.ForeignKey(Doctors,on_delete=models.CASCADE)
phone = models.CharField(max_length=15)
email = models.CharField(max_length=50)
date=models.DateField(null=True)
time=models.TimeField(null=True)
payment= models.CharField(max_length=50)
insurance= models.CharField(max_length=50)
note=models.TextField(max_length=200)
status = models.CharField(max_length=10, choices=STATUS,default='New')
ip=models.CharField(max_length=20,blank=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def str(self):
return self.user.username
class AppointmentForm(ModelForm):
class Meta:
model=Randevu
fields=['phone','email','date','time','payment','insurance','note']
views.py:
def randevu(request):
setting=Setting.objects.get(pk=1)
policlinic=Policlinic.objects.all()
doctor=Doctors.objects.all()
context={'setting':setting ,'doctor':doctor,'policlinic':policlinic}
if request.method=='POST':
form=AppointmentForm(request.POST)
if form.is_valid():
current_user=request.user
data=Randevu()
data.user_id=current_user.id
data.phone=form.cleaned_data['phone']
data.email=form.cleaned_data['email']
data.date=form.cleaned_data['date']
data.time=form.cleaned_data['time']
data.payment=form.cleaned_data['payment']
data.insurance=form.cleaned_data['insurance']
data.note=form.cleaned_data['note']
data.ip=request.META.get('REMOTE_ADDR')
data.save()
messages.success(request,"DONE! :)")
return render(request,'randevu.html',context)
messages.warning(request,"ERROR!")
return render(request,'randevu.html',context)
urls.py
urlpatterns = [
path('randevu',views.randevu,name='randevu') ]
randevu.html
<!-- MAKE AN APPOINTMENT -->
<section id="appointment" data-stellar-background-ratio="3">
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6">
<img src="{% static 'images/appointment-image.jpg' %}" class="img-responsive" alt="">
</div>
<div class="col-md-6 col-sm-6">
<!-- CONTACT FORM HERE -->
<form id="appointment-form" role="form" action="{% url 'randevu' %}" method="post">
<!-- SECTION TITLE -->
<div class="section-title wow fadeInUp" data-wow-delay="0.4s">
<h2>Randevu Alın</h2>
{%if messages%}
{%for message in messages%}
<div class="alert alert-{{message.tags}}"role="alert">
{{message}}
</div>
{%endfor%}
{%endif%}
</div>
{% csrf_token %}
<div class="wow fadeInUp" data-wow-delay="0.8s">
<div class="col-md-6 col-sm-6">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Your Email">
</div>
<div class="col-md-6 col-sm-6">
<label for="telephone">Telefon Numaranız</label>
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Phone">
</div>
<div class="col-md-6 col-sm-6">
<label for="date">Tarih</label>
<input type="date" name="date" id="date" value="" class="form-control">
</div>
<div class="col-md-6 col-sm-6">
<label for="time">Zaman</label>
<input type="time" name="time" id="time" value="" class="form-control">
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Poliklinik Seçiniz</label>
<select name="policlinic" class="form-control" id="policlinic">
{% for rs in policlinic %}
<option>{{rs.title}}</option>
{%endfor%}
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Doktor Seçiniz</label>
<select name="doctor" class="form-control" id="doctor">
{% for rs in doctor %}
<option>{{rs.name}}</option>
{%endfor%}
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Ödeme Yöntemi</label>
<select name="payment" class="form-control" id="payment">
<option>Nakit</option>
<option>Banka Kartı</option>
<option>Kredi Kartı</option>
<option>Diğer</option>
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="select">Sigorta</label>
<select name="insurance" class="form-control" id="insurance">
<option>SGK</option>
<option>AXA Sağlık Sigortası</option>
<option>Anadolu Sağlık Sigortası</option>
<option>Allianz Sağlık Sigortası</option>
<option>Akbank Sağlık Sigortası</option>
<option>Tamamlayıcı Türkiye Sağlık Sigortası</option>
<option>Diğer (Belirtiniz)</option>
</select>
</div>
<div class="col-md-12 col-sm-12">
<label for="Message">Belirtmek istediğiniz herhangi bir durum</label>
<textarea class="form-control" rows="5" id="note" name="note" placeholder="Notunuz"></textarea>
{%if user.id is not None%}
<button type="submit" class="form-control" id="cf-submit" name="submit">Submit Button</button>
{%else%}
Randevu oluşturmak için login olunuz!
{% endif %}
</div>
</div>
</form>
</div>
</div>
</div>
</section>
It's my appointment page:
enter image description here
Because get method is used to render the page
and in views.py you dont write
if request.method=='GET':
As a result, the error message is executed while there is no error
add this :
if request.method=='GET':

i can't create user in django

I am trying to create a login and signup feature on my website but for some reason, I can't create a user. and it's not showing any error.
I have done these before in another code but I don't know why it is not working in this one.
And also when I refresh the website, it asks if it should resubmit the form.
These are the codes below
index.html
<div class="main-register">
<div class="close-reg"><i class="fal fa-times"></i></div>
<ul class="tabs-menu fl-wrap no-list-style">
<li class="current"><i class="fal fa-sign-in-alt"></i> Login</li>
<li><i class="fal fa-user-plus"></i> Register</li>
</ul>
<!--tabs -->
<div class="tabs-container">
<div class="tab">
<!--tab -->
<div id="tab-1" class="tab-content first-tab">
<div class="custom-form">
<form method="post" action="" name="registerform">
{% csrf_token %}
{% for message in messages %}
<h4 style="color: red;">{{message}}</h4>
{% endfor %}
<label>Email Address * <span class="dec-icon"><i class="fal fa-user"></i></span></label>
<input name="email" type="email" placeholder="Your Mail" onClick="this.select()" value="">
<div class="pass-input-wrap fl-wrap">
<label >Password * <span class="dec-icon"><i class="fal fa-key"></i></span></label>
<input name="password" placeholder="Your Password" type="password" autocomplete="off" onClick="this.select()" value="" >
<span class="eye"><i class="fal fa-eye"></i> </span>
</div>
<div class="lost_password">
Lost Your Password?
</div>
<div class="filter-tags">
<input id="check-a3" type="checkbox" name="check">
<label for="check-a3">Remember me</label>
</div>
<div class="clearfix"></div>
<button type="submit" class="log_btn color-bg"> LogIn </button>
</form>
</div>
</div>
<!--tab end -->
<!--tab -->
<div class="tab">
<div id="tab-2" class="tab-content">
<div class="custom-form">
<form method="POST" id="registerform" class="main-register-form" name="registerform">
{% csrf_token %}
{% for message in messages %}
<h4 style="color: red;">{{message}}</h4>
{% endfor %}
<label >Full Name * <span class="dec-icon"><i class="fal fa-user"></i></span></label>
<input name="full_name" type="text" placeholder="Your Name" onClick="this.select()" value="">
<label>Email Address * <span class="dec-icon"><i class="fal fa-envelope"></i></span></label>
<input name="email" type="text" placeholder="Your Mail" onClick="this.select()" value="">
<div class="pass-input-wrap fl-wrap">
<label >Password * <span class="dec-icon"><i class="fal fa-key"></i></span></label>
<input name="password" type="password" placeholder="Your Password" autocomplete="off" onClick="this.select()" value="" >
<span class="eye"><i class="fal fa-eye"></i> </span>
</div>
<div class="filter-tags ft-list">
<input id="check-a2" type="checkbox" name="check">
<label for="check-a2">I agree to the Privacy Policy and Terms and Conditions</label>
</div>
<div class="clearfix"></div>
<button type="submit" class="log_btn color-bg"> Register </button>
</form>
</div>
</div>
</div>
<!--tab end -->
</div>
views.py
def index(request):
return render(request, 'index.html')
def signup(request):
if request.method == 'POST':
full_name = request.POST['full_name']
email = request.POST['email']
password = request.POST['password']
if User.objects.filter(email=email).exists():
messages.info(request, 'Email is taken')
return redirect('index.html')
else:
user = User.objects.create_user(full_name=full_name, email=email, password=password)
user.save()
user_model = User.objects.get(full_name=full_name)
new_profile = user_profile.objects.create(user=user_model, id_user=user_model.id)
new_profile.save()
return redirect('index.html')
else:
return render(request, 'index.html')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
models.py
from django.db import models
from django.contrib.auth import get_user_model
User =get_user_model()
# Create your models here.
class user_profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id_user = models.IntegerField()
location = models.CharField(max_length=120, blank=True)
def __str__(self):
return self.user.full_name

Remove ">" sign in Python Django Form Label

The result from the code below is something like this:
Name:
Field for name
"> Email", but without the "-signs, but including the >-sign
Field for email
Why is there a "> " before "Email" and how do I remove it?
The code I am using is the following:
forms.py:
from django import forms
class ContactForm(forms.Form):
full_name = forms.CharField(required=True, max_length=100)
from_email = forms.EmailField(required=True, max_length=100)
contact.html:
{% extends "index.html" %}
{% load static %}
{% block content %}
<!-- The Contact Modal -->
<div id="contactModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="container2">
<div class="row">
<div class="column">
<form method="POST">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" id="name" name="full_name" placeholder="Your name.." {{ form.full_name }}>
<label for="email">Email:</label>
<input type="text" id="email" name="from_email" placeholder="Your email.." {{ form.from_email
}}>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

Showing errors with LoginView in Django

I have a problem with displaying errors on the template for login page. I am using the Login built in view and I made a custom form which inherits from AuthenticationForm and I tried to override the clean() method but if the username or password is not correct is not displaying any ValidationErorr message. Any help?
I created a custom view because I need to inherit from a custom mixin for some restrictions.
my view:
class UserLoginView(IsAuthenticatedMixin, LoginView):
template_name = 'home/auth/login.html'
authentication_form = UserLoginForm
my form:
class UserLoginForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
def clean(self):
cleaned_data = super().clean()
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username is not None and password:
login = authenticate(self.request, username=username, password=password)
if login is None:
raise ValidationError('The username or password are incorrect')
return self.cleaned_data
url:
path('auth/login/', UserLoginView.as_view(), name='login'),
my template:
{% extends 'home/auth/base.html' %}
{% load widget_tweaks %}
{% block content %}
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<div class="row">
<div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
<div class="col-lg-6">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1>
</div>
<form class="user" method="POST">
{% csrf_token %}
<div class="form-group">
{% for error in form.non_field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% render_field form.username class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Username..." %}
</div>
<div class="form-group">
{% render_field form.password class="form-control form-control-user" id="exampleInputPassword" placeholder="Password" %}
</div>
<div class="form-group">
<div class="custom-control custom-checkbox small">
<input type="checkbox" class="custom-control-input" id="customCheck">
<label class="custom-control-label" for="customCheck">Remember Me</label>
</div>
</div>
<input type="submit" name="Login" class="btn btn-primary btn-user btn-block" value="Login">
<hr>
<a href="index.html" class="btn btn-google btn-user btn-block">
<i class="fab fa-google fa-fw"></i> Login with Google
</a>
<a href="index.html" class="btn btn-facebook btn-user btn-block">
<i class="fab fa-facebook-f fa-fw"></i> Login with Facebook
</a>
</form>
<hr>
<div class="text-center">
<a class="small" href="forgot-password.html">Forgot Password?</a>
</div>
<div class="text-center">
<a class="small" href="{% url 'register' %}">Create an Account!</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

Django login with custom form template

I'm using the Django authentication with my login form in my template, after i pressed the login button on the form the page refreshed but doesn't log me in and doesn't show the {{context}} error in the template.
My view:
def login_view(request):
if request.method == 'POST':
all_categories = Categories.objects.all()
all_websites = Website.objects.all()
all_discounts = Discount.objects.order_by('-id')
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/',categories=all_categories,websites=all_websites,discounts=all_discounts)
else:
context = 'wrong username or password'
all_categories = Categories.objects.all()
all_websites = Website.objects.all()
all_discounts = Discount.objects.order_by('-id')
return redirect('/',categories=all_categories,websites=all_websites,discounts=all_discounts,context=context)
My form (header.html)
<div class="col-md-3 top-info-cart text-right mt-lg-4">
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}.</p>
<p>logout</p>
{% else %}
<ul class="cart-inner-info">
<li class="button-log">
<a class="btn-open" href="#">
<span class="fa fa-user" aria-hidden="true"></span>
</a>
</li>
</ul>
<p>{{context}}</p>
{% endif %}
<!---->
<div class="overlay-login text-left">
<button type="button" class="overlay-close1">
<i class="fa fa-times" aria-hidden="true"></i>
</button>
<div class="wrap">
<h5 class="text-center mb-4">Login Now</h5>
<div class="login p-5 bg-dark mx-auto mw-100">
<form action="{% url 'frontend:login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label class="mb-2">User name</label>
<input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
<small id="emailHelp" class="form-text text-muted">We'll never share your informations with anyone else.</small>
</div>
<div class="form-group">
<label class="mb-2">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1"type="password">
</div>
<button type="submit" class="btn btn-primary submit mb-4" value="Login">Sign In</button>
<p>Don't have an account? SIGN UP </p>
</form>
</div>
<!---->
</div>
</div>
And my urls.py:
from django.urls import path
from .import views
app_name = 'frontend'
urlpatterns = [
#index
path('',views.index, name='index'),
#/discount/id
path('<id>/',views.single,name='single'),
#/category/category_name
path('category/<name>',views.category,name='category'),
#/signup
path('signup',views.signup,name='signup'),
#/logout
path('logout',views.logout,name='logout'),
#/login
path('login',views.login_view,name='login')
]
It's because of my authentication is wrong or my view function ? i been trying to fix this but still haven't figure it out. Hope someone can help me :)

Categories