Django form not refreshing once updated - python

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

Related

'QuerySet' object has no attribute 'videos_set'

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

Why is fileChoice.value() None?

I am working in Django 3.2.13 trying to create a simple upload form for a file model with a chained foreign key. I have tried creating a form with a basic form model and a ModelForm, however, even when checking request.FILES there is no data and request_file = request.FILES['document'] if 'document' in request.FILES else Noneyields None.
views.py
def home(request):
if handleAuth(request) is not None:
return handleAuth(request)
user = request.user
if request.method == "POST":
# if the post request has a file under the input name 'document', then save the file.
form = FileSubmissionForm(user, request.POST, request.FILES)
#print(request.FILES)
#request_file = request.FILES['document'] if 'document' in request.FILES else None
#if request_file:
form.save()
#else:
# print("NO FILE")
userFiles = []
if user.is_company_admin:
temp = StorageFile.objects.filter(company_key=user.company_key)
else:
temp = StorageFile.objects.filter(company_key=user.company_key,
profile__in=user.user_profiles.all())
temp.order_by("profile")
for file in temp:
userFiles.append({"name": file.getFileName(), "path": file.getMediaPath()})
form = FileSubmissionForm(user)
return render(request=request,
template_name="fileCloudApp/home.html",
context={"userHasAdmin": user.is_company_admin, "files": userFiles, "form": form})
forms.py
from django import forms
from fileCloudApp.models import StorageFile
from loginApp.models import UserProfile
class FileSubmissionForm(forms.Form):
fileChoice = forms.FileField()
profileChoice = forms.ModelChoiceField(queryset=UserProfile.objects.none(), label="Choose profile")
def __init__(self, user, *args, **kwargs):
super(FileSubmissionForm, self).__init__(*args, **kwargs)
if user.is_company_admin:
temp = UserProfile.objects.filter(company_key=user.company_key)
else:
temp = user.user_profiles.all()
temp.order_by("label")
self.fields["profileChoice"].queryset = temp
self.user = user
def save(self):
print(self["fileChoice"].value()) # None
pro = UserProfile.objects.filter(id=int(self["profileChoice"].value()))
if len(pro) > 0:
pro = pro[0]
print(pro)
models.py
class StorageFile(models.Model):
date_updated = models.DateTimeField('Date Updated', default=timezone.now)
company_key = models.ForeignKey(CompanyModel, verbose_name="Company", on_delete=models.CASCADE)
file_upload = models.FileField(upload_to=company_directory_path)
profile = ChainedForeignKey(
UserProfile,
chained_field="company_key",
chained_model_field="company_key",
show_all=False,
auto_choose=True,
sort=True,
on_delete=models.PROTECT)
def getLocalPath(self):
return self.file_upload.name.split(str(self.company_key.id) + "/")[1]
def getMediaPath(self):
return "get/{0}/0/{1}".format(self.id, self.getFileName())
def getFileName(self):
return self.file_upload.name.split("/")[-1]
def getFilePath(self):
return settings.MEDIA_ROOT + "{0}/{1}".format(str(self.company_key.id), self.getFileName())
def __str__(self):
return str(self.company_key) + ": " + str(self.file_upload)
Form must contain enctype="multipart/form-data"
<form action="" method="post" enctype="multipart/form-data">

Django Saving A Model With Form + Current User Data

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)

Putting an init method on an InLineFormSet

