Django - Form not showing up on template only the button - python

I've been trying everything, but I can't figure out why it's not showing-up. I searched everywhere on this site with no luck. The button shows up but when I click than it give me a TypeError at get_profile, saying:
Exception Value:
get_profile() got an unexpected keyword argument 'username'
Here's my code:
models.py
class CustomUser(AbstractBaseUser):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', max_length=50, unique=True, db_index=True)
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __unicode__(self):
return self.username
forms.py
from django import forms
from apps.accounts.models import CustomUser
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(widget=forms.TextInput, label='email')
username = forms.CharField(widget=forms.TextInput, label='username')
password1 = forms.CharField(widget=forms.PasswordInput, label='Enter your password')
password2 = forms.CharField(widget=forms.PasswordInput, label='Re-type your password')
first_name = forms.CharField(widget=forms.TextInput, label='First Name')
last_name = forms.CharField(widget=forms.TextInput, label='Last Name')
class Meta:
model = CustomUser
fields = ['email', 'username', 'password1', 'password2', 'first_name', 'last_name']
def clean(self, password1, password2):
cleaned_data = super(RegistrationForm, self).clean()
if password1 in self.cleaned_data and password2 in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("Passwords don't match. Please enter both fields again")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
views.py
def register(request):
"""
User Registration View
"""
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
CustomUser = form.save()
CustomUser.save()
return redirect('home.html')
else:
form = RegistrationForm()
return render_to_response('register.html', {
'form': form,
}, context_instance=RequestContext(request))
def get_profile(request):
username = CustomUser.username
return render_to_response(request, 'profile.html', {'username': username})
urls.py
urlpatterns = patterns ('',
url(r'register$', 'apps.accounts.views.register', name='register'),)
register.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<body>
{% block body %}
<form method='POST' action="register" enctype= 'multipart/form-data'>{% csrf_token %}
<table>{{ form.ast_table}}</table>
<input type='submit' class="btn btn-default" value="Register" />
</form>
{% endblock %}
</body>
</html>

It seems that you don't have the right signature for the get_profile view function.
You should check your urls, you probably have something like
url(r'^profile/(?P<username>\w+/$', get_profile),
If so, your view should be
def get_profile(request, username):
#you can get the user
user = CustomUser.objects.get(username=username)
return render_to_response(request, 'profile.html', {'username': username, 'user': user})

CustomUser is the class. You need to fetch an instance before you can actually fetch its username.
Eg:
CustomUser.objects.get(pk=1).username
Gives you the username of the first user.
Also, its supposed to be {{form.as_table}} not ast_table

Related

I don't know why my django signup form can't create the new user

