I can't find any solution on any article so I'm asking here.
I'd like to make button which is gonna redirect user to specific url.
I have already did it this way:
<button onclick="location.href='create_recipe/'" type="button" >Create new Recipe</button>
but instead of passing whole link I'd like to use {% url 'some_view' %} but I do not have an idea how I should do that.
Is it even possible to do that ?
It has to be <button>,
edit:
something like:
<button type="button" class="btn btn-outline-secondary">Create new Recipe</button>
also does not work
You can do this by adding this to the button:
onclick="goToSomeView()"
And then add this in script tag of html file:
<script type="text/javascript">
function goToSomeView(){
document.location.href = "{% url 'some_view' %}"
}
</script>
index is your function which exist views.py file.
from django.urls import path
from . import views
path('',views.index, name='index'),
HTML:
<a class="btn btn-outline-secondary" href="{% url 'index' %}">Create new Recipe</a>
As I see you're using bootstrap already, so the easiest way is to use the a element with the type="button" attribute.
Create new recipe
Below you can see that the result is the same, but for button you need to bind the onclick function. In this case I pointed to #nigel239 answer.
function goToSomeView(){
document.location.href = "{% url 'index' %}"
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<p class="lead">Using 'a' element</p>
Create new recipe
<p class="lead mt-3">Using button</p>
<button onclick="goToSomeView()" class="btn btn-outline-secondary">Create new recipe</button>
Related
I am attempting to create a view that allows users to delete a build log. On the view that shows the delete button with a link to the delete page I am getting the error
Reverse for 'build-log-delete' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/build\\-log/(?P<pkz>[0-9]+)/delete$']
If I understand this error correctly its because I am not passing paramaters in the url.
<a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a>
However I do not understand why I need to pass parameters in the URL as I am not passing any new values into the URL and if so what parameters I would pass. Do I have to re pass the previous two?
urls
path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'),
path('post/<int:pk>/build-log/<int:pkz>/delete', views.BuildLogDelete, name='build-log-delete') #error
views
def BuildLogDisplay(request, pk, pkz ):
post = BuildLog.objects.filter(post_id=pk)
log = BuildLog.objects.get(pk=pkz)
context = {
'post':post, 'log':log
}
return render(request, 'blog/buildlog.html', context)
def BuildLogDelete(request):
context = { }
return render(request, 'blog/BuildLogDelete.html', context)
full template
<div class="row">
<article class="cars-article">
<div class="flex">
<img class="rounded-circle article-img" src="{{ log.author.profile.image.url }}" />
<div>
<a class="article-title">{{ log.title }}</a>
</div>
</div>
<br>
<div>
{% if log.author == user %}
<a class="update-btn" href=""> Update</a>
<a class="delete-btn" href="{% url 'build-log-delete' %}">Delete</a>
{% endif %}
</div>
<hr class="solid">
<p class="article-content">{{ log.content | safe}}</p>
</article>
</div>
There are multiple errors in you code. You are not passing args in BuildLogDelete view but in url you are using those arguments. So the correct view should look like this.
def BuildLogDelete(request,pk,pkz):
# delete code
# write here
Next mistake which i can see is you are assigning queryset rather than object for the post key in BuildLogDisplay view. You should assign object.
post = BuildLog.objects.get(post_id=pk)
Lastly your original error mentioned in the question is because your build-log-delete url expects two arguments i.e pk and pkz but you haven't passed them in template. So it should be like this.
<a class="delete-btn" href='{% url "build-log-delete" pk=post.post_id pkz=log.pk %}'>Delete</a>
I would highly suggest you to look for already given generic views like ListView, TemplateView, CreateView, UpdateView and DeleteView. This will prevent you from reinventing the wheel
Ref: Django Class Based Generic Views
I'm new to Django, I'm trying to get a button on the homepage to link to another (as of right now) static page.
I thought this was pretty simple, I've done frontend work before and a simple href to the file would be enough but for some reason its not linking.
<h1> This is the homepage yay!</h1>
<div class="container">
Judges
<button type="button" class="btn btn-2">Students</button>
</div>
If I understood the question well, you would have to create a view and put its url in the template.
def scoring_sheet(request):
return render(request, 'scoringsheet.html', {})
And register in your url:
path('yourapp/scoring_sheet', views.scoring_sheet, name='scoring-sheet'),
and add in html;
<h1> This is the homepage yay!</h1>
<div class="container">
Judges
<button type="button" class="btn btn-2">Students</button>
</div>
I am trying to make a calendar html page, that has a dropdown button to select the different months. How to get to this calendar page is via the nav bar that is created at base.html
base.html - how to get to the calendar page.
....
....
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" data-target="scheduler_dropdown" href="#"><i class="fas fa-calendar"></i>Scheduler</a>
<div class="dropdown-menu" aria-labelledby="scheduler_dropdown">
<a class="dropdown-item" href="{% url 'view_schedule' %}"><i class="fas fa-calendar-alt"></i>View Schedule</a>
</div>
</li>
what i've build so far:
urls.py
urlpatterns = [
path('schedule/view-schedule/', views.view_schedule, name='view_schedule'),
path('schedule/view-schedule/?query=month<str:selected_month>', views.view_schedule,
name='view_schedule_selected_month'),
]
Views.py
def view_schedule(request, selected_month=None):
if request.method == 'POST':
print('post')
else:
current_month = date.today().month
current_year = date.today().year
# a = request.GET # How to get query set from dropdown menu???
# print(a)
args = {
'month_cal': monthcalendar(current_year, current_month),
'month_name': calendar.month_name[current_month],
'year_name': current_year,
}
return render(request, 'static/html/view_schedule.html', args)
view_schedule.html
<div class="card-header">
Schedule for {{ month_name }} {{ year_name }}
<form class="date-selector" method="post">
{% csrf_token %}
<div class="dropdown">
<button class="btn dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="far fa-caret-square-down"></i>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href={% url 'view_schedule_selected_month' selected_month=1 %}>Jan</a>
<a class="dropdown-item" href={% url 'view_schedule_selected_month' selected_month=2 %}>Feb</a>
<a class="dropdown-item" href={% url 'view_schedule_selected_month' selected_month=3 %}>Mar</a>
</div>
</div>
</form>
</div>
My problem is that, when I click on the drop down button and select the relevant month Jan, Feb, Mar, the url changes, but in my views.py, the query set doesn't appear. So I can't extract the query for processing.
Any thoughts?
Turns out I could have just done print(selected_month) and it would print the query result.. I got the idea when I was watching this video: https://www.youtube.com/watch?v=qmxoGYCFruM
Don't use urlpatterns to handle query strings. urlpatterns handles only the URL itself; query parameters are part of the GET data and are handled within the callback method. You'll need to change the way your HTML, urlpatterns, and the view work to accommodate this.
urlpatterns = [
path('schedule/view-schedule/', views.view_schedule, name='view_schedule'),
]
In your HTML, you'll want a form with a dropdown that GETs the data to the URL above. You can use the select tag for this.
And then in the view, you can extract GET data from request.GET. Specifically, if you used the select tag as suggested above, then the user's choice will be in request.GET[NAME] where NAME is the name of the select tag.
There are other ways to go about this, depending on aesthetic preferences, etc., but the method I've explained above is likely to be the easiest.
Also, query set (or QuerySet) has a very specific meaning in Django. It refers to a type of object used in database queries as explained here. The results of an HTML form are not "query sets."
I have a question on how to call a view function from a template HTML button? Like an onclick function?
Here is the template:
<input id="submit" type="button" onclick="xxx" method="post" value="Click" />
And the views.py is:
def request_page(request):
...do something...
return render_to_response("/directory.html", {})
Thank you very much.
Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.
inside templateHTML.html:
<form action="#" method="get">
<input type="text" value="8" name="mytextbox" size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
inside view.py:
import mypythoncode
def request_page(request):
if(request.GET.get('mybtn')):
mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')
One option is, you can wrap the submit button with a form
Something like this:
<form action="{% url path.to.request_page %}" method="POST">
<input id="submit" type="button" value="Click" />
</form>
(remove the onclick and method)
If you want to load a specific part of the page, without page reload - you can do
<input id="submit" type="button" value="Click" data_url/>
and on a submit listener
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
success: function(data){ $('#target').html(data) }
});
});
});
How about this:
<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>
The class is including bootstrap styles for primary button.
you can put the input inside a form like this:-
<script>
$(document).ready(function(){
$(document).on('click','#send', function(){
$('#hid').val(data)
document.forms["myForm"].submit();
})
})
</script>
<form id="myForm" action="/request_page url/" method="post">
<input type="hidden" id="hid" name="hid"/>
</form>
<div id="send">Send Data</div>
For deleting all data:
HTML FILE
class="btn btn-primary" href="{% url 'delete_product'%}">Delete
Put the above code in an anchor tag. (the a tag!)
url.py
path('delete_product', views.delete_product, name='delete_product')]
views.py
def delete_product(request):
if request.method == "GET":
dest = Racket.objects.all()
dest.delete()
return render(request, "admin_page.html")
For example, a logout button can be written like this:
<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>
Where logout endpoint:
#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
I want to pass userid from django url to my view
Here is what I have written in Django template
<a href ={% url 'user_details' x.id %} class='btn btn-primary' style="float: right;" >Know More</a></div>
To handle this url I have written Url like
url(r'^User/(\d{userid})/$', 'search.views.user_detail',name='user_details'),
But I am getting an error i.e
NoReverseMatch at /search/
Reverse for ''user_details'' with arguments '(2L,)' and keyword arguments '{}' not found.
Please help me out What might I am doing wrong here .
No quote ''
<a href ={% url user_details x.id %} class='btn btn-primary' style="float: right;" >
Know More
</a>
Another your url
url(r'^User/(?P<userid>\d+)/$', 'search.views.user_detail', name='user_details'),
Be carefull, after Django 1.5, use must use quotes. I came across this solution and tried it, got an error. I'm using Django 1.6 and you need the quotes:
<a href ={% url 'user_details' x.id %} class='btn btn-primary' style="float: right;" >
Know More
</a>
hope it helps.