<form action="{% url 'create'%}" method="POST" >
{% csrf_token %}
this in my template file.
def create(request):
return render(request, "auctions/create.html")
if request.method == "POST":
title = request.GET["title"]
des = request.GET["description"]
bid = request.GET["startingBid"]
imageurl= request.GET[ "imageUrl"]
category = request.GET["category"]
image = request.GET["image"]
listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category)
return render(request, "auctions/index.html",{
"listing":Auctionlisting.objects.all()
})
and this is in my views.py.
still after using csrf token i am getting 403 forbidden error. please some guide me.
Also these title, description and all are my inputs...
Just re-arrange your code like this:
def create(request):
if request.method == "POST":
title = request.GET["title"]
des = request.GET["description"]
bid = request.GET["startingBid"]
imageurl= request.GET[ "imageUrl"]
category = request.GET["category"]
image = request.GET["image"]
listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category)
listing.save() # save before getting them from database
return render(request, "auctions/index.html",{
"listing":Auctionlisting.objects.all()
})
else:
return render(request, "auctions/create.html")
Related
Got some forms in my view...
I want that only what I have submitted is changed in the database. So that no forms overwrite each other. How can I do this with my view?
I even noticed that the order in which each '..._form.is_valid()' is, makes a difference in what gets overwritten
views.py
#login_required
def DashboardView(request):
browser = str(request.user_agent.browser.family)
user = str(request.user)
short_user = user[0:7] + "..."
try:
radius = request.user.fieldradius
except FieldRadius.DoesNotExist:
radius = FieldRadius(user=request.user)
try:
font_size = request.user.fontsize
except FontSize.DoesNotExist:
font_size = FontSize(user=request.user)
try:
change_color = request.user.colors
except Colors.DoesNotExist:
change_color = Colors(user=request.user)
try:
toggle_settings = request.user.togglesettings
except ToggleSettings.DoesNotExist:
toggle_settings = ToggleSettings(user=request.user)
try:
page_details = request.user.pagedetails
except PageDetails.DoesNotExist:
page_details = PageDetails(user=request.user)
if request.method == 'POST':
form = FieldForm(request.POST, instance=Field(user=request.user))
togglesettings_form = ToggleSettingsForm(
request.POST, instance=toggle_settings)
radius_form = FieldRadiusForm(request.POST, instance=radius)
change_color_form = ColorsForm(request.POST, instance=change_color)
fontsize_form = FontSizeForm(request.POST, instance=font_size)
pagedetails_form = PageDetailsForm(
request.POST, request.FILES, instance=page_details)
if togglesettings_form.is_valid():
togglesettings_form.save()
return redirect('/dashboard/#panel1')
if form.is_valid():
time.sleep(1.5)
obj = form.save(commit=False)
obj.creator_adress = get_client_ip(request)
obj.save()
return redirect('/dashboard')
if radius_form.is_valid():
radius_form.save()
return redirect('/dashboard')
if fontsize_form.is_valid():
fontsize_form.save()
return redirect('/dashboard')
if change_color_form.is_valid():
change_color_form.save()
return redirect('/dashboard')
if pagedetails_form.is_valid():
pagedetails_form.save()
return redirect('/dashboard')
else:
form = FieldForm()
radius_form = FieldRadiusForm(instance=radius)
fontsize_form = FontSizeForm(instance=font_size)
change_color_form = ColorsForm(instance=change_color)
pagedetails_form = PageDetailsForm(instance=page_details)
togglesettings_form = ToggleSettingsForm()
return render(request, 'dashboard.html', {'form': form, 'togglesettings_form': togglesettings_form, 'fontsize_form': fontsize_form, 'change_color_form': change_color_form, 'browser': browser, 'short_user': short_user, 'radius_form': radius_form, 'radius': radius, 'pagedetails_form': pagedetails_form})
If I submit a form, for example the togglesettings_form, it looks like this in the database:
After that, I submit another form, for example the fontsize_form. The fontsize_form will be saved but then the togglesettings_form will be resetted:
Forms and models, if you want to see them:
https://pastebin.com/PhaFCdBP
I have read something like
if ...form in request.POST:
do this
But I dont know how to implement that in my view
Usually I name the submit button on the form something like "my-form"
Then you can just go:
if "my-form" in request.POST:
then do what you need to do
View example:
if 'load_doc' in request.POST:
file = request.FILES['document_file']
doc = documents(client=current_client,document_name=request.POST['document_name'],document_file=file)
doc.save()
html example:
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="panel-body">{{ single_load_form|crispy }}</div>
<div class="panel-footer"><button class="btn btn-primary" name="load_doc">Submit</button></form></div>
I made a model called Annoucement in my models.py file as well as the form for it in my forms.py file. I then made the simple create view for it in my my views.py and made it show on the frontend using the django-crispy-forms package but anytime i load the website, the border of the field appears red showing that there is an error. I have tried checking what the error could be but I am not getting any luck around it.
models.py
class Announcement_by_dean(models.Model):
student_id = models.ManyToManyField(add_students_by_manager)
message = models.TextField()
sent_date = models.DateField(default=datetime.now(), blank=True)
updated_date = models.DateField(auto_now=True, blank=True)
def __str__(self):
return "message sent on "+ str(self.sent_date)
forms.py
class Annoucement_form(ModelForm):
class Meta:
model = Announcement_by_dean
fields = ['student_id', 'message']
views.py
def dean_page(request):
annoucement_list = Announcement_by_dean.objects.all()
if request.method == 'POST':
form = Annoucement_form(request.POST)
if form.is_valid():
form.save()
messages.success(request, _("Message Sent Successfully!!!"))
return redirect('dean_page')
else:
messages.error(request, _("Message Not Sent, Something is Wrong!!!"))
else:
form = Annoucement_form()
messages.error(request, _("Invalid Method!!!"))
context = {"form":form, "annoucement_list":annoucement_list}
return render(request, "dean_page.html", context)
dean_page.html
<!-- Send Announcement -->
<div class="tab-pane fade show" id="nav-announcement" role="tabpanel" aria-labelledby="nav-announcement-tab">
<div class="container mt-4 p-3">
<form action="{% url 'dean_page' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form|crispy}}
<button type="submit" class="btn btn-success btn-sm">Submit</button>
</form>
</div>
</div>
I was able to solve the problem, I realised that the indentation of my context and return render was the issue.
views.py
def dean_page(request):
annoucement_list = Announcement_by_dean.objects.all().order_by('-id')
if request.method == 'POST':
form = Annoucement_form(request.POST)
if form.is_valid():
form.save()
messages.success(request, _("Message Sent Successfully!!!"))
return redirect('dean_page')
else:
messages.error(request, _("Message Not Sent, Something is Wrong!!!"))
else:
form = Annoucement_form()
context = {"annoucement_list":annoucement_list, "form":form}
return render(request, "dean_page.html", context)
to
def dean_page(request):
annoucement_list = Announcement_by_dean.objects.all().order_by('-id')
if request.method == 'POST':
form = Annoucement_form(request.POST)
if form.is_valid():
form.save()
messages.success(request, _("Message Sent Successfully!!!"))
return redirect('dean_page')
else:
messages.error(request, _("Message Not Sent, Something is Wrong!!!"))
else:
form = Annoucement_form()
context = {"annoucement_list":annoucement_list, "form":form}
return render(request, "dean_page.html", context)
I am having form which creates Ipd and Ipd model is created using patient model with one to many relationship, and I am already having one table with patient list in urls.
I am trying to create the list of all Ipd that are created using form, I am trying to redirect the form page to Idp list after I submit for Ipd form but ending with this error "NoReverseMatch at /1/ipd/",
One thing I want to clear is each Ipd is having unique id and Ipd is created from patient with one to many relationship which also have another unique id , the number which is in the error is patient id
views.py
#login_required
def ipd(request, patient_id):
object = get_object_or_404(Patient,pk=patient_id)
if request.method == "POST":
formtwo = IpdForm(request.POST)
if formtwo.is_valid() :
instance = formtwo.save(commit=False)
instance.save()
return HttpResponseRedirect(reverse('ipd_list', args=[patient_id]))
else:
return HttpResponse(formtwo.errors)
else:
formtwo = IpdForm()
return render(request, 'newipd.html', {'object':object, 'form2': formtwo})
#login_required
def ipd_list(request):
ipdlist = Ipd.objects.all()
return render(request, 'Ipdlist.html', {'ipd': ipdlist })
urls.py
re_path(r'^$', my_patient.index, name='home'), <-- patient list-->
re_path(r'^(?P<patient_id>\d+)/ipd/$', my_patient.ipd, name='ipd'),
path(r'^ipdlist/', my_patient.ipd_list,name='ipdlist' ),
Template
<ul>
<li>Indoor Patient Department</span></li>
</ul>
########
in ipdform
<form class="col s12" role="form" action="{% url 'ipd_list' 'patient_id' %}" method="post" enctype="multipart/form-data"> {% csrf_token %}
You have to remove args=[patiend_id] since you are returning to the ipd_list
return HttpResponseRedirect(reverse('ipd_list'))
You are trying to redirect user to ipdlist url instead with patameters. As this is a list method you shouldn't do that. You need to change:
#login_required
def ipd(request, patient_id):
object = get_object_or_404(Patient,pk=patient_id)
if request.method == "POST":
formtwo = IpdForm(request.POST)
if formtwo.is_valid() :
instance = formtwo.save(commit=False)
instance.save()
return HttpResponseRedirect(reverse('ipd_list'))
else:
return HttpResponse(formtwo.errors)
else:
formtwo = IpdForm()
return render(request, 'newipd.html', {'object':object, 'form2': formtwo})
#login_required
def ipd_list(request):
ipdlist = Ipd.objects.all()
return render(request, 'Ipdlist.html', {'ipd': ipdlist })
So the problem is that when i call the two methods authorSearch and deleteAuthor in views.py, form,is_valid() is always returning false.
models.py
class Author(models.Model):
author_name = models.CharField(max_length=200,primary_key=True)
def __str__(self):
return self.author_name
Forms.py
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ['author_name',]
views.py
def authorSearch(request):
if request.method=='POST':
form = AuthorForm(request.POST)
if form.is_valid():
#some processing here
return render(request,'authorSearch.html',{})
else:
return HttpResponse('No such Author Found!')
else:
form = AuthorForm()
return render(request,'authorSearch.html',{'form':form})
def deleteAuthor(request):
if request.method=='POST':
form=AuthorForm(request.POST)
if form.is_valid():
#some processing here
return HttpResponse('Author deleted successfully!')
else:
return HttpResponse('Author deletetion failed!')
else:
form=AuthorForm()
return render(request,'deleteAuthor.html',{'form':form})
authorSearch.html
<div class='container'>
{% if request.method == 'GET' %}
<form action='' method='POST'>
<!--Some html here -->
</form>
{% elif request.method == 'POST' %}
<!--Some html here -->
{% endif %}
A wild guess: you forgot the csrf token.
Simply print the actual data sent to the form and the errors to see what's happening !
def authorSearch(request):
if request.method=='POST':
form = AuthorForm(request.POST)
if form.is_valid():
#some processing here
return render(request,'authorSearch.html',{})
else:
# you want to check what's happening here
# something like this (from memory, might be wrong):
print request.POST
print form.errors
print form.non_field_errors
return HttpResponse('No such Author Found!')
else:
form = AuthorForm()
return render(request,'authorSearch.html',{'form':form})
Also, I'd personally recommend you to:
use Charles or something similar to check the HTTP requests and responses
write tests :)
I have a view called "search" which stores POST input as "search_id" but "search_id" is only available in the scope of the view "search". I want to be able to access the variable "search_id" in my view "dispTable".
Disclaimer- if this part of my question makes no sense, plz ignore: I understand that I could add an additional parameter to dispTable which would allow me to pass the search_id into dispTable in a return statement but what if I wanted to be able to access search_id in multiple views.
def search(request):
if request.method == 'POST' :
search_id = request.POST.get('textfield', None)
try:
return dispTable(request)
except Person.DoesNotExist:
return HttpResponse("no such user")
except Person.MultipleObjectsReturned :
#return dispTable(request, search_id)
return showResults(request)
else :
return render(request, 'People/search.html')
def dispTable(request) :
table = authTable(Person.objects.filter(MAIN_AUTHOR = 'search_id'))
RequestConfig(request).configure(table)
#return render(request, 'People/tableTemp.html', {'table':table})
return render(request, 'People/tableTemp.html', {"table" : Person.objects.filter(MAIN_AUTHOR = search_id)})
I also tried using a form, but I still did not know how to access the input variable in additional views, like dispTable
from django import forms
class SearchForm(forms.Form) :
search_id = forms.CharField(max_length=100)
def process(self) :
search_id = self.cleaned_data['search_id']
def search(request) :
if request.method == 'POST' :
form = SearchForm(request.POST)
if form.is_valid() :
form.process()
return dispTable(request)
else :
form = SearchForm()
return render (request, 'People/search.html')
And here is my html file:
<form method="POST" action="send/">
{% csrf_token %}
<input type="text" name="textfield">
<button type="submit">Upload text</button>
</form>