Django same function data not showing after page render - python

I am creating university management system using django. I have created faculty(teacher) registration form. For that, in my views.py
def faculty_registration(request):
data = {}
form = FacultyRegisterForm()
activetab = 'list'
if request.method == 'POST':
activetab = 'add'
form = FacultyRegisterForm(request.POST)
if form.is_valid():
userdata = User()
if User.objects.filter(username=request.POST.get('email')).exists():
messages.error(request, f"This email already exists.")
return redirect('/faculty/faculty_registration')
else:
userdatafirst_name = request.POST.get("first_name")
userdata.username = request.POST.get('email')
userdata.email = request.POST.get('email')
try:
fac_ID = Faculty.objects.last().id
except:
fac_ID = 0
LastInsertId = fac_ID+1
print('after_id',LastInsertId)
password = User.objects.make_random_password()
faculty_pw = password+str(LastInsertId)
print("pass",faculty_pw)
userdata.password = make_password(faculty_pw)
print( "teacher_pasword",userdata.password)
userdata.save()
fac = Faculty()
fac.faculty_college_id = request.POST.get("faculty_college")
fac.faculty_programme_id = request.POST.get('faculty_programme')
fac.salutation = request.POST.get("salutation")
fac.first_name = request.POST.get("first_name")
fac.middle_name = request.POST.get("middle_name")
fac.last_name = request.POST.get("last_name")
fac.phone = request.POST.get("phone")
fac.email = request.POST.get("email")
fac.address = request.POST.get('address')
fac.department = request.POST.get('department')
fac.highest_qualification = request.POST.get("highest_qualification")
fac.years_of_experience = request.POST.get('years_of_experience')
fac.previous_institute = request.POST.get('previous_institute')
# fac.documents = request.POST.get("documents")
if 'documents' in request.FILES:
filename = request.FILES['documents']
if str(filename).lower().split('.')[-1] == 'pdf':
if int(len(request.FILES['documents'].read())) < (3 * 1024 * 1024):
fac.documents = request.FILES['documents']
else:
messages.warning(request, "please upload a pdf within 3 mb")
navshow = 'add'
return redirect('faculty_registration')
else:
messages.warning(request, "please upload a pdf")
navshow = 'add'
return redirect('faculty_registration')
fac.photo = request.FILES.get('photo', 'faculty_picture/def.png')
fac.created_by_id = request.user.id
fac.user_id = userdata.id
fac.save()
assign_role(userdata, 'teacher')
html_content = render_to_string("email_template.html",{'title':'Kindly Note your Mailid and Password For Login.','to_mail':fac.email,'to_password':faculty_pw})
text_content = strip_tags(html_content)
msg = EmailMessage(
'Welcome to University', #subject
text_content, #content
settings.EMAIL_HOST_USER, #from email
[fac.email], #reclist
)
msg.content_subtype = "html" # Main content is now text/html
msg.send()
# print("send_email",send_email)
messages.success(request, f"Lecturer has been added successfully")
return redirect('/faculty/faculty_registration')
else:
print("\ninvalid form\n")
else:
form = FacultyRegisterForm()
# fac_data = Faculty.objects.order_by('-id')
fac_data = Faculty.objects.order_by(Lower('first_name'))
data['form'] = form
data['faculties'] = fac_data
data['activetab'] = activetab
return render(request, 'faculty_register.html', data)
Also I have added searchbar button to search faculty name.
So I created following function:
def searchbar (request):
data = {}
find = request.GET['find']
res = Faculty.objects.filter(Q(first_name__icontains=find) | Q(middle_name__icontains=find)| Q(last_name__icontains=find))
activetab = 'list'
form = FacultyRegisterForm()
data['form'] = form
data['activetab'] = activetab
data['faculties'] = res
return render(request,"faculty_register.html",data)
I have also added 'add' functionality to add faculty.
Now my problem is when I click search button, I am not able to add faculty because I think i am rendering the same page 'faculty_register.html' in both return function. So how can I get same page data even after clicking 'search button'.
URLs:
urlpatterns = [
path('faculty_registration', views.faculty_registration, name='faculty_registration'),
path('faculty/searchbar', views.searchbar, name= 'searchbarf')]
I've tried to add searchbar function in faculty_registration but not able to solve this.

