I am trying to get all the videos related to a curriculum, I've tried curriculum.videos.all but it return this error that says 'QuerySet' object has no attribute 'videos', i also tried using curriculum.videos_set.all then it shows the same error but this time with a 'QuerySet' object has no attribute 'videos_set'. what can be the issue with this problem?
models.py
class Course(models.Model):
course_title = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(unique=True)
course_thumbnail = models.ImageField(upload_to=user_directory_path, blank=True)
class Curriculum(models.Model):
course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="curriculum")
title = models.CharField(max_length = 100 , null = False)
slug = models.SlugField(unique=True)
def __str__(self):
return f'{self.course.course_title} - {self.title}'
class Video(models.Model):
title = models.CharField(max_length = 100 , null = False)
curriculum = models.ForeignKey(Curriculum , null = False , on_delete=models.CASCADE, related_name="videos")
serial_number = models.IntegerField(null=False)
video_id = models.CharField(max_length = 100 , null = False)
def __str__(self):
return self.title
Now this is the view that i have written for it
View.py
def course_details(request, course_slug):
if request.user.is_authenticated:
user = request.user
course = Course.objects.get(slug=course_slug)
course.views = course.views + 1
curriculum = Curriculum.objects.filter(course=course)
serial_number = request.GET.get('lecture')
# videos = curriculum.videos.all().order_by("serial_number")
# video_count = curriculum.videos.all().order_by("serial_number").count()
videos = Video.objects.filter(curriculum=curriculum).order_by("serial_number")
profile = Profile.objects.get(user=course.course_creator)
user_rating = CreatorRating.objects.filter(profile=profile).aggregate(Avg('rating'))['rating__avg']
profile = Profile.objects.get(user=user)
follow_status = Follow.objects.filter(following=course.course_creator, follower=request.user).exists()
followers_count = Follow.objects.filter(following=course.course_creator).count()
liked = CourseLikes.objects.filter(user=user, course=course).count()
post_tags_ids = course.tags.values_list('id', flat=True)
similar_posts = Course.objects.filter(tags__in=post_tags_ids).exclude(id=course.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-date_created')
rating_average = CourseRating.objects.filter(course=course).aggregate(Avg('rating'))['rating__avg']
reviews = CourseRating.objects.filter(active=True, course=course).order_by("-date")
reviews_count = CourseRating.objects.filter(active=True, course=course).count()
rating_count = CourseRating.objects.filter(course=course, rating__in=["3.0", "4.0", "5.0"]).count()
discussions = CourseDiscussion.objects.filter(active=True, course=course).order_by('-date')
enrolled_student_count = UserCourse.objects.filter(course=course).count()
user_courses = Course.objects.filter(course_creator=course.course_creator).count()
students_enrolled_for_a_creator = UserCourse.objects.filter(course__course_creator=course.course_creator).count()
all_star = CourseRating.objects.filter(course__course_creator=course.course_creator).count()
# lectures = Video.objects.filter(curriculum=curriculum).count()
recent_courses = Course.objects.filter(course_publish_status="published").order_by("?")[:3]
is_liked = False
if course.likes.filter(id=request.user.id).exists():
is_liked = True
is_saved = False
if profile.favourite_course.filter(slug=course_slug).exists():
is_saved = True
# Course Rating Feature
if request.method == "POST":
form = CourseRatingForm(request.POST)
if form.is_valid():
rating_form = form.save(commit=False)
rating_form.user = request.user
rating_form.course = course
rating_form.save()
messages.success(request, f'You review was sent successfully!')
return redirect("course:course-detail", course.slug)
else:
form = CourseRatingForm
# Course Discusion Feature
if request.method == "POST":
discform = CourseDiscussionForm(request.POST)
if discform.is_valid():
disc_form = discform.save(commit=False)
disc_form.user = request.user
disc_form.course = course
disc_form.save()
messages.success(request, f'Posted!')
return redirect("course:course-detail", course.slug)
else:
discform = CourseDiscussionForm
#For the color of the favorite button
if profile.favourite_course.filter(slug=course_slug).exists():
favorited = True
else:
favorited = False
if liked == True:
liked = True
else:
liked = False
if serial_number is None:
serial_number = 1
# if Video.objects.all().exists
# video, created = Video.objects.get_or_create(serial_number=serial_number, curriculum=curriculum)
video, created = Video.objects.get_or_create(serial_number=serial_number, curriculum=curriculum)
# video_count = Video.objects.get(serial_number=serial_number, course=course)
video.save()
if(video.is_preview is False):
if request.user.is_authenticated is False:
return redirect("course:sign-in")
else:
user = request.user
try:
user_course = UserCourse.objects.get(user=user, course=course)
except:
return redirect("course:check-out", slug=course.slug)
# if request.user.is_authenticated:
# student = request.user.student
# order, created = Order.objects.get_or_create(student=student, completed=False)
# items = order.orderitem_set.all()
# cartItems = order.get_cart_items
# else:
# items = []
course.save()
context = {
'enrolled_student_count':enrolled_student_count,
'user_courses':user_courses,
"reviews" : reviews,
# "lectures" : lectures,
"reviews_count" : reviews_count,
"rating_count" : rating_count,
"followers_count" : followers_count,
"follow_status" : follow_status,
"favorited" : favorited,
"all_star" : all_star,
"liked" : liked,
'recent_courses': recent_courses,
'is_liked': is_liked,
"video" : video,
"form" : form,
'discussions': discussions,
'discform': discform,
# "video_count" : video_count,
'videos':videos,
'course': course,
'students_enrolled_for_a_creator': students_enrolled_for_a_creator,
'is_saved':is_saved,
'rating_average':rating_average,
'user_rating':user_rating,
'similar_posts':similar_posts,
# 'cartItems': cartItems,
}
return render(request, 'course/course-detail.html', context)
else:
user = request.user
course = Course.objects.get(slug=course_slug)
course.views = course.views + 1
serial_number = request.GET.get('lecture')
videos = course.videos.all().order_by("serial_number")
video_count = course.videos.all().order_by("serial_number").count()
post_tags_ids = course.tags.values_list('id', flat=True)
similar_posts = Course.objects.filter(tags__in=post_tags_ids).exclude(id=course.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-date_created')
rating_average = CourseRating.objects.filter(course=course).aggregate(Avg('rating'))['rating__avg']
reviews = CourseRating.objects.filter(active=True, course=course).order_by("-date")
reviews_count = CourseRating.objects.filter(active=True, course=course).count()
rating_count = CourseRating.objects.filter(course=course, rating__in=["3.0", "4.0", "5.0"]).count()
discussions = CourseDiscussion.objects.filter(active=True, course=course).order_by('-date')
enrolled_student_count = UserCourse.objects.filter(course=course).count()
user_courses = Course.objects.filter(course_creator=course.course_creator).count()
students_enrolled_for_a_creator = UserCourse.objects.filter(course__course_creator=course.course_creator).count()
all_star = CourseRating.objects.filter(course__course_creator=course.course_creator).count()
lectures = Video.objects.filter(course=course).count()
recent_courses = Course.objects.filter(course_publish_status="published").order_by("?")[:3]
is_liked = False
if course.likes.filter(id=request.user.id).exists():
is_liked = True
is_saved = False
if serial_number is None:
serial_number = 1
# if Video.objects.all().exists
video, created = Video.objects.get_or_create(serial_number=serial_number, course=course)
video_count = Video.objects.get(serial_number=serial_number, course=course)
video.save()
if(video.is_preview is False):
if request.user.is_authenticated is False:
return redirect("course:sign-in")
else:
user = request.user
try:
user_course = UserCourse.objects.get(user=user, course=course)
except:
return redirect("course:check-out", slug=course.slug)
course.save()
context = {
'enrolled_student_count':enrolled_student_count,
'user_courses':user_courses,
"reviews" : reviews,
"lectures" : lectures,
"reviews_count" : reviews_count,
"rating_count" : rating_count,
'similar_posts':similar_posts,
"all_star" : all_star,
'recent_courses': recent_courses,
"video" : video,
'discussions': discussions,
"video_count" : video_count,
'videos':videos,
'course': course,
'students_enrolled_for_a_creator': students_enrolled_for_a_creator,
'is_saved':is_saved,
'rating_average':rating_average,
}
return render(request, 'course/course-detail.html', context)
You should query like this using filter() if you want to get all videos related to curriculum:
# #login_required
def course_details(request, course_slug):
if request.user.is_authenticated:
user = request.user
course = Course.objects.get(slug=course_slug)
curriculum = Curriculum.objects.filter(course=course)
serial_number = request.GET.get('lecture')
videos = Video.objects.filter(curriculum=curriculum).order_by('serial_number')
...
Note: It is generally better to use get_object_or_404 instead of get(), it automatically handles http 404 error.
Use as:
course = get_object_or_404(Course,slug=course_slug)
You have to use the Video manager and filter by the curriculum instance.
Try it like this:
# #login_required
def course_details(request, course_slug):
if request.user.is_authenticated:
user = request.user
course = Course.objects.get(slug=course_slug)
curriculum = Curriculum.objects.filter(course=course)
serial_number = request.GET.get('lecture')
videos = Video.objects.filter(curriculum=curriculum).order_by('serial_number')
...
More info in the official docu
Related
this is my model of Qualification Approval
class QualificationApproval(models.Model):
"""Model definition for QualificationApproval."""
# TODO: Define fields here
qtitle = models.ForeignKey(Qualification, on_delete=models.CASCADE)
ofEqualCode = models.CharField(max_length=100)
porposDate = models.DateField()
anNo = models.IntegerField()
status = models.CharField(max_length= 50, default="pending")
sec9 = models.ForeignKey(Sec9, on_delete=models.CASCADE)
class Meta:
"""Meta definition for QualificationApproval."""
verbose_name = 'QualificationApproval'
verbose_name_plural = 'QualificationApprovals'
so here is qtitle is foreign key of qualification
the problem is that when I assign the qualification in QualifcationApproval so its give me and error
def sec9edit(request, secId):
if 'userId' not in request.session:
return render(request, "front/login.html", {
"message": "Login Required First"
})
user = User.objects.get(pk = request.session['userId'])
sec1 = Sec1.objects.get(user = user )
qualification = Qualification.objects.all()
if request.method == "POST" and secId:
sec9 = Sec9.objects.get(pk = secId)
sec9.curriculum = request.POST['curriculum']
sec9.save()
qlrn = request.POST.getlist('qualification')
code = request.POST.getlist('code')
pdate = request.POST.getlist('pdate')
anticipated = request.POST.getlist('anticipated')
j = 0
qa = QualificationApproval.objects.filter(sec9 = sec9)
for q in qlrn:
if q:
qua = Qualification.objects.get(pk = q.split(',')[0])
print(type(qa[j].qtitle))
qa[j].qtitle = qua,
qa[j].ofEqualCode = code[j],
qa[j].porposDate = pdate[j],
qa[j].anNo = anticipated[j],
qa[j].sec9 = sec9
qa[j].save()
messages.success(request, 'Section 9 udpated successfully')
return HttpResponseRedirect(reverse('addCentre/sec10'))
else:
try:
sec9 = Sec9.objects.get(sec1= sec1)
qa = QualificationApproval.objects.filter(sec9 = sec9)
except:
return render(request, "front/sec9.html", {
"qualification": qualification
})
return render(request, "front/sec9.html", {
"qualification": qualification,
"sec9": sec9,
"qa": qa
})
I print the qa.qtitle it give me the result
<class 'lrnadmin.models.Qualification'>
but when I assign
it shows this error
ValueError: Cannot assign "(<Qualification: Qualification object (1)>,)": "QualificationApproval.qtitle" must be a "Qualification" instance.
you have additional , at the end
# ↓ delete this commas
qa[j].qtitle = qua, ↓
qa[j].ofEqualCode = code[j],
qa[j].porposDate = pdate[j],
qa[j].anNo = anticipated[j],
should be like this:
qa[j].qtitle = qua
qa[j].ofEqualCode = code[j]
qa[j].porposDate = pdate[j]
qa[j].anNo = anticipated[j]
I get an Integrity error, Foreign Key Constraint failed. I have the following function I am trying to run:
if request.method == "POST":
#Get token
access_token = AccessToken.objects.get(token = request.POST.get('access_token'),
expires__gt = timezone.now())
#Get profile
customer = access_token.user.customer
# Check if customer has a order that is not delivered
if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED):
return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"})
# Check Address
if not request.POST["address"]:
return JsonResponse({"status": "failed", "error": "Address is required."})
# Ger Order Details
order_details = json.loads(request.POST["order_details"])
order_total = 0
for meal in order_details:
order_total += Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"]
if len(order_details)>0:
# Step 1 - Create an Order
order = Order.objects.create(
customer = customer,
restaurant_id = request.POST["restaurant_id"],
total = order_total,
status = Order.PENDING,
address = request.POST["address"]
)
# Step 2 - Create Order details
for meal in order_details:
OrderDetails.objects.create(
order = order,
meal_id = meal["meal_id"],
quantity = meal["quantity"],
sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"]
)
return JsonResponse({"status": "success"})
Here is my order class:
Class Order(models.Model):
PENDING = 1
COOKING = 2
READY = 3
ONTHEWAY = 4
DELIVERED = 5
STATUS_CHOICES = (
(PENDING, "Pending"),
(COOKING, "Cooking"),
(READY, "Ready"),
(ONTHEWAY, "On The Way"),
(DELIVERED, "Delivered"),
)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE, blank = True, null = True)
address = models.CharField(max_length=500)
total = models.IntegerField()
status = models.IntegerField(choices = STATUS_CHOICES)
created_at = models.DateTimeField(default = timezone.now)
picked_at = models.DateTimeField(blank = True, null = True)
def __str__(self):
return str(self.id)
I previously got an error because Driver was not null so I added blank = True, null = True. Now it gives the Foreign Key Contraint Error.
I am testing the function is postman, and I do not define the driver anywhere, the driver is to be added later not while the function is called.
This is my views.py
def restaurant_add_meal(request):
form = MealForm()
if request.method == "POST":
form = MealForm(request.POST, request.FILES)
if form.is_valid():
meal = form.save(commit=False)
meal.restaurant = request.user.restaurant
meal.save()
return redirect(restaurant_meal)
return render(request, 'restaurant/add_meal.html', {
"form": form
})
I changed restaurant_id = request.POST["restaurant_id"] to
restaurant = Restaurant.objects.get(pk = request.POST["restaurant_id"])
and the error is fixed.
I'm writing my first app in django and i have encountered a problem. I'm trying to make a booking system. I'm trying to save the reservation model. It works just fine while the user is logged out. But once i click submit while logged in nothing really happens. The site simply reloads. Can anyone point out what I'm doing wrong?
That's my model code:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
name = models.CharField(max_length = 100)
surname = models.CharField(max_length = 100)
phone = models.CharField(max_length = 9)
class Reservation(models.Model):
reservationID = models.AutoField(primary_key = True)
name = models.CharField(max_length = 100)
surname = models.CharField(max_length = 100)
phone = models.CharField(max_length = 9)
email = models.EmailField()
bookIn = models.DateField('Book in date', default = timezone.now)
bookOut = models.DateField('Book out date', default = timezone.now)
roomType = models.ForeignKey(Room_type, on_delete = models.CASCADE)
My form:
class Booking(forms.ModelForm):
class Meta:
model = Reservation
fields = ('name', 'surname', 'phone', 'email', 'roomType', 'bookIn', 'bookOut',)
widgets = {
'bookIn': forms.DateInput(attrs={'class': 'datepicker'}),
'bookOut': forms.DateInput(attrs={'class': 'datepicker'})
}
And my view:
form = Booking()
if request.method == 'POST':
form = Booking(request.POST)
if form.is_valid():
if request.user.is_authenticated:
reservation = Reservation()
guest = Profile.objects.get(user=request.user)
reservation.name = guest.name
reservation.surname = guest.surname
reservation.phone = guest.phone
reservation.email = guest.user.email
reservation.bookIn = form.cleaned_data.get('bookIn')
reservation.bookOut = form.cleaned_data.get('bookOut')
reservation.roomType = form.cleaned_data.get('roomType')
reservation.save()
else:
reservation = form.save()
reservation.save()
n = reservation.pk
return redirect('bookSuccess', n)
return render(request, 'hotel/bookRoom.html', {'form' : form})
I am assuming your form is not validating for some reason, and you need to catch it to see what might be going wrong. So you can update your view like this:
form = Booking(request.POST or None)
if request.method == 'POST':
if form.is_valid():
if request.user.is_authenticated:
reservation = form.save(commit=False)
# optimized the code
guest = Profile.objects.get(user=request.user)
reservation.name = guest.name
reservation.surname = guest.surname
reservation.phone = guest.phone
reservation.email = request.user.email
reservation.save()
else:
reservation = form.save() # removed duplicate save
n = reservation.pk
return redirect('bookSuccess', n)
return render(request, 'hotel/bookRoom.html', {'form' : form})
Update
You don't need to put null true and blank true in the model fields. You can pass the user data from view to form. and if the user is authenticated then pop the fields which is not necessary for authenticated user. Like this:
class Booking(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(Booking, self).__init__(*args, **kwargs)
if user.is_authenticated:
self.fields.pop('name') # or make them required false like this: self.fields['name'].required = False
self.fields.pop('surname')
# other fields unnecessary for authenticated user
# rest of the code
And use this form in view like this:
form = Booking(request.POST or None, user=request.user)
While I hit the search button..it shows the
Page not found (404)
No Category matches the given query.
My views
def search_in_category(request, slug):
# reset the search params, if present
try:
del request.session['search']
except KeyError:
pass
return search_results(request, slug)
def search_results(request, slug):
category = get_object_or_404(Category, slug=slug)
fields = list(category.field_set.all())
fields += list(Field.objects.filter(category=None))
fieldsLeft = [field.name for field in fields]
if request.method == "POST" or 'search' in request.session:
ads = category.ad_set.filter(active=True,
expires_on__gt=datetime.datetime.now())
# A request dictionary with keys defined for all
# fields in the category.
post = {}
if 'search' in request.session:
post.update(request.session['search'])
else:
post.update(request.POST)
sforms = prepare_sforms(fields, fieldsLeft, post)
isValid = True
for f in sforms:
# TODO: this assumes the form is not required
# (it's a search form after all)
if not f.is_valid() and not f.is_empty():
isValid = False
if isValid:
if request.method == 'POST':
request.session['search'] = {}
request.session['search'].update(request.POST)
return redirect('classifieds_browse_search_results', slug=slug)
for f in sforms:
ads = f.filter(ads)
if ads.count() == 0:
return render_to_response('classifieds/list.html',
{'no_results': True,
'category': category},
context_instance=RequestContext(request))
else:
context = context_sortable(request, ads)
context['category'] = category
return render_to_response('classifieds/list.html', context,
context_instance=RequestContext(request))
else:
sforms = prepare_sforms(fields, fieldsLeft)
return render_to_response('classifieds/search.html',
{'forms': sforms, 'category': category},
context_instance=RequestContext(request))
My models.py
class Category(models.Model):
site = models.ForeignKey(Site)
template_prefix = models.CharField(max_length=200, blank=True)
name = models.CharField(max_length=200)
slug = models.SlugField()
enable_contact_form_upload = models.BooleanField(default=False)
contact_form_upload_max_size = models.IntegerField(default=2 ** 20)
contact_form_upload_file_extensions = models.CharField(max_length=200,
default="txt,doc,odf,pdf")
images_max_count = models.IntegerField(default=0)
images_max_width = models.IntegerField(help_text=_(u'Maximum width in pixels.'),
default=1024)
images_max_height = models.IntegerField(help_text=_(u'Maximum height in pixels.'),
default=1024)
images_max_size = models.IntegerField(help_text=_(u'Maximum size in bytes.'),
default=2 ** 20)
images_allowed_formats = models.ManyToManyField(ImageFormat, blank=True)
description = models.TextField(default='')
sortby_fields = models.CharField(max_length=200,
help_text=_(u'A comma separated list of field names that should show up as sorting options.'),
blank=True)
sort_order = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.name + u' Category'
class Meta:
verbose_name_plural = u'categories'
My url
url(r'^search/(?P<slug>[-\w]+)/$', 'browse.search_in_category',
name='classifieds_browse_category_search'),
url(r'^search/results/(?P<slug>[-\w]+)/$', 'browse.search_results',
name='classifieds_browse_search_results'),
This my code, Why I am getting the 404 error? What I have to do for fix this error?
you cannot do
return search_results(request, slug)
do rather this redirect
return redirect(reverse('classifieds_browse_search_results', kwargs={'slug':slug}))
dont forget to import
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
Iam working in django forms using python.
Iam facing an issue while saving editform.
If iam saving the form with charfield and textfield changes, its working fine(refreshing with the updated content).
But if i save the form by changing the imagefield and charfield, its updating but not refreshing the page.
I want the page to be refreshed once the details updated or saved.
Thanks in Advance.
MY VIEWS.PY:
def profile_page(request,type = None):
profile_list = get_object_or_404(UserProfile, visit_id = request.user.username, profile_type = type)
image = UserProfile.objects.get(visit_id = request.user.username, profile_type = type).image
if request.method == "POST":
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
new_image = form.cleaned_data['image']
if new_image == None:
current_image=form.fields['image'].initial = profile_list.image
else:
person = UserenaSignup.objects.get(visitid = request.user.username).id
UserImage.objects.filter(username = person, profile_type = type).delete()
current_image = UserImage.objects.create(username_id = person, profile_type = type, image = form.cleaned_data['image']).image
UserProfile.objects.filter(visit_id = request.user.username, profile_type = type).update(username = form.cleaned_data['username'],
designation = form.cleaned_data['designation'],
image = current_image,
)
return render_to_response('profile_page.html',locals(),context_instance = RequestContext(request))
else:
form = UserProfileForm(instance = profile_list)
return render_to_response('profile_page.html', locals(), context_instance=RequestContext(request))
else:
form = UserProfileForm(instance = profile_list)
return render_to_response('profile_page.html',locals(),context_instance = RequestContext(request))
You can try to remove .image from the end of this line:
current_image = UserImage.objects.create(username_id = person, profile_type = type, image = form.cleaned_data['image']).image