Here I have changed the model and view name but I am unable to extend my user model why it gives the error like Registration() got an unexpected keyword argument 'myuser' please try to solve this error.
And this problem arises many time please give me the solution.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Registration(models.Model):
fname = models.CharField(max_length=30)
lname = models.CharField(max_length=30)
dob=models.DateField()
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
def __str__(self):
return self.fname
class Candidate(models.Model):
full_name = models.CharField(max_length=30)
position = models.CharField(max_length=30)
total_vote = models.IntegerField(default=0)
def __str__(self):
return "{} -- {}".format(self.full_name,self.position)
views.py
def register(request):
if request.method == "POST":
# Get the post parameters
username = request.POST['username']
email = request.POST['email']
fname = request.POST['fname']
lname = request.POST['lname']
dob = request.POST['dob']
pass1 = request.POST['pass1']
pass2 = request.POST['pass2']
# check for errorneous input
if User.objects.filter(username=username).exists():
messages.error(request, 'This Aadhaar is Already Used')
return redirect('home')
if User.objects.filter(email=email).exists():
messages.error(request, 'This Email is already Used')
return redirect('home')
if (pass1 != pass2):
messages.error(request, " Passwords do not match")
return redirect('home')
# Create the user
myuser = User.objects.create_user(username, email, pass1)
myuser.first_name = fname
myuser.last_name = lname
reg = Registration(dob=dob,myuser=myuser)
reg.save()
messages.success(request, "You are successfully registered")
return redirect('home')
else:
return HttpResponse("404 - Not found")
error:
TypeError at /register
Registration() got an unexpected keyword argument 'myuser'
Request Method: POST
Request URL: http://127.0.0.1:8000/register
Django Version: 3.1.7
Exception Type: TypeError
Exception Value:
Registration() got an unexpected keyword argument 'myuser'
Exception Location: C:\Python3.9\lib\site-packages\django\db\models\base.py, line 501, in __init__
Python Executable: C:\Python3.9\python.exe
Python Version: 3.9.2
Python Path:
['C:\\Users\\DeLL\\PycharmProjects\\E_VotigSystem\\ovs',
'C:\\Python3.9\\python39.zip',
'C:\\Python3.9\\DLLs',
'C:\\Python3.9\\lib',
'C:\\Python3.9',
'C:\\Python3.9\\lib\\site-packages']
Server time: Sun, 30 May 2021 12:30:11 +0000
Registration model has a user field, you give it a myuserargument.
reg = Registration(dob=dob, user=myuser)
should fix it. But then again, fname and lname are not nullable.
Also, please be more verbose about your fields.
dob? fname? lname?
date_of_birth, first_name, last_name
Also, please finish the official tutorial, it has most of these things covered.
You need to create a new Registration like Registration(dob=dob, user=myuser) because the field is named user in your Registration model - and you don’t need to call reg.save() the create step already persists the instance in your database - if you use Registration.objects.create(dob=dob, user=myuser)
Related
I am trying to generate a token for users requesting for forget password. I have a model to handle and store this.
models.py
class ForgetPassword(models.Model):
user = models.ForeignKey(CustomUser, on_delete= models.CASCADE)
forget_password_token = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add= True)
def __str__(self):
return self.user.email
The view functions that handles the request are below
views.py
def forget_password(request):
try:
if request.method == 'POST':
user_email = request.POST.get('email')
if CustomUser.objects.filter(email = user_email).exists():
user_obj = CustomUser.objects.get(email = user_email)
name = user_obj.full_name
plan = user_obj.plan
print("\n this is the user : ", user_obj, " this is its name : ", name,"\n")
token = str(uuid.uuid4())
fp = ForgetPassword.objects.get(user = user_obj)
fp.forget_password_token = token
fp.save()
forget_password_mail.delay(user_email, name, token)
messages.info(request, 'An email has been sent to your registered email.')
return redirect('forget-password')
else:
messages.info(request, 'User does not exist')
return redirect('forget-password')
except Exception as e:
print("\nthe exception is comming from forget_password : ", e, "\n")
return render(request, 'fp_email_form.html')
So, here I am trying to get the user first in user_obj from my CustomUser model and then I am trying to get the same user in the ForgetPassword model and store the token against that user. But I am getting the below exception
ForgetPassword matching query does not exist.
Please suggest or correcct me where I am wrong.
You do not have a ForgetPassword object associated with the user object you are trying to fetch at,
fp = ForgetPassword.objects.get(user = user_obj)
Instead, you should use get_or_create.
reference link
I am a newbie in Django. I have defined the models and a method
from django.db import models
from django.contrib.auth.models import User
class Practice(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=200)
phone = models.IntegerField()
def __str__(self):
return self.name
class Doctor(models.Model):
specialisation = models.CharField(max_length=50)
practice = models.ForeignKey(Practice, related_name='doctor',on_delete=models.DO_NOTHING)
name = models.ForeignKey(User, related_name ='doctor', on_delete=models.DO_NOTHING)
selected = models.BooleanField()
def __str__(self):
return self.specialisation
def get_list_doctors(self):
all_doctors = User.objects.exclude(pk=1).filter(doctor__isnull=False)
all_doctors_names = all_doctors.values_list('last_name', 'first_name')
return all_doctors_names
class Patient(models.Model):
name = models.ForeignKey(User, related_name='patient', on_delete=models.DO_NOTHING)
height = models.DecimalField(max_digits=6, decimal_places=2)
weight = models.DecimalField(max_digits=6, decimal_places=2)
practice = models.ForeignKey(Practice, related_name='patient',on_delete=models.DO_NOTHING)
primary_doctor = models.ForeignKey(Doctor, related_name='patient',on_delete=models.DO_NOTHING)
class Appointment(models.Model):
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doctor = models.ForeignKey(Doctor, related_name='appointment',on_delete=models.DO_NOTHING)
practice = models.ForeignKey(Practice, related_name='appointment',on_delete=models.DO_NOTHING)
patient = models.ForeignKey(Patient, related_name='appointment',on_delete=models.DO_NOTHING)
This is my view
def login_user(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)
messages.success(request, ('You Have Been Logged In!'))
doctor_list = get_list_doctors()
context = { 'doctor_name': doctor_list}
return render(request, 'homeunimed.html', context)
I am trying to use the method in the view. The reason for defining it in the model is so that I can reuse.
NameError at /
name 'get_list_doctors' is not defined
Request Method: POST
Request URL: http://localhost:8000/
Django Version: 2.1
Exception Type: NameError
Exception Value:
name 'get_list_doctors' is not defined
Exception Location: /Users/vinoojacob/Django/my_app/authenticate/views.py in login_user, line 27
Python Executable: /Users/vinoojacob/Django/bin/python
Python Version: 3.6.5
Python Path:
['/Users/vinoojacob/Django/my_app',
'/Users/vinoojacob/Django/lib/python36.zip',
'/Users/vinoojacob/Django/lib/python3.6',
'/Users/vinoojacob/Django/lib/python3.6/lib-dynload',
'/Users/Shared/anaconda3/lib/python3.6',
'/Users/vinoojacob/Django/lib/python3.6/site-packages']
However, I get this error. Any pointers to what is wrong. I thought you could access any methods defined in the model as long as the model is imported. Thanks for your help.
As you wrote you can access it via model. So decorate your method with #staticmethod, leave out self as argument and call it this way doctor_list = Doctor.get_list_doctors().
#staticmethod
def get_list_doctors():
all_doctors = User.objects.exclude(pk=1).filter(doctor__isnull=False)
all_doctors_names = all_doctors.values_list('last_name', 'first_name')
return all_doctors_names
The function get_list_doctors(self) is pretty useless and exclude a user hardcoding its pk. This is pretty bad.
A couple of suggestions:
1) Change the line in Doctor
name = models.ForeignKey(User, related_name ='doctor', on_delete=models.DO_NOTHING)
With:
user = models. OneToOneField(User, related_name ='doctor', on_delete=models.CASCADE)
The relation is a user and if the user is gone, then you must remove the Doctor too. And also, the relation is one to one!
2) You can get the list of the doctor very easily in your view
def login_user(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)
messages.success(request, ('You Have Been Logged In!'))
doctors_list = Doctor.objects.exclude(user=user)
context = { 'doctors_list': doctors_list}
return render(request, 'homeunimed.html', context)
In your template, you can access the name of the doctors through the user (this is a very naive example)
{% for doctor in doctors_list %}
First name: {{ doctor.user.first_name }}
Last name: {{ doctor.user.last_name }}
{% endfor %}
I encounter error NOT NULL constraint failed: when intend to create a User account:
The model data code:
class ActivateCode(models.Model):
""" """
user = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.CharField(max_length=100)
date_expired = models.DateTimeField(default=tomorrow)
def __str__(self):
return self.code
the register in views.py
def register(request):
if request.method == "GET":
form = UserForm()
if request.method == "POST":
form = UserForm(request.POST)
print(vars(form))
if form.is_valid():
user = User.objects.create_user(
form.cleaned_data['username'],
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password'])
user.is_active = False
user.save()
#create activate code
uuid_code = str(uuid.uuid4()).replace("-", '')
activate_code = ActivateCode(code=uuid_code)
activate_code.save()
return HttpResponse(f"You have registered successfully with activate_code: {uuid_code}. \n"
"Please activate your account from your registered email.")
The error it throwed
IntegrityError at /user/register
NOT NULL constraint failed: user_activatecode.user_id
Request Method: POST
Request URL: http://127.0.0.1:8001/user/register
Django Version: 1.11.13
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: user_activatecode.user_id
How to solve such a problem?
Seems you are trying to insert null value in a field that don't accept it, in you ActivateCode Model its seems you have a foreign key related to the user, maybe you have to post it also. Try to pass the user to the ActivateCode call:
ActivateCode(code=code, user=user)
I'm trying to implement a user registration page in Django. Seems like a simple task, but I'm getting an error I just don't understand. Here's my view:
def registration_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username = form.cleaned_data['username'],
password = form.cleaned_data['password1'],
email = form.cleaned_data['email1']
)
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form
})
return render_to_response('registration/registration_page.html', variables)
And here's my registration form:
class RegistrationForm(forms.Form):
username = forms.CharField(label = u'Username', max_length = 30, error_messages={'required': 'A username is required.'})
email1 = forms.EmailField(label = u'Email Address', error_messages={'required': 'An email address is required.'})
email2 = forms.EmailField(label = u'Email Address confirmation', error_messages={'required': 'A confirmed email address is required.'})
password1 = forms.CharField(label = u'Password', widget = forms.PasswordInput(), error_messages={'required': 'A password is required.'})
password2 = forms.CharField(label = u'Password confirmation', widget = forms.PasswordInput(), error_messages={'required': 'A confirmed password is required.'})
def clean_password2(self):
if 'password1' in self.cleaned_data:
password1 = self.cleaned_data['password1']
password2 = self.cleaned_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords must be identical. Remember, passwords are case-sensitive.')
def clean_email2(self):
if 'email1' in self.cleaned_data:
email1 = self.cleaned_data['email1']
email2 = self.cleaned_data['email2']
if email1 == email2:
if User.objects.get(email = email1):
raise forms.ValidationError("The email address '%s' is already associated with an account. This typically means you created an account in the past. Please use it." % email1)
else:
return email2
raise forms.ValidationError('Email addresses must be identical.')
def clean_username(self):
if 'username' in self.cleaned_data:
username = self.cleaned_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username can only contain letters, numbers, and the underscore characters.')
try:
User.objects.get(username = username)
except User.DoesNotExist:
return username
raise forms.ValidationError("Username '%s' is already taken." % username)
The problem pops up in the form.is_valid() and clean_username(). If I add a user that does or does not exist (it doesn't matter if the user exists or not, behavior is the same) and populate the form with data I know is valid, the code should simply return username from clean_username() and form.is_valid() should be True. Instead, I get an error page that looks like this:
DoesNotExist at /register/
User matching query does not exist.
Request Method: POST
Request URL: http://127.0.0.1:8000/register/
Django Version: 1.4.1
Exception Type: DoesNotExist
Exception Value:
User matching query does not exist.
Exception Location: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py in get, line 366
Python Executable: /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.2
Python Path:
['/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg',
'/Library/Python/2.7/site-packages/bpython-0.10.1-py2.7.egg',
'/Library/Python/2.7/site-packages/Pygments-1.5-py2.7.egg',
'/Library/Python/2.7/site-packages/django_registration-0.8-py2.7.egg',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/PIL',
'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
'/Library/Python/2.7/site-packages']
Server time: Sun, 28 Oct 2012 00:51:58 -0400
It's got to be something small I'm missing, but I can't see it.
In your code
def clean_email2(self):
...
# here
if User.objects.get(email = email1):
raise forms.ValidationError("The email address '%s' is already associated with an account. This typically means you created an account in the past. Please use it." % email1)
...
The get() could cause DoesNotExist but is not captured. Is that the issue?
Also, please provide full traceback of the line making the issue.
Furthermore, according to the doc, its better to put the logic of validating passwords & emails to the clean() method.
My Models.py, Here I'm using OneToOneField here, to extend StudentProfile.
from django.db import models
from django.contrib.auth.models import User, UserManager
class SecretQuestion(models.Model):
question = models.CharField(max_length=200)
def __unicode__(self):
return self.question
class StudentProfile(models.Model):
user = models.OneToOneField(User)
batch = models.CharField(max_length=10)
course = models.CharField(max_length=20)
date_of_birth = models.DateField()
secret_question = models.ForeignKey(SecretQuestion)
answer = models.CharField(max_length=20)
contact = models.CharField(max_length=20)
And my registration view, I'm creating new user main_user and I'm using it to create Student Profile :-
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
main_user = User.objects.create_user(
username= form.cleaned_data['username'],
password = form.cleaned_data['password1'],
)
user = StudentProfile.objects.create(
user_id = main_user.id,http://stackoverflow.com/questions/ask
batch=form.cleaned_data['batch'],
course=form.cleaned_data['course'],
date_of_birth=form.cleaned_data['date_of_birth'],
secret_question=form.cleaned_data['secret_question'],
answer=form.cleaned_data['answer'],
contact=form.cleaned_data['contact']
)
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {'form': form})
return render_to_response('registration/register.html',variables)
After registering in Django, I'm getting,
FieldError at /register/
Cannot resolve keyword 'username' into field. Choices are: answer, batch, contact, course, date_of_birth, id, secret_question, user
This is happening after filling registration fields and pressing register button.
I'm not able to interpret this error. What does this mean?
You need to subclass RegistrationForm as described in Adding extra fields to django-registration form
User.objects.create_user has no keyword argument named username. The username must be the first positional argument:
main_user = User.objects.create_user(form.cleaned_data['username'],
password = form.cleaned_data['password1'],
)
In the future, please include at least the line number where the error occurred.
The current code shouldn't cause this error.
The error suggests you are filtering by a username keyword argument to your StudentProfile class, which does not have a username field according to your model.
The error should list which line your code is breaking on and tell you exactly where this is happening - that's where the answer lies. Your code? Django registration code? I don't know until you post it.
FYI, this error appears if you try to filter a model by an invalid field.
MyModel.objects.filter(non_existent_field=True) # would throw this error.
Passing an invalid field into create would cause a TypeError