Related

i am making a django website with multiple forms also used foregin key ValueEror :The view Capp.views.InsertProduct didn't return anHttpResponseobject

i am making a django website with multiple forms also used foregin key(user_id) to link one form with other in the database but at the last i get value error the error is:Exception Type: ValueError
Exception Value:
The view Capp.views.InsertProduct didn't return an HttpResponse object. It returned None insteated ,
the following is view.py file code(not complete code but only where error can lie)models.py part
def InsertProduct(request):
if request.method == 'POST':
if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'):
saveproduct = ProInsert()
saveproduct.user_id = request.POST.get('user_id')
saveproduct.pname = request.POST.get('pname')
saveproduct.pcategory = request.POST.get('pcategory')
saveproduct.pdetails = request.POST.get('pdetails')
saveproduct.foundedin = request.POST.get('foundedin')
saveproduct.orderoftest = request.POST.get('orderoftest')
saveproduct.t1 = request.POST.get('t1')
saveproduct.t2 = request.POST.get('t2')
saveproduct.t3 = request.POST.get('t3')
saveproduct.f1 = request.POST.get('f1')
saveproduct.f2 = request.POST.get('f2')
saveproduct.f3 = request.POST.get('f3')
saveproduct.f4 = request.POST.get('f4')
saveproduct.f5 = request.POST.get('f5')
checkpname = ProInsert.objects.filter(
pname=saveproduct.pname).first()
return render(request, 'product_details.html')#here I had add what u said sir
if checkpname:
msgpname = messages.success(request, 'The user with Product Name ' +
request.POST['pname']+' already exist...!')
return render(request, 'product_details.html', {'msgpname': msgpname})
saveproduct.save()
messages.success(request, 'Product Added..!')
return render(request, 'product_details.html')
else:
return render(request, 'product_details.html')
I think you got it wrong I have update your code and commented the part i was telling you.
def InsertProduct(request):
if request.method == 'POST':
if request.POST.get('user_id') and request.POST.get('pname') and request.POST.get('pcategory') and request.POST.get('pdetails') and request.POST.get('foundedin') and request.POST.get('orderoftest') and request.POST.get('t1') and request.POST.get('t2') and request.POST.get('t3') and request.POST.get('f1') and request.POST.get('f2') and request.POST.get('f3') and request.POST.get('f4') and request.POST.get('f5'):
saveproduct = ProInsert()
saveproduct.user_id = request.POST.get('user_id')
saveproduct.pname = request.POST.get('pname')
saveproduct.pcategory = request.POST.get('pcategory')
saveproduct.pdetails = request.POST.get('pdetails')
saveproduct.foundedin = request.POST.get('foundedin')
saveproduct.orderoftest = request.POST.get('orderoftest')
saveproduct.t1 = request.POST.get('t1')
saveproduct.t2 = request.POST.get('t2')
saveproduct.t3 = request.POST.get('t3')
saveproduct.f1 = request.POST.get('f1')
saveproduct.f2 = request.POST.get('f2')
saveproduct.f3 = request.POST.get('f3')
saveproduct.f4 = request.POST.get('f4')
saveproduct.f5 = request.POST.get('f5')
checkpname = ProInsert.objects.filter(
pname=saveproduct.pname).first()
# return render(request, 'product_details.html')# NO need to add here as code below will be dead in this case.
if checkpname:
msgpname = messages.success(request, 'The user with Product Name ' +
request.POST['pname']+' already exist...!')
return render(request, 'product_details.html', {'msgpname': msgpname})
saveproduct.save()
messages.success(request, 'Product Added..!')
return render(request, 'product_details.html')
else:
return render(request, 'product_details.html')# What i meant was to add it here
else:
return render(request, 'product_details.html')

Python flask, when editing images in forms, form.image.data is empty