I made a signup form and a signup view in the Django project. But it seems that 'create_user' does not work. There is no error. Signup view just sends the browser to Home without creating a new user object
The user model is using email as a username.
I tried to do this with ModelForms but it was the same.
I don't know why happens this.
users/forms.py
class StudentSignUpForm(forms.Form):
first_name = forms.CharField()
last_name = forms.CharField()
email = forms.EmailField(
widget=forms.EmailInput(attrs={"placeholder": "Enter your emaill adress"})
)
password = forms.CharField(
widget=forms.PasswordInput(attrs={"placeholder": "Enter the Password"})
)
password_confirm = forms.CharField(
widget=forms.PasswordInput(attrs={"placeholder": "Confirm the Password"})
)
def clean_email(self):
email = self.cleaned_data.get("email")
try:
models.User.objects.get(email=email)
raise forms.ValidationError("This email already exists.")
except models.User.DoesNotExist:
return email
def clean_password_confirm(self):
password = self.cleaned_data.get("password")
password_confirm = self.cleaned_data.get("password_confirm")
if password != password_confirm:
raise forms.ValidationError("Password confirmation does not match.")
else:
return password
def save(self):
first_name = self.cleaned_data.get("first_name")
last_name = self.cleaned_data.get("last_name")
email = self.cleaned_data.get("email")
password = self.cleaned_data.get("password")
user = models.User.objects.create_user(email, password)
user.first_name = first_name
user.last_name = last_name
user.save()
users/views.py
class StudentSignupView(FormView):
template_name = "users/student_signup.html"
form_class = forms.StudentSignUpForm
success_url = reverse_lazy("core:home")
def form_vaild(self, form):
form.save()
email = form.cleaned_data.get("email")
password = form.cleaned_data.get("password")
user = authenticate(self.request, username=email, password=password)
if user is not None:
login(self.request, user)
return super().form_valid(form)
templates/users/student_signup.html
{% extends "base.html" %}
{% block page_title %}
Student Sign up
{% endblock page_title %}
{% block movie_search_bar %}
{% endblock movie_search_bar %}
{% block people_search_bar %}
{% endblock people_search_bar %}
{% block content %}
<form method="post" action="{% url 'users:student_signup' %}">
{% csrf_token %}
{{form.as_p}}
<button>Sign up</button>
</form>
{% endblock content%}
users/urls.py
from django.urls import path
from users import views as user_views
app_name = "users"
urlpatterns = [
path("students/", user_views.StudentList.as_view(), name="list"),
path(
"students/<int:pk>", user_views.StudentProfile.as_view(), name="student_profile"
),
path("students/search/", user_views.SearchView.as_view(), name="search"),
path("users/login/", user_views.LoginView.as_view(), name="login"),
path("users/logout/", user_views.log_out, name="logout"),
path("users/signup/", user_views.sign_up, name="signup"),
path(
"users/signup/student",
user_views.StudentSignupView.as_view(),
name="student_signup",
),
]
users/models.py
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
from django.db import models
class CustomUserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("Users require an email field")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
"""User Model Definition"""
SCHOOL_ACCA_ROMA = "acccademia_belle_arti_di_roma"
SCHOOL_CHOICES = ((SCHOOL_ACCA_ROMA, "Accademia Belle Arti di Roma"),)
ACCOUNT_TYPE_STUDENT = "student"
ACCOUNT_TYPE_PUBLIC = "public"
ACCOUNT_TYPE_CHOICES = (
(ACCOUNT_TYPE_STUDENT, "Studente"),
(ACCOUNT_TYPE_PUBLIC, "Publico"),
)
username = None # email을 username으로 사용하기 위해 Abspython manage.py migratetractUser의 username을 none으로 override.
email = models.EmailField(
_("email address"), unique=True
) # _ 는 ugettext_lazy()의 별칭. 언어설정에 따라 출력되는 문자열을 변환해주는 함수다.
USERNAME_FIELD = "email" # email을 username처럼 사용하기.
REQUIRED_FIELDS = (
[]
) # AbsractUser에는 email이 Required로 잡혀있으나 USERNAME_FIELD로 사용되는 필드는 REQUIRED에 있으면 안된다.
school = models.CharField(
_("accademia"), choices=SCHOOL_CHOICES, max_length=50, null=True, blank=True
)
avatar = models.ImageField(upload_to="user_avatars", null=True, blank=True)
biography = models.TextField(_("biography"), null=True, blank=True)
account_type = models.CharField(
_("tipo d'account"),
choices=ACCOUNT_TYPE_CHOICES,
max_length=50,
null=True,
blank=True,
)
objects = CustomUserManager()
def __str__(self):
return self.email

Keeping user logged in after changing password (Django) custom user model

