I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks
views.py
def UpdateReservation(request, pk):
table_exists = Reservation.objects.get(id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
if request.POST['table']:
request.POST = request.POST.copy()
table_exists = Reservation.objects.get(id=pk)
try:
if table_exists:
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists)
resrv.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
except Exception as e:
messages.error(request, "Unknown error" + str(e))
return redirect(request.path)
context = {"form":form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update'
It is better to validate the form and update the individual fields with respective values and then save the object. The view should be as follows:
from django.shortcuts import get_object_or_404
def UpdateReservation(request, pk):
table_exists = get_object_or_404(Reservation, id=pk)
form = ReservationForm(instance=table_exists)
if request.method == "POST":
form = ReservationForm(request.POST, instance=table_exists)
if form.is_valid():
time = form['time']
people = form['people']
comment = form['comment']
date_reserved = form['date_reserved']
email = form['email']
phone = form['phone']
first_name = form['first_name']
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.save()
messages.success(request, "you have successfully edited.")
return redirect(request.path)
else:
messages.error(request, "Unable to edit.")
return redirect(request.path)
context = {"form": form}
return render(request, "dashboard/super/admin/update_reserve.html", context)
You should use model like this:
table_exists = Reservation.objects.get(id=pk)
table_exists.email = email
table_exists.first_name = first_name
table_exists.people = people
table_exists.time = time
table_exists.date_reserved = date_reserved
table_exists.comment = comment
table_exists.table = table_exists
table_exists.save()
Related
I am kinda like stuck.
I have a BankAccountCreation() and the the form is called in a modal in Django template.
I am trying to get the same for be used for editing. but when I do that my edit button returns an empty form
My view is as below
def employee_info(request, id):
if not request.user.is_authenticated:
return redirect('/')
context = {}
banks = Bank.objects.all()
employee = get_object_or_404(Employee, id = id)
bank_instance = Bank.objects.filter(employee = employee).first()
context = {}
context['employee'] = employee
context['bank'] = bank_instance
context['banks'] = banks
context['title'] = 'profile - {0}'.format(employee.get_full_name)
if request.method == 'GET':
form = BankAccountCreation()
context['form'] = form
return render(request, 'employee/employee_info.html', context)
if request.method == 'POST':
form = BankAccountCreation(data = request.POST)
if form.is_valid():
instance = form.save(commit = False)
employee_id = request.POST.get('employee')
employee_object = employee
instance.employee = employee_object
instance.name = request.POST.get('name')
instance.branch = request.POST.get('branch')
instance.account = request.POST.get('account')
instance.code = request.POST.get('code')
instance.save()
messages.success(request, 'Bank Details Successfully Created for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-success alert-dismissible show')
return redirect('employee_info', id=employee.id)
else:
context['form'] = form
messages.error(request, 'Error Updating details for {0}'.format(employee_object.get_full_name), extra_tags = 'alert alert-warning alert-dismissible show')
return redirect('employee_info', id=employee.id)
form = BankAccountCreation()
return render(request, 'employee/employee_info.html', context)
The Bank model has a foreign key to the Employee model
i have a small form in my blog detail view and it has a name,last name,email and an image field. the first three work fine but when i add the imagefield in the form, the form wont save from the page but it works from admin page.
this is my views.py:
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
form = FormCamp(request.POST)
if request.method == 'POST':
if form.is_valid():
name = request.POST.get('name')
last = request.POST.get('last')
email = request.POST.get('email')
comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email)
comment.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
and this is my comment model:
class CampaignForm(models.Model):
campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
last = models.CharField(max_length=100)
email = models.EmailField()
image = models.ImageField(upload_to='images')
this is a non user form, so everyone can fill it. please help me understand how to add the ability to upload an image in this form
oh and this the form:
class FormCamp(forms.ModelForm):
class Meta:
model = CampaignForm
fields = ('name','last','email', 'image',)
THANKS ALOT FOR THE ANSWERS AND SUPPORTS
Instead of using the form to validate and then manually extracting the fields again, you should use the save method of your ModelForm and pass request.FILES to your form when creating it.
And as the campaign is not an editable field, it shall be added after creating the object.
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
if request.method == 'POST':
form = FormCamp(request.POST, request.FILES)
if form.is_valid():
campaign_form = form.save(commit=False)
campaign_form.campaign = campaign
campaign_form.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#the-save-method
https://docs.djangoproject.com/en/2.2/topics/forms/#the-view
Try this:
def campaign_detail_view(request, id):
template_name = 'gngo/campaign-detail.html'
campaign = get_object_or_404(Campaign, id = id)
comments = CampaignForm.objects.filter(campaign=campaign).order_by('-id')
form = FormCamp(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
comment = form.save(commit=False)
comment = CampaignForm.objects.create(campaign=campaign,name=name,last=last,email=email)
comment = request.FILES['image']
comment.save()
return redirect('campaign-detail',id=id)
else:
form = FormCamp()
context = {
'campaign':campaign,
'comments':comments,
'form':form,
}
context["object"] = Campaign.objects.get(id = id)
return render(request, template_name, context)
class FormCamp(forms.ModelForm): to this;
class FormCamp(forms.Form):
Don't forget to add enctype=multipart/form-data in your form in template.
I'm trying to do a web page using django. Where a user can register and login to the page. But When I try to login the authenticate function returns None even if the entered password and username are correct.
I'm using django version 2.1.2 and Python 3.5
I have tried adding
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',)
in settings.py
this is the function that I'm using for registration.
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.refresh_from_db()
username= request.POST.get('username')
user.password=form.cleaned_data.get('password1')
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.save()
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})
This is the function that i use for login
class getLogin(View):
def get(self, request):
if request.user.is_authenticated:
return render(request, "authentication/signin.html")
else:
return render(request,"authentication/signin.html")
def post(self, request):
user = request.POST.get('user')
password = request.POST.get('pass')
usernamelog = User.objects.get(username=user)
auth = authenticate(username=usernamelog, password=password)
print("auth",auth)
if auth:
request.session['user']=auth.id
request.session['grade']=auth.student.grade
print("re",request.session['user'])
print("ath",auth.username)
request.session['username']=auth.username
print("usr", request.session['username'])
request.session['super']=auth.is_superuser
print("ddd",auth.student.grade)
# request.session['auth'] = auth.is_superuser
if auth.is_superuser:
return render(request,"app/admin.html")
else:
student_id=request.session['user']
grade = request.session['grade']
ex = Exam.objects.filter(level=grade)
code = Code.objects.filter(student_id=student_id)
return render(request, "app/student.html", {'link': ex, 'code': code,'profile':student_id})
else:
messages.add_message(request, messages.ERROR, 'Username or password mismatch')
return redirect('login')
I'm not able to authenticate the user even the given username and password are correct
First of all, as Daniel Roseman pointed out, you are overwriting the correctly saved user object with unhashed password. If you want to save the Student model, the you should call user.student.save() instead of user.save().
def SignUp(request):
countryobj = Country.objects.all()
if request.method == 'POST':
form = CustomUserCreationForm(request.POST or None)
gr=request.POST.get('grade')
if gr == 'Grade':
messages.add_message(request, messages.WARNING, 'Select Any Grade')
return render(request, 'authentication/registration.html', {'form': form, 'countries': countryobj})
if form.is_valid():
print("hihihih")
user = form.save()
user.student.birthdate = form.cleaned_data.get('birthdate')
user.student.school_name = form.cleaned_data.get('school_name')
user.student.individual = form.cleaned_data.get('individual')
user.student.school_address = form.cleaned_data.get('school_address')
user.student.country = form.cleaned_data.get('country')
user.student.state = form.cleaned_data.get('state')
user.student.communication_address = form.cleaned_data.get('communication_address')
user.student.c_country = form.cleaned_data.get('c_country')
user.student.c_state = form.cleaned_data.get('c_state')
user.student.grade = form.cleaned_data.get('grade')
user.student.cost = form.cleaned_data.get('cost')
user.student.total = form.cleaned_data.get('total')
user.student.type_user = form.cleaned_data.get('type_user')
user.student.currency=form.cleaned_data.get('currency_code')
user.student.save() # this will save the Student data
subject = 'Registration Successfull'
message = 'You have successfully completed registration....'+'\n'+'Username:' +user.username+'\n'+ 'Password:' +user.password
email_from = settings.EMAIL_HOST_USER
recipient_list = [user.email]
send_mail(subject, message, email_from, recipient_list)
messages.add_message(request, messages.SUCCESS, 'Registration Successfull .. Check E-mail for credentials')
return redirect('login')
else:
form = CustomUserCreationForm()
return render(request, 'authentication/registration.html', {'form': form,'countries':countryobj})
else:
form = CustomUserCreationForm()
print("lalala")
# return render(request, 'authentication/registration.html')
print(countryobj)
return render(request, 'authentication/registration.html',{'form':form,'countries':countryobj})
views.py
def patient_num(request):
if request.method == 'POST':
form = EditToBeSaveForm(request.POST)
if form.is_valid():
num = form.cleaned_data['病人编号']
new_p = Patient.objects.get(p_number=num)
if new_p:
new_p.p_name = form.cleaned_data['姓名']
new_p.p_sex = form.cleaned_data['性别']
new_p.p_age = form.cleaned_data['年龄']
new_p.p_tel_number = form.cleaned_data['电话号码']
new_p.save()
return render(request, 'polls/patient_edit.html')
else:
form = EditToBeSaveForm()
return render(request, 'polls/patient_num.html', {'form': form})
models.py
class Patient(models.Model):
sex_choice = (
('男', '男'),
('女', '女'),
)
p_name = models.CharField(max_length=100, default='template')
p_age = models.IntegerField(default=0)
p_number = models.IntegerField(default=0)
p_tel_number = models.IntegerField(default=0)
p_sex = models.CharField(choices=sex_choice, max_length=2, default='男')
forms.py
class EditForm(forms.Form):
病人编号 = forms.IntegerField()
class EditToBeSaveForm(forms.Form):
sex_choice = (
('male', '男'),
('female', '女'),
)
病人编号 = forms.IntegerField(label='你要修改的病人编号')
姓名 = forms.CharField(max_length=100)
年龄 = forms.IntegerField()
电话号码 = forms.IntegerField()
性别 = forms.ChoiceField(choices=sex_choice)
after i populate the form and submit it, the view didn't update the database instance,why?
i can do it one by one in shell as below.
new confuse!when i populate the form with invalid value,for example, an inexistent id of Patient object,it will still render the template,why?
It seems to me your problem is that you never reach the code under the if form.is_valid() of your patient_num view. Try to add some prints after the if form.is_valid() clause and make sure your form is valid. It is expected that your model will not be updated if your form is not valid.
Your problem here that you are passing request to form instead request.POST
form = EditToBeSaveForm(request.POST)
i put some 'print stuff' in my view and disvocer sth:
def patient_num(request):
print(111)
if request.method == 'POST':
print(2222)
form = EditToBeSaveForm(request.POST)
if form.is_valid():
print(3333)
num = form.cleaned_data['病人编号']
new_p = Patient.objects.get(p_number=num)
if new_p:
print(4444)
new_p.p_name = form.cleaned_data['姓名']
new_p.p_sex = form.cleaned_data['性别']
new_p.p_age = form.cleaned_data['年龄']
new_p.p_tel_number = form.cleaned_data['电话号码']
new_p.save()
return render(request, 'polls/patient_edit.html')
else:
form = EditToBeSaveForm()
return render(request, 'polls/patient_num.html', {'form': form})
i can only see 111 in the shell output.it seems that the view even didn't receive the post request.and i check my html file and find the problem.the form's destination direct to another view function…… it's so stupid, i'm sorry for waste your time !
I made a simple pet store app and just added search box feature and I received this error
ValueError at /pet/search/
The view mysite.pet.views.search_page didn't return an HttpResponse object.
I tried to change render_to_response into HttpResponseRedirect but still got the same error.
Linking back to my search_page function in views.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
I did some research and I understand a view has to return a HttpResponse when a HttpRequest is made and render_to_response is just a shortcut.Can someone help explain why this function won't work.Thank you
You are getting this problem because you havn't written a HttpResponse object if request type is not POST
To overcome this in your view write somthing which will process if request type is not post
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
Hope this will help you thanks
The error is because when the function is called the method type is not POST and it does not find the corresponding HttpResponse object.
def search_page(request):
form = SearchForm()
if request.method == "POST":
f = SearchForm(request.POST)
if f.is_valid():
Pets = Pet.objects.filter(animal = f.cleaned_data["text"])
return HttpResponseRedirect("search.html",{"Pets":Pets},{"form":form})
else:
return render_to_response("search.html",{"form":form} , context_instance = RequestContext(request))
return render_to_response("any.html",{} , context_instance = RequestContext(request))
def addsponser(request):
if request.method == 'POST':
# return HttpResponse(request,'error is here')
if (request.POST.get('firstname') and
request.POST.get('lastname') and
request.POST.get(' email') and
request.POST.get('phone_Number') and
request.POST.get('gender') and
request.POST.get('state') and
request.POST.get('adress') and
request.POST.get('postal_code') and
request.POST.get('town')
):
fname = request.POST.get('firstname')
lname = request.POST.get('lastname')
em = request.POST.get(' email')
phn = request.POST.get('phone_Number')
gnd = request.POST.get('gender')
stt = request.POST.get('state')
add = request.POST.get('adress')
pstc = request.POST.get('postal_code')
twn = request.POST.get('town')
try:
sponser = Sponsers()
sponser.firstname = fname
sponser.lastname = lname
sponser.email = em
sponser.Phone_Number = phn
sponser.gender = gnd
sponser.state = stt
sponser.adress = add
sponser.postal_code = pstc
sponser.town = twn
sponser.save()
messages.success(request, "sponser Added")
return redirect('sponsers')
except Exception:
messages.error(request, "Failed to add sponser")
return redirect('sponsers')
else:
pass
else:
return redirect('sponsers')