I have a form to edit an object created by another form, the editing form is not able to update the image to the new image and will display the old images.
when printing form.image.data, it is empty even though I am uploading an image file.
init.py
def edit_item(itemid):
context = {"message": ""}
item = itemcontroller.get_item_by_UID(itemid)
if(not item):
abort(404)
form = edit_sales_item(formdata=request.form, obj=item)
if request.method == 'POST' and form.validate():
f = form.image.data
print(f)
print(os.path.exists(PACKAGEDIR + form.UID.data))
if(f):
os.remove(ITEMSDIR + form.UID.data)
f.save(ITEMSDIR + form.UID.data)
update_form = form.data.copy()
update_form["image_url"] = ITEMSDIR + form.UID.data
item2 = itemcontroller.create_and_save_item(update_form)
if (item2):
context ={"message":"You have created a new item"}
itemcontroller.remove_sales_item(item)
flash("You have updated the item "+ item.get_UID() +" information")
return redirect(url_for("admin_pages.list_sales_items"))
else:
context ={"error":"A error have occured..."}
return render_template('admin/editing/edit_items.html', form=form, message=context, item=item)
forms.py
class edit_sales_item(FlaskForm):
UID = StringField("Unique ID:", validators=[validators.Length(min=3, max=10),DataRequired()])
name = StringField("Name: ", validators=[validators.Length(min=3, max=200) ,DataRequired()])
description = TextAreaField("Description: ", validators=[validators.Length(min=5, max=3000) ,DataRequired()])
price = DecimalField("Price: ", validators=[DataRequired()])# Regexp(
image = FileField("Image of product: ", validators=[FileAllowed(images ,'Image only!')])
stocks = IntegerField("Stocks amount: ", validators=[validators.NumberRange(min=1),DataRequired()])
submit = SubmitField()
the templates will just shows the form.

Same code, works in runserver but not in apache

views.py
def create_reply(request, topic_id):
if request.method == 'POST':
t = topic.objects.get(id=topic_id)
past_time = int(time.time() - t.locktime)
r = post()
r.topic = t
if request.POST['content']:
r.content = request.POST['content']
else:
return error(request, '不能空着')
# messages.add_message(request, messages.WARNING, _('content cannot be empty'))
# return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id}))
if past_time > 300:
messages.add_message(request, messages.WARNING, _('overtime'))
return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': topic_id}))
r.user = request.user
# when success to reply ,unlock the topic.
t.locker = '0'
t.locked = False
t.last_replier = request.user.username
r.floor = t.reply_count + 1
r.keyword = t.keyword
if t.keyword == "keywordwrite":
t.keyword = rand_key()
elif t.keyword == "freewrite":
t.keyword = None
user_has_subscribed = t.subscriber.filter(
username=request.user.username
)
if not user_has_subscribed:
t.subscriber.add(request.user)
t.save()
r.save()
sendemail.after_response(t.subscriber.all(),t)
sendemail(t.subscriber.all(), t)
return HttpResponseRedirect(reverse('topic_view', kwargs={'topic_id': t.id}))
elif request.method == 'GET':
return error(request, 'don\'t get')
sendemail is
from django.core.mail import EmailMessage
import after_response
#after_response.enable
def sendemail(users_list,topic):
def get_mail_list(users_list):
def getmail(user):
return user.email
mail_list = map(getmail,users_list)
return mail_list
link ='http://www.gushijielong.cn/topic/'+str(topic.id)
mail_list=get_mail_list(users_list)
mailtitle =u'你关注的主题:'+ topic.title + u'有新的接续了'
mailcontent = u'点击查看'+ topic.title + u'的新接续' + "<a href='" + link + u"'>点击</a>"
email = EmailMessage(mailtitle, mailcontent, to=mail_list)
email.content_subtype = "html"
print mailcontent
email.send()
This code is for sending email to the subscribers when a topic has a new reply.
It works( I can receive the emails ) in runserver, but not in apache.
sendemail() works well when I excute it in the server's console.

Formset.is_valid() False, why?

