I'm using Django. In my function accept_request(), I'm trying to select the profile of a user with a certain PrimaryKey. Here's the function:
def accept_request(request, pk):
book = Book.objects.get(id=pk)
print(book.owner.pk)
user = request.user
user_email = request.user.email
owner_profile = UserProfileInfo.objects.get(user=book.owner)
owner_house_number = owner_profile.house_number
owner_phone_number = owner_profile.phone_number
owner_full_name = owner_profile.full_name
r = UserRents.objects.get(book_id=pk)
r.status = 1
r.save()
subject = "{}, your request to rent the book, \"{}\", has been accepted.".format(user, book)
body = "You had requested to rent the book, \"{}\". It's been accepted! You can head over to #{} to get the book. You can contact the owner, {}, at +91 {}. Please return the book in the same condition as it was when you got it.\n Hope you enjoy reading the book!".format(book, owner_house_number, owner_full_name, owner_phone_number)
sender_email = "pfcbookclub#gmail.com"
receiver_email = user_email
password = "Zt2.~[3d*.[Y5&5r"
# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email # Recommended for mass emails
# Add body to email
message.attach(MIMEText(body, "plain"))
text = message.as_string()
# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
return redirect("/")
This is the UserProfileInfo model in models.py:
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
full_name = models.CharField(max_length=1000, blank=True)
house_number = models.CharField(max_length=5, blank=True)
email = EmailField(max_length=1000, blank=True)
creation_date = models.DateTimeField(default=timezone.now)
phone_number = models.CharField(max_length=20, blank=True, null=True)
def __str__(self):
return self.user.username
And here's the Book model in models.py:
class Book(models.Model):
title = models.CharField(max_length=1000, blank=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
description = models.TextField()
author = models.CharField(max_length=1000, blank=True, null=True)
thumbnail = models.ImageField(upload_to='book_thumbnails', blank=True)
creation_date = models.DateTimeField(default=timezone.now)
status = IntegerField(default=1)
min_age = models.IntegerField(blank=True, null=True)
max_age = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.title
When I go to the URL I've fixed for this function, it gives an error:
DoesNotExist at /main/accept_rent_request/1/
UserProfileInfo matching query does not exist.
The error's at the line where I try to access the UserProfileInfo of the owner of the book:
owner_profile = UserProfileInfo.objects.get(user=book.owner)
Django is not able to access the profile of the owner. What can I do to fix the issue?
First, you can access the user's profile info by doing
owner_profile = book.owner.userprofileinfo
Also, the error stems from your UserProfileInfo not existing. If you want to explictly query it, you can first check if it exists, then assigning it to owner_profile
user_profile_info_query = UserProfileInfo.objects.filter(user=book.owner)
if user_profile_info_query.exists():
owner_profile = user_profile_info_query.first()
You can maybe create a new UserProfileInfo in the shell and assign the user to it so you can test.
Related
Here is the error screenshot
My code is
def contacts(request):
if request.method == "POST":
name = request.POST.get('name')
email = request.POST.get('email')
phone = request.POST.get('phone')
desc = request.POST.get('desc')
contact = Contact(name=name, email=email, phone=phone, desc=desc, date=datetime.today())
contact.save()
return render(request, 'contacts.html')
and my model code is
from django.db import models
Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=122)
email = models.CharField(max_length=122)
phone = models.CharField(max_length=12)
desc = models.TextField()
date = models.DateField(auto_now_add=True)
Error tell you exactly what's going on.
name field in Contact can't be empty (null/None). If you want some fields to be not required in form then you can add null=True, blank=True
class Contact(models.Model):
name = models.CharField(max_length=122, null=True, blank=True)
email = models.CharField(max_length=122)
phone = models.CharField(max_length=12)
desc = models.TextField()
date = models.DateField(auto_now_add=True)
I wrote a fullstack django ticketing system for a company. Everything works, login, register, posting a ticket, database, send mail to admin. Only thing that is left is to check the status field of the ticket and if its true send an email to the user who posted it.
class tickets(models.Model):
name = models.ForeignKey(devices, on_delete=models.CASCADE, blank=True, null=True)
location = models.CharField(max_length=200)
company = models.CharField(max_length=200)
serial_number = models.CharField(max_length=200)
problem = models.CharField(max_length=1000)
contact_number = models.CharField(max_length=200)
status = models.BooleanField(default=False)
author = models.ForeignKey(User, on_delete=models.CASCADE, r elated_name="authorname", null=True)
executive = models.ForeignKey(executives, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.problem
you can do like this
from django.core.mail import send_mail
class tickets(models.Model):
email_as_send = models.BooleanField(default=False)
...
def save(self):
if self.status and self.email_as_send:
send_mail("subject", "message","your_website#email.fr", [self.author.email])
self.email_as_send = True
super().save()
I have impletmented the detailview with views.py this afternoon.
I have a model with the pk set as a UUID.
the URLs line concerned is:
path('user/detail/<uuid:pk>', UserDetailView.as_view(), name='userdetail'),
the template referring to it is:
<a href="{% url 'userdetail' user.pk %}">
which is generating the following URL:
http://127.0.0.1:8000/accounts/user/detail/809b0ec2-d604-4171-8966-0817bfd59c88
however I get:
Reverse for 'userdetail' with arguments '('',)' not found. 1 pattern(s) tried: ['accounts/user/detail/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$'].
If I use the username e.g. email from AbstractBase User, the detail view doesn't like it as it wants Pk or slug.
Help would be greatly appreciated.
EDIT: I am including the model below;
class UserDetails(AbstractBaseUser, PermissionsMixin):
FormFieldUserID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
FormFieldTitle = models.CharField(max_length=75, help_text='Enter title',
verbose_name="Enter")
FormFieldFirstName = models.CharField(max_length=75, help_text='Enter First Name',
verbose_name="First Name") # Users First Name
FormFieldMiddleName = models.CharField(max_length=75, help_text='Enter Middle Name', blank=True,
verbose_name="Middle Names") # Users middle name
FormFieldLastName = models.CharField(max_length=75, help_text='Enter Last Name',
verbose_name="Last Name") # users last name
email = models.EmailField(max_length=254, unique=True, help_text="Enter Username/email",
verbose_name="Email Address") # user email
FormFieldUserImg = ResizedImageField(size=[40,40], crop=['middle', 'center'], upload_to='project/images/',
help_text="Choose project image", blank=True)
FormFieldAddr1 = models.CharField(max_length=100, help_text='Enter Address',
verbose_name="Address 1") # Users Address
FormFieldAddr2 = models.CharField(max_length=100, help_text='Enter Address', blank=True,
verbose_name="Address 2") # Users Address
FormFieldAddr3 = models.CharField(max_length=100, help_text='Enter Address', blank=True,
verbose_name="Address 3") # Users Address
FormFieldAddr4 = models.CharField(max_length=100, help_text='Enter Address', blank=True,
verbose_name="Address 4") # Users Address
FormFieldCounty = models.CharField(max_length=200, help_text='Enter County',
verbose_name="County") # Users county
FormFieldCountry = CountryField(help_text='Select user country', verbose_name="Country") # Users country
FormFieldAddrCode = models.CharField(max_length=20, help_text='Enter zip/post code',
verbose_name="Post Code") # Users Post Code
FormFieldMobileNo = models.CharField(max_length=25, help_text="Enter Mobile Phone Number",
verbose_name="Mobile Number") # User mobile Number
FormFieldPhoneNo = models.CharField(max_length=25, help_text="Enter Phone Number",
verbose_name="Phone Number",blank=True) # User phone Number
FormFieldWebAddr = models.CharField(max_length=254, help_text='Enter website details',
verbose_name="Website Details",blank=True) # User Website details
FormFieldUserNotes = models.CharField(max_length=254, help_text='Enter any user notes',
verbose_name="User Notes",blank=True) # User notes
FormFieldDateAdded = models.DateTimeField(default=datetime.now, help_text='Date user added',
verbose_name="User added date")
FormFieldAddedBy = models.CharField(default=settings.AUTH_USER_MODEL, max_length=200,
help_text='Select update detail', verbose_name="Used added by")
# Fields required by Abstract Model for users auth
is_active = models.BooleanField(default=True, help_text='Is User Active',
verbose_name="User Active") # Default must be true )
is_admin = models.BooleanField(default=False, help_text='Is user an administrator',
verbose_name="Admin User") # Default must be false)
USERNAME_FIELD = 'email'
objects = CustomUserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"""Does the user have a specific permission?"""
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"""Does the user have permissions to view the app `app_label`?"""
# Simplest possible answer: Yes, always
return True
#property
def is_staff(self):
"""Is the user a member of staff?"""
# Simplest possible answer: All admins are staff
return self.is_admin
class Meta:
verbose_name = 'User Detail'
verbose_name_plural = 'User Details'
put this because your path it's nedd to pk (int or str ...)
<a href="{% url 'userdetail' pk=user.pk %}">
if don't work put this :
path('user/detail/<str:pk>', UserDetailView.as_view(), name='userdetail'),
I cannot insert data into a database.
I want to create a user with specific department name and the department table, with a foreign key to detect the user from a certain department.
Here is my model file:
class Department(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
admin_id = models.ForeignKey('Admin' , on_delete=models.CASCADE)
admin_post_id = models.ForeignKey('Admin_Post' , on_delete=models.CASCADE)
def __str__(self):
return name
This is my custom user model:
class User(AbstractBaseUser):
first_name = models.CharField(max_length=50, blank=False, null=False)
last_name = models.CharField(max_length=50, blank=False, null=False)
address = models.CharField(max_length=150)
phone_number = models.IntegerField( blank=False, null=False, unique=True)
department = models.ForeignKey('Department' , on_delete=models.CASCADE)
semester = models.FloatField(blank=False, null=False)
registation = models.IntegerField(blank=False, null=False, unique=True)
email = models.EmailField(max_length=150, blank=False, null=False, unique=True)
password = models.CharField(max_length=150, blank=False)
password_con = models.CharField(max_length=150, blank=False, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELD = ['email']
objects = UserManager()
def _str__(self):
return registration;
Here is my view file:
def register(request):
if request.method == 'POST':
first_name = request.POST['first_name']
last_name = request.POST['last_name']
address = request.POST['address']
phone_number = request.POST['phone_number']
department = request.POST['department']
semester = request.POST['semester']
registration = request.POST['registration']
email = request.POST['email']
password = request.POST['password']
password_con = request.POST['password_con']
user = Department()
user = User.objects.create_user(first_name=first_name ,last_name=last_name ,address=address ,phone_number=phone_number ,department=department ,semester=semester ,registration=registration ,email=email ,password=password)
if User.objects.filter(email=email).exists():
messages.info(request,'Email is Already taken')
elif User.objects.filter(registration=registration):
messages.info(request,'Registration Id is Already taken')
elif password != password_con:
messages.info(request,'Credentials not mathcing')
else:
# user.department = Department.objects.get()
user.save()
print('user created')
return redirect('signin/')
else:
return render(request,'register.html')
you are trying to make a database relation out from a name, you can't do that in Django.
You must first retrieve the Department instance that correponds to the POST data and the give it so that Django creates a foreign key relation.
Something like this
# retrieve object
department_instance = Department.objects.get(name=request.POST['department']) # here 'Civil Engineering (CE)'
# use the instance (actually only the ID of that instance will be stored in the table User, but that's a detail)
User.objects.create_user(department=department_instance.id, etc...) #you can omit '.id'
Your line
department = request.POST['department']
should be something like:
department = Department.objects.get(id=request.POST['department'])
I have a model:
class Artwork(models.Model):
title = models.CharField(max_length=50)
description = models.TextField(null=True, blank=True)
image_file = models.ImageField(upload_to='portfolios/image/%Y/%m', null=True, blank=True)
video_file = models.FileField(upload_to='portfolios/video/%Y/%m', null=True, blank=True)
video_url = models.URLField(blank=True, null=True)
When a user edits one of these objects, how can I verify the at least one of these three fields is provided with data: image_file, video_file, or video_url so that the verification message appears in the form by the field, similar to what happens automatically if you set blank=False and leave it blank?
You need to overwrite the form's clean method and assign an error message to a field. Here's an example where all three fields get an error message if they are all blank, adapted from the Django docs:
from django import forms
class ArtworkForm(forms.Form):
def clean(self):
cleaned_data = super(ArtWorkForm, self).clean()
image_file = cleaned_data.get("image_file")
video_file = cleaned_data.get("video_file")
video_url = cleaned_data.get("video_url")
if not (image_file or video_file or video_url):
msg = "your error message."
self.add_error('image_file', msg)
self.add_error('video_file', msg)
self.add_error('video_url', msg)