Reputation: 21
Form.py from django import forms from .models import UserRegister from django.contrib.auth.forms import UserCreationForm from django.core.exceptions import ValidationError
form.py
from django import forms
from .models import UserRegister
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import ValidationError
class UserRegisterForm(UserCreationForm):
username = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'input-group'}))
email = forms.EmailField(max_length=70, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'input-group'}))
password1 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'input-group', 'id': 'password'}))
password2 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'input-group', 'id': 'password'}))
class Meta:
model = UserRegister
fields = ['username', 'email', 'password1', 'password2']
def clean_email(self):
email = self.cleaned_data.get('email')
if UserRegister.objects.filter(email=email).exists():
raise ValidationError('This email address is already in use.')
return email
def clean_username(self):
username = self.cleaned_data.get('username')
if UserRegister.objects.filter(username=username).exists():
raise ValidationError('This username is already in use.')
return username
def clean(self):
cleaned_data = super().clean()
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise ValidationError("Passwords do not match.")
return cleaned_data
model.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth.hashers import make_password
class UserRegister(models.Model):
username= models.CharField(max_length=50,unique=True)
email = models.EmailField(unique=True,max_length=70)
password = models.CharField(max_length=128)
class Meta:
verbose_name = "User Register"
verbose_name_plural = "User Register"
def save(self,*args,**kwargs):
self.password = make_password(self.password)
super(UserRegister,self).save(*args,**kwargs)
def __str__(self):
return self.username
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect ,Http404
from .forms import UserRegisterForm
from django.contrib import messages
from .models import UserRegister
products=[{
"slug": "Mustang-GT",
"About": """The Ford Mustang GT in its stunning white color is nothing short of a modern-day classic.
From the moment you lay eyes on it, the Mustang's sleek and muscular design commands attention and admiration.
The pristine white finish only adds to its allure, giving it a timeless, elegant look that stands out on the road.
Performance: Under the hood, the Mustang GT roars to life with its 5.0-liter V8 engine, delivering a thrilling 450 horsepower.
The acceleration is exhilarating, and the handling is precise, making every drive a memorable experience.
Whether you're cruising down the highway or taking on winding roads, the Mustang GT's performance is unmatched in its class.
Interior: Step inside, and you're greeted with a blend of classic muscle car ambiance and modern sophistication.
The leather seats are comfortable and supportive, perfect for long drives. The dashboard is well-designed, with intuitive controls
and a high-quality infotainment system that keeps you connected and entertained. Driving Experience: Driving the Mustang GT is an absolute joy.
The sound of the engine is music to any car enthusiast's ears, and the responsive steering makes you feel in complete control.
The car's suspension strikes a perfect balance between comfort and sportiness, ensuring a smooth ride even on less-than-perfect roads.
Conclusion: The Ford Mustang GT in white is a perfect blend of beauty, power, and sophistication. It's a car that not only performs
exceptionally well but also turns heads wherever it goes. Whether you're a long-time Mustang fan or new to the world of muscle cars,
this vehicle will exceed your expectations. Highly recommended for anyone looking for a thrilling and stylish driving experience.""",
"image": "images/car.jpg"
}]
def Home(request):
return render(request, "home.html")
def Login(request):
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form_info = UserRegister(username=form.cleaned_data.get('username'), email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password1'))
form_info.save()
messages.success(request, 'Your account has been created!')
return HttpResponseRedirect('/Products')
else:
print("Form is not valid")
print(form.errors)
else:
form = UserRegisterForm()
return render(request, 'login.html', {'form': form})
def Products(request):
return render(request, "products.html")
def about_product(request, slug):
for product in products:
if product["slug"] == str(slug):
return render(request, "about_product.html", {"product": product})
raise Http404("Product not found")
login.html {% extends "base.html" %}
{% block title %}
Home
{% endblock %}
{% load static %}
{% block css_files %}
<link rel="stylesheet" href="{% static 'reviews/login.css' %}">
{% endblock %}
{% block content %}
<form method="POST" action="/Products">
{% csrf_token %}
<div class="input-section">
<div class="input-group">
<label for="{{ form.username.id_for_label }}">Username</label>
{{ form.username }}
{% if form.username.errors %}
<div class="error-message">
{% for error in form.username.errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
</div>
<div class="input-group">
<label for="{{ form.email.id_for_label }}">Email</label>
{{ form.email }}
{% if form.email.errors %}
<div class="error-message">
{% for error in form.email.errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
</div>
<div class="input-group">
<label for="{{ form.password1.id_for_label }}">Password</label>
{{ form.password1 }}
{% if form.password1.errors %}
<div class="error-message">
{% for error in form.password1.errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
</div>
<div class="input-group">
<label for="{{ form.password2.id_for_label }}">Confirm Password</label>
{{ form.password2 }}
{% if form.password2.errors %}
<div class="error-message">
{% for error in form.password2.errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
</div>
<button class="submit-btn">Sign In</button>
</div>
</form>
{% endblock %}
Error:-
For the past few days, I have been encountering an issue where I am unable to get form data into the database. Additionally, I am now getting the following error:
type object 'UserRegister' has no attribute 'USERNAME_FIELD'.
Upvotes: 0
Views: 47
Reputation: 1
Hi I believe your issue lies in it seems you are trying to create a custom user model.
This post has a similar issue to you., however, the solution is detailed below.
Documentation for CustomUser
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth.hashers import make_password
class UserRegister(AbstractUser):
username= models.CharField(max_length=50,unique=True)
email = models.EmailField(unique=True,max_length=70)
password = models.CharField(max_length=128)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
class Meta:
verbose_name = "User Register"
verbose_name_plural = "User Register"
def save(self,*args,**kwargs):
self.password = make_password(self.password)
super(UserRegister,self).save(*args,**kwargs)
def __str__(self):
return self.username
Upvotes: 0