I am working on CS50 Web Development on the lesson of Django.
I want to pass a string from view.py to HTML as the URL link
here is the view.py
def randompage(request, name):
random_page = random.choice(util.list_entries())
return render(request, "encyclopedia/layout.html", {
"random_page": random_page})
and this is the HTML page
Random Page
the urls.py
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:name>", views.title, name= "title"),
path("wiki/", views.randompage, name= "randompage"),
path("searchresult", views.searchresult, name= "searchresult"),
path("newpage", views.newpage, name= "newpage")
]
the error code is
NoReverseMatch at /
Reverse for 'randompage' with arguments '('',)' not found. 1 pattern(s) tried: ['wiki/$']
I know I shall you templatetag URL, but I don't really understand how it works and I cant find anyone have a similar situation with me.
You can do this by using the following in your HTML template:
Random Page
title is the path name from your urls.py
randompage is the parameter
Here is the relevant section of the Django docs.
Related
I'm stuck with a st*pid question and problem.
I'm working with a form(html) on django, this form will be used to update information on my database regarding the page it's one.
So my problem is : django terminal tell me he receive the post correctly
app_1 | [10/Jan/2023 17:44:50] "GET /nb_database/49/ HTTP/1.1" 200 11810
app_1 | [10/Jan/2023 17:44:54] "POST /nb_database/49/ HTTP/1.1" 200 11810
However , i made a quick function to know my information from the form are coming to the function and here is the problem.
The function never print anything, i supposed the request never reach the function
Here is the function (located on the app named 'nb_database' :
def adding_address_to_db(request):
print("OK REQUETE RECEIVE")
the urls.py (on the same app):
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('nb_database', views.nb_database, name='nb_database'),
path('nb_database/<int:annonce_id>/', views.detail, name='detail'),
path('nb_database/<int:annonce_id>/', views.adding_address_to_db, name='adding_address_to_db'),
]
And here is the form in HTML , for this example let's say it's on page mysite.com/nb_database/49/
<form action="" method="post">
{% csrf_token %}
<input type="text" name="adding_address_to_db" placeholder="Entrez l'adresse" style="color: black;">
</form>
Basically i want to be able to answer the form on the generated page (mysite.com/nb_database/49/) and stay on it once answered.
Any help will be welcome !
Thank's everyone, enjoy your day
You have 2 identical paths in urls.py. When you access mysite.com/nb_database/49/, only the function from the first path runs, not the second.
Remove this line and your function should run:
path('nb_database/<int:annonce_id>/', views.detail, name='detail'),
OK so , i resolved my problem.
As said previously you can't have 2 urls pointing to 2 differents function on view.
I had to use the class Form provided by django.
Working with the post method and the form class i manage to add my function in the function who was generating the page and handle when a post method is send to catch the POST request and execute the code.
Here is a link to Django form documentation :
Django Documentation
And this is the kind of code i have to add to my rendering function :
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
I am trying to send data from my web page to urlpattern in Django and then to the view. I know that I can include a dict in my urlpattern path that will be sent to my view:
path("edit_page", views.edit_article, {'article':'fake_text'}, name="edit_page")
I want to send the dict directly from my webpage. I have been trying:
urls.py
path("edit_page", views.edit_article, name="edit_page")
html
<a href='{% url 'edit_page' {'article': 'article_test'} %}'>Edit</a>
Where am I going wrong?
You typically encode the data in the URL, for example with:
path('edit_page/<str:article>/', views.edit_article, name='edit_page'),
then you define the view as:
def edit_article(request, article):
# …
then the view will be called with the article part of the URL path.
In the template you can then "calculate" the URL with:
Edit
I'm in the process of creating a small poll app with Django and the main page has a button that allows the user to create new polls and another one that allows them to delete polls.
My delete route should send the user to a confirmation page that would be located at /polls/:id/delete. When I type it in the URL it works but when I try to access the confirmation page via button click it sends me to the wrong URL.
I've tried changing information in the deletePoll class and in the Path but neither work.
Any idea what I'm doing wrong?
#this is my form on the page:
<form action="{% url 'polls:delete' pk=question.id %}"method="GET">
{% csrf_token %}
<input class="btn btn-default btn-danger" type="submit"value="Delete"/>
</form>
#this is my class inside of views.py
class PollDelete(DeleteView):
template_name = 'polls/delete.html'
# can specify success url
# url to redirect after sucessfully
# deleting object
def get_object(request):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/delete.html')
#this is my polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
# ex: /polls/
path('', views.IndexView.as_view(), name='index'),
# ex: /polls/5/
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
# ex: /polls/5/results/
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
#path for delete
#Tried changing the format to /polls/delete/PK but it didn't work
path('<int:pk>/delete/', views.PollDelete.as_view(), name='delete'),
# path('createpoll/', views.createPoll, name='createPoll')
]
path('delete/<int:pk>', views.PollDelete.as_view(), name='delete')
paste this code to your urls.py. the action in your html recognizes delete/pk, you are throwing pk/delete/ to your url which does not return the proper url.
I have a project "something". In something/shop/templates/shop I have HTML files.
I want to have a link between 'main' and 'about' html files, but I do not know how. I tried to do it as in usual HTML file, but it is not working.
About
Also I tried this way, but it is not working too.
About
It is in urls.py:
urlpatterns = [
path('', views.main, name='main'),
path('about/', views.about, name='about'),]
views.py:
def main(request):
return render(request, 'shop/main.html')
def about(request):
return render(request, 'shop/about.html')
What should I write to get a normal link between them?
I want to execute my python code by onclick. I am getting result after running the server. My button is not working. Here is my code.
URL -
url(r'^index/$', index),
index.html-
<html>
<body>
<form action="/index/" method="GET">
<input type="submit" value="Click">
</form>
{{output}}
</body>
</html>
views.py -
from django.shortcuts import render, render_to_response
from pythoncode import mycode
def index(request):
if request.method=="GET":
py_obj=mycode.test_code(10)
py_obj.code()
return render(request, 'index.html', {"output":py_obj.a})
I created one more application to separate python code -
application name is python code and file name mycode
class test_code:
def __init__(self, a):
self.a=a
self.b=4
def code(self):
return self.a, self.b
please help me. I am new in Django. Thanks in advance
If you just want to click and display something on the fly on your page, you'll need JavaScript and AJAX. There is no need to create whole form just for one button. Remove your form completely, which closing tag is also wrong (read Brandon's comments).
You can use this snippet in your index.html:
<button id="myClickButton" type="button">Click</button>
<div id="myOutput"></div>
Now let's trigger something when clicking on the button:
$("#myClickButton").click(function() {
$.get("/output/", function(data) {
$("#myOutput").html(data);
}, "html");
});
The above code is jQuery. Please read the official documentation of jQuery. There is everything explained how to use the library.
Now let's go to your views.py.
def index(request):
return render(request, 'yourapp/index.html')
Remember to put your templates in a folder templates within your app. It should look like this:
--yourproject
|
|--yourapp
|----templates
|------yourapp
|--------index.html
Make another view in your views.py:
def output(request):
if request.is_ajax():
py_obj = mycode.test_code(10)
return render(request, 'yourapp/output.html', {'output': py_obj.a})
Your output.html can be like this:
<p>{{ output }}</p>
That's all. No header, no body, nothing. This code will be inserted per AJAX on the fly in index.html.
Now let's analyze your method code:
def code(self):
return self.a, self.b
Do you know what happens here? You can return only ONE value in a function. You think you're returning a and b as integers. Wrong! This method returns a tuple with two elements. This method will return (10, 4).
When you call this method in your index view it just returns this tuple, but you're not assigning it to a variable, so it will go with the wind. It's useless call.
I hope this gives you an idea how you can do it. If you don't want to use JavaScript (and AJAX) you can send your form per POST and make a distinction in your view:
def index(request):
if request.method == 'GET':
return render(request, 'yourapp/index.html', {'output': ''})
elif request.method == 'POST':
py_obj = mycode.test_code(10)
return render(request, 'yourapp/output.html', {'output': py_obj.a})
In this case you won't need the view output and output.html. You can use your index.html with the form inside.