I have a customized Django model. My problem is whenever I update any of the user profile information, it logged out. I know that Django logged out the user after changing their password and I have to use update_session_auth_hash() function. However, in my case it didn't work and I don't want to use Django changePasswordForm because I want the user to be able to change all his information in one form. Any help will be appreciated.
This is my custom user model:
class MyUser(AbstractBaseUser):
firstName = models.CharField(max_length=100, validators =[firstnameCheck] )
lastName = models.CharField(max_length=100, validators =[lastnameCheck] )
#nationalID = models.IntegerField(unique=True)
nationalID = models.CharField(max_length=10, validators=[RegexValidator(r'^[0-9]{10}$')], unique=True)
GENDER_CHOICES = [('male', 'Male'), ('female', 'Female')]
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)
dateofbirth = models.DateField(auto_now=False, auto_now_add=False)
email = models.EmailField(max_length=100, unique=True)
password = models.CharField(max_length=100)
password_confirm = models.CharField(max_length=100, default='')
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 = 'email' #enable authentication by using email instead of default 'username'
REQUIRED_FIELDS = ['firstName', 'lastName', 'nationalID','gender','dateofbirth','password','password_confirm']
objects = MyUserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self,app_label):
return True
This is my view
def update_admin(request,id):
context = {}
if request.method == "POST":
pi = MyUser.objects.get(pk=id)
fm = UserRegisterationForm(request.POST,instance=pi)
if fm.is_valid():
request.user.set_password(fm.cleaned_data['password1'])
fm.save()
update_session_auth_hash(request, request.user)
messages.add_message(request, messages.INFO, 'The profile updated successfully.')
context['form'] = fm
else:
pi = MyUser.objects.get(pk=id)
fm = UserRegisterationForm(instance=pi)
context['form'] = fm
return render(request,'project/update_admin.html', context)
The problem is that the change of the password will make the session invalid.
See doc
You could also heredity the django change password form for your own form.
You could do something like this.
Template:
<form method="POST" class="contact-form" action="{% url 'change-password' %}"> ##make sure the action links to the `changepassword` view
{% csrf_token %}
<input type="password" name="password" required id="password" pattern="^[a-zA-Z0-9]{6,}$">
</div>
<button type="submit">Submit</button>
</form>
Views.py:
def changepassword(request):
user = request.user
if 'password' in request.POST:
user.set_password(request.POST['password'])
return render(request, 'project/changepassword.html')
This will keep your user logged in after the password change, but you will need to add validation handling & error handling to this to make it a viable solution.

Custom user creation form always invalid in Django