I'm trying to validate a form set, it shows in the template perfectly but when I try to save it, its validation returns False.
I tried to put some errors callbacks and the error in print(formset.non_form_errors) say the following:
<bound method PhysicianSpecialtiesFormFormSet.non_form_errors of <django.forms.formsets.PhysicianSpecialtiesFormFormSet object at 0x7fd70af38a10>>
I don't know what to do to have a correct input in the form; the form is a dropdown list, and it's impossible to get wrong.
def UpdatePhysician(request,id):
physician = get_object_or_404(Physician, id=id)
employee = get_object_or_404(Employee, id=physician.employee.id)
person = get_object_or_404(Person, id=employee.person.id)
try:
address = get_object_or_404(Address, id=return_id(str(person.addresses.values('id'))))
except:
address = None
try:
email = get_object_or_404(Email, id=return_id(str(person.emails.values('id'))))
except:
email = None
try:
phone = get_object_or_404(PhoneNumber, id=return_id(str(person.phone_numbers.values('id'))))
except:
phone = None
try:
academic_degree = get_object_or_404(AcademicDegree, id=return_id(str(employee.academic_degrees.values('id'))))
university = get_object_or_404(University, id=return_id(str(employee.academic_degrees.values('university'))))
except:
academic_degree = None
university = None
physician_specialties = get_list_or_404(PhysicianSpecialties, employee_academic_degree__employee__pk=physician.employee.id)
for item in physician_specialties:
print(unicode(item.specialty))
specialties = Specialty.objects.all()
specialty = PhysicianSpecialties.objects.filter(employee_academic_degree__employee__physician__pk=id)
SpecialtyFormset = modelformset_factory(PhysicianSpecialties, fields=('specialty',),max_num=1, labels=None, )
formset = SpecialtyFormset(queryset=PhysicianSpecialties.objects.filter(employee_academic_degree__employee__pk=physician.employee.id))
person_form = PersonForm(request.POST or None, instance=person)
employee_form = EmployeeForm(request.POST or None, instance=employee)
physician_form = PhysicianForm(request.POST or None, instance=physician)
email_form = EmailForm(request.POST or None, instance=email)
address_form = AddressForm(request.POST or None, instance=address)
phone_form = PhoneForm(request.POST or None, instance=phone)
academic_degree_form = AcademicDegreeForm(request.POST or None, instance= academic_degree)
university_form = UniversityForm(request.POST or None, instance=university)
if request.method == "POST":
if (person_form.is_valid() and employee_form.is_valid() and physician_form.is_valid() and email_form.is_valid() and
address_form.is_valid() and phone_form.is_valid and physician_form.is_valid() and university_form.is_valid and
academic_degree_form.is_valid() and formset.is_valid()):
person_form.save()
physician_form.save()
new_address = address_form.save()
new_email = email_form.save()
new_phone = phone_form.save()
# academic_degree_form.save()
# university_form.save()
formset.save()
if address == None:
PersonAddress.objects.create(person=person, address=new_address)
if email == None:
PersonEmail.object.create(person=person, email=new_email)
if phone == None:
PersonPhoneNumber.objects.create(person=person, hone_number=new_phone)
return HttpResponse('yesh')
else:
print(formset.is_valid())
print(formset.non_form_errors)
print('nope')
return HttpResponse('nope')
You haven't passed data to your formset. Without post data, your formset is unbound and will always be invalid.
formset = SpecialtyFormset(request.POST or None, queryset=PhysicianSpecialties.objects.filter(employee_academic_degree__employee__pk=physician.employee.id))
Another problem is that you are trying to display the errors incorrectly. formset.non_form_errors is a method, you have to call it.
print(formset.non_form_errors())
There may also be errors attached to the forms in the formset, you can see these by printing formset.errors.
print(formset.errors)

django testing response.context TypeError: 'NoneType' object is not subscriptable

I want to test this view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
#if True:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login /email are taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
And here is my part of my test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add anotheer user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEqual(response.context['code'],4)
And here is the error that I got:
,
in test_valid_credentials
self.assertEqual(response.context['code'],4)
TypeError: 'NoneType' object is not subscriptable
I tried it with get method and it works perfectly. Just with post it don't want to work.What am I doing wrong?Best regards
What is the response status? Redirects doesn't have context. Anyway, printing the response should help.
My guess is
key = register_user(login,email,password,newsletter)
throws an exception on duplicate register attempts and thus the handler does not generate a response.

Categories