I have used an InLineFormSet to display all of the records that relate to a particular timesheet. The user can add many new forms on the page, I've used ajax and html to append an empty existing_form on the bottom with new IDs. However saving this is a problem.... because the newly added forms do not have timesheet_id assigned yet, they don't save as part of existing_forms.
I am trying to put an init method together to assign this when the form is created, hopefully solving this problem. (?)
1) Do I have to save the record before it will become part of existing_formset?
2) I have excluded the timesheet_id from the TimeForm.... this means I assume form.timesheet_id = var will not work... and I would have to use obj.timesheet_id... but can I do this in the init of a form?? very confused.
3) Is it easier to use a new formset for newly added forms and use modelformset_factory.....
View:
class CustomInlineFormSet(BaseInlineFormSet):
def clean(self):
super(CustomInlineFormSet, self).clean()
timesheet = TimeSheet.objects.get(pk=timesheet_id)
for form in self.forms:
form.empty_permitted = True
def __init__(self, request, *args, **kwargs):
super(CustomInlineFormSet, self).__init__(*args,**kwargs)
# the following won't work because it's excluded from the form?
# self.fields['timesheet_id'] = forms....... oh no
timesheet_fromview = request.session.get('timesheet')
print timesheet_fromview
for form in self.forms:
obj = form.save(commit=False)
obj.timesheet_id = timesheet_fromview
try:
del request.session['timesheet']
print "session deleted"
except KeyError:
pass
print "Key error raised"
def timesheet(request, timesheet_id):
timesheet = TimeSheet.objects.get(pk=timesheet_id)
TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet)
if request.method == 'POST':
# instance is not yet timesheet.... no foreign key in new fields so doesn't do anything
existing_formset = TimeInlineFormSet(request.POST, request.FILES, instance=timesheet)
for thetime in existing_formset.forms:
# obj = thetime.save(commit=False)
# obj.timesheet_id = timesheet
# obj.save()
# print obj
if thetime.is_valid():
print "existing time is valid"
thetime.save()
else:
"existing time is not valid"
context = {
"timesheet": timesheet,
"existing_formset": existing_formset,
}
return render(request, 'tande/timesheet.html', context)
else:
print "method is not post"
existing_formset = TimeInlineFormSet(instance=timesheet)
new_timeformset = NewTimeFormSet()
request.session['timesheet'] = timesheet
context = {
"timesheet": timesheet,
"existing_formset": existing_formset,
}
return render(request, 'tande/timesheet.html', context)
I've approached this by using two separate formsets in my views, one inline for existing records and one modelformset for new additions. I then save the two separately with a field that is True when the record is a new addition, and False when it is in the existing formset:
class Time(models.Model):
project_id = models.ForeignKey(Project, null=True)
date_worked = models.DateField(null=True, blank=True)
hours = models.CharField(max_length=1)
description = models.CharField(max_length=150)
timesheet_id = models.ForeignKey(TimeSheet, null=True)
add_row = models.CharField(max_length=10, default=True, editable=False)
def __unicode__ (self):
return self.description
The view saves the two formsets separately:
def timesheet(request, timesheet_id):
timesheet = TimeSheet.objects.get(pk=timesheet_id)
TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet)
NewTimeFormSet = modelformset_factory(Time, form=TimeForm, formset=RequiredFormSet)
if request.method == 'POST':
existing_formset = TimeInlineFormSet(request.POST, request.FILES, instance=timesheet)
newtime_formset = NewTimeFormSet(request.POST, request.FILES)
for orange in newtime_formset:
obj = orange.save(commit=False)
if obj.add_row == "True":
obj.timesheet_id = timesheet
obj.add_row = "False"
obj.save()
for thetime in existing_formset.forms:
if thetime.is_valid():
thetime.save()
existing_formset = TimeInlineFormSet(instance=timesheet)
newtime_formset = NewTimeFormSet()
context = {
"timesheet": timesheet,
"existing_formset": existing_formset,
"newtime_formset": newtime_formset,
}
return render(request, 'tande/timesheet.html', context)

How to insert Checkbox in django

hallo i want to create data with checkbox field but data cannot save in database when i use widget RadioSelect
this is forms.py
class VehicleAttribute(forms.ModelForm):
OPERATION = [('production','Production Vehicle'),('supporting','Supporting Vehicle')]
PAYLOAD_METER = [('yes','Yes'),('no','No')]
NUMBER_STRUT = [('0','0'),('3','3'),('4','4')]
operation = forms.ChoiceField(widget=forms.RadioSelect, choices = OPERATION)
payload_meter = forms.ChoiceField(widget=forms.RadioSelect, choices = PAYLOAD_METER)
number_of_strut_pressure = forms.ChoiceField(widget=forms.RadioSelect, choices = NUMBER_STRUT)
class Meta:
model = Vehicle_attribute
fields = ['operation','payload_meter','number_of_strut_pressure']
this is views.py
def data_vehicle_add(request):
if request.method == "POST":
form = VehicleAttribute(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('data_vehicle_add.html', pk=post.pk)
else:
form = VehicleAttribute()
return render(request,'data_vehicle_add.html', {'form':form}, context_instance=RequestContext(request))
can you help me solve this problem?

Categories

Resources