I would like to have both a contact form, a newsletter form and a photo slider/portofolio in index.html. Everything drawn into this page only.
Am I correct to assume it has something to do With "URL dispatcher" in the documentation? And could someone please help me with some examples on how to point everything to the same URL?
Want everything to redirect back to the index when done, after email has been sent, after registering for newsletter and so on. Just to explain better what I actually mean here as I don't have the knowledge to do it in correct terminology.
Thanks in advance for all the help I can get.
As a possible solution you can create index page with multiple forms. Each form will redirect on post to it own view, for example:
First form:
<form action="{% url 'myapp:index_one' %}" enctype="multipart/form-data" method="post">
Second form:
<form action="{% url 'myapp:index_two' %}" enctype="multipart/form-data" method="post">
In each view you create all the forms and pass them to index.html
def index_one():
indexForm1 = index_form1()
indexForm2 = index_form2()
if request.POST:
indexForm = index_form1(request.POST, request.FILES)
//process first form here
//load index.html and pass context with forms
In second view you do the same but on POST you process another form:
def index_two():
indexForm1 = index_form1()
indexForm2 = index_form2()
if request.POST:
indexForm2 = index_form2(request.POST, request.FILES)
//process second form here
//load index.html and pass context with forms
I have such solution in production and it is working fine.
Related
my code is simple but I admit I have taken it from the internet.
I want to update a model with a button click. Which model, it is chosen by the variable. So I have this html code:
<form action="{% url 'reception:update_status' slug=name %}" method="POST">
{% csrf_token %}
<input type="submit" value="has arrived">
</form>
This code is in url.py
re_path('update_status/(?P<slug>[-a-zA-Z0-9_]+)$', views.update_status, name='update_status'),
and in views.py
def update_status(request, slug):
if request.method == 'POST':
p = MyModel.objects.filter(name=slug)
p.status = 'is waiting'
p.update()
return redirect(request, 'home')
Now with the code like this it comes back with the following error when I click on the button!
Reverse for '<WSGIRequest: POST '/update_status/Name10'>' not found. '<WSGIRequest: POST '/update_status/Name10'>' is not a valid view function or pattern name.
and I have no clue what this means. Please help?
Thanks
For regex patterns in Django 2.0, you need to use re_path, instead of path for your url.
I solved this problem with pk rather than slugs.
I would recommend everyone who is new to Django to create an id field for every Model. Because that can then be used to pass parameters very easy. Slug is more complicated and makes life unnecessarily difficult!
I am trying to make a button redirect the user to a new url after they submit a form. This is how it is right now, and it works properly and all the data gets sent to the django database.
<form method='POST' action='' class="col-md-6 col-md-offset-7" style="background-color: lightgreen; border-radius: 10px">
However, when I change the action to
action="{% url 'ridesharing:request-success' %}",
the redirect works, but the data does not go to my django database.
What is going on here?
You seem to have some confusion here. The action of the form is where the browser will send the data. Obviously, if you don't point that at the view which actually processes the data, then it won't be saved.
To redirect after a post, your view should return a redirect.
When you declare a form with an empty action attribute:
<form method='POST' action=''>
the POST data will be sent to the same URL. This is useful because if there is some error in the form, it's easy to re-display it with all fields filled with values entered by the user. Then, when the form becomes valid, a redirect is done to the confirmation page.
When you declare your form that way:
<form method='POST' action='{% url 'ridesharing:request-success' %}'>
The data entered by the user in the form will be sent to the view request-success. But this view probably only render the template of the confirmation page. If you want to correctly handle data from the form, you have to set action attribute of your <form> to the same view, or easier, keep it empty.
I do not understand why Daniel Roseman's post isnt accepted as the answer. It helped me when I wanted to redirect a create form to its update form.
Basically in the view of the app I defined the get_success_url to reverse_lazy to the data-update.
def get_success_url(self):
return reverse_lazy('app_name:data-update')
Just replace the 'app_name:data-update' with the appropriate url.
When I submit the form (eg: below), url gets redirected to localhost:8000/test/result/, and I get some result. This step works fine.
However, when I click on browser back button to go back to the initial form, Firefox doesn't load the form, although url has changed to localhost:8000/test/. I get a blank page. Also, if I click the back button again, it takes me to localhost:8000 page. Chrome and IE works though.
What am I doing wrong and how can I fix this FF issue?
Many thanks in advance.
#---test.html---
<form id="input-form" action="{% url test.views.main_view %}" method="post" enctype="multipart/form-data">{% csrf_token %}
...
</form>
#---views.py---
class MainView(FormView):
template_name = 'test.html'
form_class = UserInputForm
success_url = 'result/'
def form_valid(self, form):
...
#---urls.py---
urlpatterns = patterns('test.views',
url(r'^$', view='main_view', name='main-view'),
url(r'^result/$', view='result_view', name='result-view'),
)
I have a feeling this is the issue. Failing that, something that will definitely work is setting your Cache-Control header to “no-cache, must-revalidate, no-store” – but that's a nasty brute force solution.
I have a Django view which corresponds to a URL like this:
<my_site>/project_info/?pitched=true
I validate the form for this page the normal way:
form = ProjectInfoForm(request.POST or None)
if form.is_valid():
# handle form
...
But when the form is returned with errors it ends up at the same page without the URL (obviously):
<my_site>/project_info/
I don't really want to changed the pitched=true parameter to a captured URL parameter. What is the best way to redirect, considering I can't know if the page had this GET variable or not?
What does the HTML in your template look like? Try setting the action attribute on your form to "" (it should preserve your variables), like this:
<form action="" method="post">
The action="" trick works. If you want to be sure, you can do something like
<form action="{% if request.GET.pitched %}?pitched={{ request.GET.pitched }}{% endif %}" method="post">
I have a form on my website, that creates an entry in database. So every time when I refresh a page I got this message first:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be repeated.
Do you want to continue?
Obviously I don't want have the same information more than once in my database.
just in case: this is my code (I know there is a lot of crap that needs to be deleted):
#views.py
#login_required
def subject(request,username, subject_name):
subject_id = Subjects.objects.filter(user = request.user).get(name=subject_name)
#Upload form
if request.method == "POST":
if "upload-b" in request.POST:
form = ContentForm(request.POST, request.FILES, instance=subject_id)
if form.is_valid(): # need to add some clean functions
up_f = FileDescription.objects.get_or_create(subject=subject_id,
subject_name=subject_name,
file_type=request.POST['file_type'],
file_uploaded_by = username,
file_name=request.POST['file_name'],
file_description=request.POST['file_description'],
image = request.FILES['image'],
)
form = ContentForm()
#Show uploaded files with respect to clicked session (Homework, Class , Random ... )
homework_files = Homework.homework.filter(subject_name__exact=subject_name,
file_uploaded_by__exact=username)
class_files = ClassPapers.classpapers.filter(subject_name__exact=subject_name)
random_files = RandomPapers.randompapers.filter(subject_name__exact=subject_name,
file_uploaded_by__exact=username)
return render_to_response('subject_content.html', {'form':form,
'subject_name': subject_name,
'class_files': class_files,
'homework_files': homework_files,
'class_files': class_files,
'random_files': random_files,
},
context_instance=RequestContext(request))
#forms.py:
class ContentForm(forms.ModelForm):
file_name =forms.CharField(max_length=255, widget=forms.TextInput(attrs={'size':20}))
file_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':25}))
class Meta:
model = FileDescription
exclude = ('subject', 'subject_name', 'file_uploaded_by')
#template
<div id="sbj-creation-frm">
<h3>Upload File</h3>
<form action="." method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" name="upload-b" class="btn-create" />
</form>
</div>
This message is from the browser; and it will display anytime you try to refresh a page that was displayed as the result of a POST request.
It has no bearing on your code, the browser will display the same message on all websites where you try to refresh the page (hit F5 for example) which was displayed as a result of a previous POST request.
To prevent this from happening, make sure all POST requests redirect to a different view upon completion; and not render templates themselves.
redirect to same page working for me :
header("Location: #");
Just redirect your page to current page after inserting
, it will clear all the values and avoid adding the Duplicate records !
example:
protected void btnAdd_Click(object sender, EventArgs e)
{
//your code
Response.Redirect("Currentpage.aspx",true);
//or
Response.Redirect(Request.Url.AbsoluteUri);
}