I am working on building a new Django Website and am trying to make an abstract base class and using forms to fill it out. I thought I was doing it correctly, but whenever I try to fill out the form it is always invalid. I am wondering if anyone can help me with this problem. All of the other help I find online does not help me. Here is my code. Thanks
My forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = Profile
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def __init__(self, regLinkModel):
super(CustomUserCreationForm, self).__init__()
self.linkInfo = regLinkModel
def save(self, commit=True):
user = super(CustomUserCreationForm, self).save(commit=False)
user.username = self.cleaned_data['username']
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['fname']
user.last_name = self.cleaned_data['lname']
user.password1 = self.cleaned_data['password1']
user.password2 = self.cleaned_data['password2']
if commit:
user.save()
return user
My Models.py
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, password):
if not email:
raise ValueError("User needs email address")
if not username:
raise ValueError("User needs username")
if not first_name:
raise ValueError("User needs first name")
if not last_name:
raise ValueError("User needs last name")
user = self.model(
email=self.normalize_email(email),
password = password,
username =username,
first_name = first_name,
last_name = last_name,
)
user.set_password(password1)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password, first_name, last_name):
user = self.create_user(
email=self.normalize_email(email),
password = password,
username =username,
first_name = first_name,
last_name = last_name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
def count_total_profiles(self):
return Profile.objects.filter(license_id= self.id).count()
def count_active_profiles(self):
return Profile.objects.filter(license_id= self.id).filter(is_active=True).count()
def is_expired(self):
return timezone.now() > self.expire_date
def __repr__(self):
return self.name
class Profile(AbstractBaseUser):
email =models.EmailField(verbose_name='email', max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True, default=" ")
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=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)
first_name = models.CharField(max_length=30, default=" ")
last_name = models.CharField(max_length=30, default=" ")
password1 = models.CharField(max_length=20,default= " ")
password2 = models.CharField(max_length=20,default= " ")
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'password1', 'password2']
objects = MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
My view.py
def regUser(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
print(form)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
return redirect("/youdiditwrong")
My HTML code
<HTML>
<head>
<title>Create a User</title>
</head>
<body>
<h1>User: </h1>
<form action="" method="POST">
{% csrf_token %}
First Name: <input type="text" name="fname"/><br/>
Last Name: <input type="text" name="lname"/><br/>
Username: <input type="text" name ="username"/><br/>
Email:<input type="text" name="email"/><br/>
Password:<input type="text" name="password1"/><br/>
Confirm Password:<input type="text" name="password2"/><br/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
I think your code should look something like this, you have to add the jinja2 in the html, so that you can use the form you created
<HTML>
<head>
<title>Create a User</title>
</head>
<body>
<h1>User: </h1>
<form action="" method="POST">
{% csrf_token %}
<!-- This is the first option
{{ form.first_name }}
{{ form.last_name }}
{{ form.username }}
{{ form.email }}
{{ form.password }}
{{ form.password2 }}
-->
<!-- This is second option
{{ form.as_ul }}
-->
<input type="submit" value="Post"/>
</form>
</body>
</html>
views.py
def regUser(request):
if request.method == "POST":
form = CustomUserCreationForm(request.POST)
print(form)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("/")
else:
return redirect("/youdiditwrong")
else: # if the method is not POST
return render(request, "page with the html",
{"form": CustomUserCreationForm()}

Django custom login form show extra field

I've created Django custom login form, but it shows email field for 2 times and it fails to auth. here are my files :
urls.py
path('login/', views.login, name='login'),
models.py where is the modeluser table is created :
class UserModelManager(BaseUserManager):
def create_user(self, email, password, pseudo):
user = self.model()
user.name = name
user.email = self.normalize_email(email=email)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password):
'''
Used for: python manage.py createsuperuser
'''
user = self.model()
user.name = 'admin-yeah'
user.email = self.normalize_email(email=email)
user.set_password(password)
user.is_staff = True
user.is_superuser = True
user.save()
return user
class UserModel(AbstractBaseUser, PermissionsMixin):
## Personnal fields.
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=16)
## [...]
## Django manage fields.
date_joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['email', 'name']
objects = UserModelManager()
def __str__(self):
return self.email
def get_short_name(self):
return self.name[:2].upper()
def get_full_name(self):
return self.name
forms.py
class SignUpForm(UserCreationForm):
email = forms.EmailField(required=True, help_text='البريد الإلكترونى الخاص بك - يجب ان يكون حقيقى (يستخدم لتسجيل الدخول) ')
name = forms.CharField(required=True, help_text='إسمك الحقيقى - سيظهر كأسم البائع')
password1 = forms.CharField(widget=forms.PasswordInput,
help_text='كلمة المرور - حاول ان تكون سهلة التذكر بالنسبة لك')
password2 = forms.CharField(widget=forms.PasswordInput,
help_text='تأكيد كلمة المرور - إكتب نفس كلمة المرور السابقة مرة أخرى')
class Meta:
model = UserModel
fields = ('email','name', 'password1', 'password2', )
labels = {
'name': 'إسمك الحقيقى - سيظهر كأسم البائع',
'email': 'البربد الإلكترونى Email',
'password1': 'كلمة المرور',
'password2': 'تأكيد كلمة المرور'
}
def clean_email(self):
data = self.cleaned_data['email']
return data.lower()
class LoginForm(AuthenticationForm):
email = forms.EmailField(required=True)
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = UserModel
fields = ('email', 'password')
def clean_email(self):
data = self.cleaned_data['email']
return data.lower()
And fialy here are the views.py and the html tempalte that shows the form for users :
first .. Views.py
def login(request):
if request.method == 'POST':
login_form = LoginForm(request.POST)
if login_form.is_valid():
login_form.save()
username = login_form.cleaned_data.get('username')
raw_password = login_form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
return redirect('home')
else:
login_form = LoginForm()
context = {
'login_form': login_form,
}
return render(request, 'fostania_web_app/login.html', context)
Then there is the HTML file :
<form method="post" align="right">
{% csrf_token %}
{{ login_form }}
<button type="submit" class="btn btn-success" style="background: linear-gradient(to right, #ff00a4 , #871f78);border-color: #871f78;">تسجيــل</button><br>
</form>
and that how it looks like in the final UserInterface:
So the whole problem is with that extra email field
Since your SignUpForm class inherit from UserCreationForm you should only provide the additional fields not the once already defined in the UserCreationForm.
So in your case you have to remove the email from the fields array in the meta class (in your SignUpForm class) like so:
class Meta:
model = UserModel
fields = ('name', 'password1', 'password2', )
Then you should only have 1 email field in the form.

Properly configuring user registration using 2 forms

