So my form was working just fine until i played around with my frontend...changing the look of the system. But i dont think this has an effect on my forms but surprisingly all my forms are no longer saving data to the database!! Some help here guys. Here is my views.py
from django.contrib.auth.models import User
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from .forms import *
# Create your views here.
def register(request):
form = RegistrationForm()
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'User successfully registered!')
return redirect('home')
else:
form = RegistrationForm()
return render(request, 'accounts/register.html', {'form': form} )
def login(request):
if request.method == 'POST':
username = username.POST['username']
password = request.POST['password']
try:
user = Account.objects.get(username=username)
except:
messages.error(request, 'username does not exist')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, 'Invalid username Or Password')
return render(request, 'accounts/login.html', {} )
models.py
from distutils.command.upload import upload
import email
from django.db import models
from django.conf import settings
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager
class MyAccountManager(BaseUserManager):
def _create_user(self, email, username, profile_pic, address, phone_number, car, details, password):
if not email:
raise ValueError("User must have an email")
if not username:
raise ValueError("User must have a username")
user = self.model(
email = self.normalize_email(email),
username = username, profile_pic=profile_pic, address = address,
phone_number = phone_number, car=car, details=details, password=password
)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, username, profile_pic=None, address=None, phone_number=None, car=None, details=None, password=None):
return self._create_user(email, username, profile_pic, address, phone_number, car, details, password)
def create_superuser(self, email, username, password):
"""
Creates and saves a superuser with the given email, name and password.
"""
user = self.create_user(email=email,
username=username,
password=password,
)
user.is_admin = True
user.is_superuser = True
user.is_staff = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(verbose_name='username', unique=True, max_length=60, null=True)
profile_pic = models.ImageField(blank=False, null=True)
address = models.CharField(verbose_name='address', max_length=200, null=True)
phone_number = models.IntegerField(verbose_name='phone_number', null=True)
car = models.CharField(verbose_name='car' , max_length=60, blank=False, null=True)
details = models.CharField(verbose_name='details', unique=True, max_length=60, blank=False, null=True)
last_login = models.DateTimeField(verbose_name='last_login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = MyAccountManager()
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
@property
def profile_picURL(self):
try:
url = self.profile_pic.url
except:
url = ''
return url
class UserProfile(models.Model):
user = models.OneToOneField(Account, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to = 'static/images')
forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from accounts.models import Account, UserProfile
class RegistrationForm(UserCreationForm):
email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'email'}), help_text='Required. Add a valid email address')
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'username'}))
#profile_pict = forms.ImageField()
address = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'address'}))
phone_number = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'phone_number'}))
car = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'car'}))
details = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'details'}))
profile_picture = forms.ImageField()
class Meta:
model = Account
fields = ('email', 'username', 'address', 'phone_number', 'car', 'details')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('user', 'avatar')
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
return avatar
and the template:
{% load static %}
{% include 'others/base.html' %}
{% include 'others/sidebar.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div style="margin-top: 58px; margin-left: 300px; margin-right: 20px; height: 45px;">
<h3 style="text-align: center; color: black;">Register New Drivers</h3>
<div style=" height: 600px; padding-top: 60px; padding-left: 50px; background-color: gainsboro;">
<form method="POST">
{% csrf_token %}
<div >
<div >
{{ form.email|as_crispy_field }}
</div>
<div >
{{ form.username|as_crispy_field }}
</div>
<!--<div >
{{ form.profile_picture|as_crispy_field }}
</div>-->
<div >
{{ form.address|as_crispy_field }}
</div>
<div >
{{ form.phone_number|as_crispy_field }}
</div>
<div >
{{ form.car|as_crispy_field }}
</div>
<div >
{{ form.details|as_crispy_field }}
</div>
<input style="margin-left: 10px;" type="submit" href ="{% url 'home' %}" value="Sign Up">
</div>
</form>
</div>
</div>
{% endblock %}
I would really appreciate your help...its giving me a headache and cant understand why really the data isnt being saved to my database!!!
CodePudding user response:
It seems that form is not going to register
view, kindly check it as the name you have mentioned to redirect is home
in href
of input tag (maybe the name is register
or something else check it), also suggest not to mention anything like action
or href
as Django by default take current page route, so:
Template file:
<form method="POST">
{% csrf_token %}
<div >
<div >
{{ form.email|as_crispy_field }}
</div>
<div >
{{ form.username|as_crispy_field }}
</div>
<!--<div >
{{ form.profile_picture|as_crispy_field }}
</div>-->
<div >
{{ form.address|as_crispy_field }}
</div>
<div >
{{ form.phone_number|as_crispy_field }}
</div>
<div >
{{ form.car|as_crispy_field }}
</div>
<div >
{{ form.details|as_crispy_field }}
</div>
<input style="margin-left: 10px;" type="submit" value="Sign Up">
</div>
</form>
views.py:
def register(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'User successfully registered!')
return redirect('home')
else:
form = RegistrationForm()
return render(request, 'accounts/register.html', {'form': form} )
CodePudding user response:
RegisterForm doesn't save data because form.is_valid() is False.
for your RegisterForm
as long as you are using file(image) field in your form you should add enctype to your form tag in template, following :
<form method="POST" entype="multipart/form-data">
and inside your register view you should instantiate your form like this:
form = RegistrationForm(request.POST, request.FILES)