I am trying to expand my user model and now I have added two more fields public_address and nonce.
Problem-
Now I do not require to store username and email and want to keep these fields empty while storing public_address and nonce only.
The error I am getting is-
UNIQUE constraint failed: user_user.username
my User model-
class User(AbstractUser):
username = models.CharField(unique=True, max_length=50)
email = models.EmailField(unique=True, null=False, blank=False)
otp = models.CharField(max_length=9, blank=True, null=True)
count = models.IntegerField(default=0, help_text='Number of opt_sent')
public_address = models.CharField(null=True, max_length=500)
nonce = models.CharField(null=False, max_length=500)
validated = models.BooleanField(default=False,
help_text='if it is true, that means user have validate opt correctly in seconds')
token_string = models.CharField(max_length=32, blank=True, null=True)
USERNAME_FIELD = 'username'
def __str__(self):
return self.email
is there any way to ignore this error ?
thanks :)
Related
I am unable to save a model in Django with a ManyToManyField while inside Django Admin because I don't know how to create the ID in the database first, and then save the data. It's trying to do both at the same time, but I have to separate the two processes, and I don't know how.
I've gone five full pages deep on Google, and there are tons of answers, but nothing that I can relate to my specific use case.
The error message I get when submitting the form that has the ManyToManyField in it:
ValueError: "<Clients: Lowe, Robb>" needs to have a value for field "id" before this many-to-many relationship can be used.
Here's the model I'm using:
class BusinessInfo(models.Model):
id = models.IntegerField(primary_key=True, editable=False)
business_name = models.CharField(blank=True, null=True, max_length=50)
business_address = models.CharField(blank=True, null=True, max_length=50)
business_city = models.CharField(blank=True, null=True, max_length=50)
business_state = models.CharField(choices=STATE_SELECT, null=True, blank=True, max_length=50)
related_person = models.ManyToManyField('Clients', related_name='related_person', null=True, blank=True)
business_zip = models.IntegerField(blank=True, null=True)
business_contact_name = models.CharField(blank=True, null=True, max_length=50)
business_phone = PhoneField(null=True, help_text='Phone Number | <span style="color: red;">Required</span>')
business_email = models.CharField(blank=True, null=True, max_length=50)
And specifically the field I created:
related_person = models.ManyToManyField('Clients', related_name='related_person', null=True, blank=True)
I've also attempted to use django-modelcluster to no avail.
I'm pretty new to Django so if anyone can help me out and use explicit code that would help me a great deal. Thank you!
I have 2 model classes in Django:
class Notification(models.Model):
receiver = models.ForeignKey(User, null=True, blank=True)
content = models.CharField(max_length=500)
object_id = models.IntegerField(blank=True, null=True)
type = models.TextField(max_length=200, blank=True, null=True)
Class Notification stores notification about users activity. Field "content" is like: "welcome you registered Business Course successfully", or "5ASC is your voucher code". Field type stores types of object: course, promotion.
class PaymentTransaction(models.Model):
course = models.ForeignKey(Course)
student = models.ForeignKey(User)
PAYMENT_STATUS = ( SUCCESS, FAILURE, PROCESSING)
payment_status = models.CharField(max_length=50, choices=PAYMENT_STATUS, default=PROCESSING)
In notification pop up, when he clicks to paid Course then go to Course detail page and start learning, when he clicks to unpaid Course then go to Course register page, when he clicks to promotion code then go to promotion code page
How to have a QuerySet return all fields of Notification and PaymentTransaction tables, and condition is Notification.receiver_id = PaymentTransaction.student_id .
For each Course notification, i want to get Course payment status.I did:
user = request.user
p_list = PaymentTransaction.objects.filter(student=user)
n_list = Notification.objects.filter(receiver=user).intersection(p_list)
But it did't work
I can't understand why you create the Models like this but:
I think it should be:
class Book:
title = models.CharField(max_length=500)
price = models.FloatField()
class User:
name= models.CharField(max_length=500)
something = models.CharField()
class Book_User:
user = models.ForeignKey(User)
book = models.ForeignKey(User)
detail = models.CharField()
And i what is noti for?Just show up the list?
~> it should be the list of Book_User in page of user
~> Problem solve
Here are the models:
class Teacher(models.Model):
login = models.CharField(max_length=10, primary_key=True)
fname = models.CharField(max_length=30)
mname = models.CharField(max_length=30)
lname = models.CharField(max_length=30)
class Course(models.Model):
semester = models.ForeignKey(Semester, on_delete=models.CASCADE)
title = models.CharField(max_length=40)
teachers = models.ManyToManyField(Teacher.login, through='TeacherCourse')
credits = models.IntegerField()
numberEnrolled = models.IntegerField()
nomenclature = models.CharField(max_length=128)
lectures = models.IntegerField()
class TeacherCourse(models.Model):
teacher = models.ForeignKey(Teacher.login, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
allotedLectures = models.IntegerField()
Just added these to fresh project and tried to runserver. I'm getting the following:
AttributeError: type object 'Teacher' has no attribute 'login'
I'm missing something obvious?
I later found your bug from Uday Bhatye's answer:
teacher = models.ForeignKey(Teacher.login, on_delete=models.CASCADE)
is a syntax error in django.
You should do:
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
And to reference the login status of teachers assigned to a particular TeacherCourse:
teachercourse = TeacherCourse.objects.filter(id=teachercourse_id).select_related('teacher')
login_status = course.teacher.login
Hits the database once with select_related and fetches the login status of all teachers assigned to the TeacherCourse.
As the login field in teacher model is already declared as primary key, I need not reference it in the other two models as Teacher.login. Only referencing as Teacher suffices.
i am trying to make a simple profile edit form for users on a website. I've followed the standard advice for updating, in the docs it says that Django detects the instances primary key and knows to update instead of insert.
only problem is, i get an insert when i am trying to update. I pre populate a form with a model instance (the instance that im trying to edit) but when i try and save it, i get a new instance. When i add the 'force_update=True' line, i get an error message that tells me that no primary key is detected. Not sure why, because im pre populating the form with a model instance, although, obviously the pk is not a part of the form. is there something im missing?
some code:
the model:
class profile(models.Model):
user = models.ForeignKey(User)
first_name = models.CharField(max_length=20, null=True)
last_name = models.CharField(max_length=20, null=True)
DOB = models.DateField(null=True)
age = models.IntegerField(null=True)
public_email = models.EmailField(null=True)
county = models.CharField(max_length=20, null=True)
town = models.CharField(max_length=30, null=True)
the form:
class profileForm(forms.ModelForm):
class Meta:
model = profile
exclude = ['user']
the view:
#login_required()
def edit_profile(request):
if request.POST:
proform = profileForm(request.POST)
if proform.is_valid():
prof = proform.save(False)
prof.user = request.user
prof.save(force_update=True)
return HttpResponseRedirect('/accounts/view_profile/')
else:
c = {}
if profile.objects.filter(user=request.user).exists():
prof = profile.objects.get(user=request.user)
c['proform'] = profileForm(instance=prof)
else:
c['proform'] = profileForm()
return render(request, 'edit_profile.html', c)
any help greatly appreciated!
i got it, turns out i was trying to just calling save() on the form without specifying the particular instance that the form relates to.
code:
#login_required()
def edit_profile(request):
c = {}
if profile.objects.filter(user=request.user).exists():
profModel = profile.objects.get(user=request.user)
c['proform'] = profileForm(instance=profModel)
else:
c['proform'] = profileForm()
if request.POST:
# this line here, added 'instance=profModel' to specify
# the actual instance i want to save
proform = profileForm(request.POST, instance=profModel)
if proform.is_valid():
prof = proform.save(False)
prof.user = request.user
prof.save()
return HttpResponseRedirect('/accounts/view_profile/')
else:
return render(request, 'edit_profile.html', c)
works!
In my htmlpage I am having 100 fields
I am having a field for upload file which is optional for users.
When i submit the form with the file chosen and few other fields left blank,
it got saved into db.
At the same time when i try to submit the form without choosing the
file to be uploaded,it is raising error as ""Key 'up_file' not found
in ""
--models.py--
class js_details(models.Model):
user = models.ForeignKey(User, unique=True)
fname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
dob = models.CharField(max_length=20, null=True)
sec_email = models.EmailField(max_length=50, null=True)
address1 = models.CharField(max_length=50, null=True)
address2 = models.CharField(max_length=50, null=True)
up_file = models.FileField(upload_to='documents', null=True)
--views.py--
def newpost(request):
if request.method == "POST":
user_id = request.POST.get('user_id')
fname= request.POST.get('fname')
lastname= request.POST.get('lastname')
dob = request.POST.get('dob')
sec_email = request.POST.get('sec_email')
address1 = request.POST.get('address1')
address2 = request.POST.get('address2')
up_file = request.FILES['up_file']
p = js_details(user_id=user_id,fname=fname,lastname=lastname,dob=dob,sec_email=sec_email,address1=address1,address2=address2,up-file=up_file)
p.save()
How to save the form without the file field filled.?
All ur answers are welcomed.
Thanks in advance.
To strictly answer your question : you are using a subscript access on request.FILES (=> request.FILES['up_file']), which indeed raises aKeyErrorif there's no matchinh key. You should userequest.FILES.get('up_file')and check the returned value which will beNoneif the user didn't post a file. Read the Python's doc aboutmappinganddict` for more on these data types.
Now there's another problems with your code. The first one is that you blindly accept any user input without validation, sanitization and data type conversion. Using a ModelForm would take care of this and simplify your code.
Also and as side note, you should really stick to Django / Python naming conventions and use CapCase for your class names.
Here's a fixed version of you're code:
# models.py
class JsDetails(models.Model):
# ForeignKey -> OneToOneField,
# cf https://docs.djangoproject.com/en/1.4/ref/models/fields/#onetoonefield
user = models.OneToOneField(User, unique=True)
fname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
# I assume "dob" means "date of birth"
# so CharField -> DateField
dob = models.DateField(blank=True, null=True)
sec_email = models.EmailField(max_length=50, blank=True, null=True)
address1 = models.CharField(max_length=50, blank=True, null=True)
address2 = models.CharField(max_length=50, blank=True, null=True)
up_file = models.FileField(upload_to='documents', blank=True, null=True)
# forms.py
from .models import JsDetail
from django import forms
class JsDetailForm(forms.ModelForm):
class Meta:
models = JsDetail
# views.py
from .forms import JsDetailForm
from django.shortcuts import redirect, render
def newpost(request):
if request.method == "POST":
form = JsDetailForm(request.POST, request.FILES)
if form.is_valid():
newdetail = form.save()
redirect("/somewhere/to/show/the/result")
# if the form is not valid it will be redisplayed
# to the user with error messages
else:
form = JsDetailForm()
return render(
request,
"your/template.htm",
dict(form=form)
)
There are still problems with this code IMHO but that's still an improvement. I very strongly suggest you take some time doing the Python tutorial and the Django tutorial, it will save you a whole lot of pain and trouble.