I am trying to submit 2 forms at a time to create my student user in Django. I have been struggling for a while now, but I think I'm finally closing to an end on how to manage 2 forms at a time for my users to register. But when I fill in the data and then click register, I get error: "This field is required." under my student ID field. What am I doing wrong ? Thanks.
class UserForm(forms.ModelForm):
password = forms.CharField(
label='Password',
max_length=32,
required=True,
widget=forms.PasswordInput,
)
password2 = forms.CharField(
label='Confirm',
max_length=32,
required=True,
widget=forms.PasswordInput,
help_text="Make sure they match!",
)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'password', 'password2')
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ('phone', 'student_ID', 'photo')
class User(AbstractUser):
pass
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
student_ID = models.CharField(unique=True, max_length=14,
validators=[RegexValidator(regex='^.{14}$',
message='The ID needs to be 14 characters long.')])
photo = models.ImageField(upload_to='students_images')
phone = models.CharField(max_length=15, )
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_user_student(sender, instance, created, **kwargs):
if created:
Student.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_student(sender, instance, **kwargs):
instance.profile.save()
#csrf_protect
def student_register(request):
if request.method == 'POST':
form1 = UserForm(request.POST, prefix="user")
form2 = StudentForm(request.POST, prefix="profile")
if form1.is_valid() and form2.is_valid():
# create initial entry for user
username = form1.cleaned_data["username"]
password = form1.cleaned_data["password"]
new_user = User.objects.create_user(username, password)
new_user.save()
# create entry for UserProfile (extension of new_user object)
profile = form2.save(commit=False)
profile.user = new_user
profile.save()
return HttpResponseRedirect("index")
else:
form1 = UserForm(prefix="user")
form2 = StudentForm(prefix="profile")
c = {
'form1': form1,
'form2': form2,
}
return render(request, "student_signup_form.html", c)
<form method="post">
{% csrf_token %}
<p style="color:red"> {{ form.username.errors }}</p>
{{ form1.as_p }}
{{ form2.as_p }}
<input type="submit" value="Create the account">
</form>
First, you don't need #csrf_protect if you use {% csrf_token %} in template.
Second, you are probably getting student_ID required because you are trying to create a profile in signal providing just the user.
You can change your models like this:
models.py
class User(AbstractUser):
pass
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
student_ID = models.CharField(unique=True, max_length=14,
validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None)
photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None)
phone = models.CharField(max_length=15, null=True, blank=True, default=None)
def __str__(self):
return self.user.username
views.py
def student_register(request):
data = dict()
if request.method == 'POST':
form1 = UserForm(request.POST)
form2 = StudentForm(request.POST, request.FILES)
if form1.is_valid() and form2.is_valid():
cd1 = form1.cleaned_data
username = cd1["username"]
password = cd1["password"]
new_user = User.objects.create_user(username, password)
new_user.save()
cd2 = form2.cleaned_data
phone = cd2['phone']
student_ID = cd2['student_ID']
photo = cd2['photo']
Student.objects.create(user=new_user, phone=phone, student_ID=student_ID, photo=photo)
return redirect('index')
else:
form1 = UserForm()
form2 = StudentForm()
data['form1'] = form1
data['form2] = form2
return render(request, "student_signup_form.html", data)
template
<form action='' method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p style="color:red"> {{ form.username.errors }}</p>
{{ form1.as_p }}
{{ form2.as_p }}
<input type="submit" value="Create the account">
</form>
You can make StudentForm class a derived class of UserForm by declaring like class StudentForm(UserForm): and just submit one form that is StudentForm
It can be done like this also,
#models.py
from django.contrib.auth.models import User
class Student(models.Model):
user = models.OneToOneField(User)
student_ID = models.CharField(unique=True, max_length=14,validators=[RegexValidator(regex='^.{14}$',message='The ID needs to be 14 characters long.')])
photo = models.ImageField(upload_to='students_images')
phone = models.CharField(max_length=15, )
User.student = property(lambda u: Student.objects.get_or_create(user=u)[0])
#forms.py
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ('student_ID', 'photo', 'phone', )
#views.py
def student_register(request):
template_name = "student_signup_form.html"
context = {}
if request.method == 'POST':)
form = StudentForm(request.POST, instance=request.user.student)
if form.is_valid():
object = request.user.student
object.student_ID= form.cleaned_data['student_ID']
object.photo = form.cleaned_data['photo']
object.phone = form.cleaned_data['phone']
object.save()
return HttpResponseRedirect('index')
else:
form = StudentForm()
context['form'] = form
return render(request, template_name, context)

Categories