Django url multiple parameter - python

It have been from a week that I search without any answer to my problem. I don't know if I proceed in the good way, but I try to have an url that look like this : article/title/0/search=ad/2017-08-01/2017-08-09/; where the parameter are (in brace) : article/{filter}/{page}/search={search}/{date1}/{date2}/.
My url.py regex is:
url(r'article/(?P<filter>.+)/(?P<page>\d+)/(?:search=(?P<search>.*)/)?(?:(?P<date1>(\d{4}-\d{1,2}-\d{1,2})?)/)(?:(?P<date2>(\d{4}-\d{1,2}-\d{1,2})?)/)?$')
When the value search, date1 and date2 are fill, my url think that the {searched word}/2017-08-01/2017-08-09/ is the search value.
When search, date1 and date2 are empty, my link are like this: article/title/0/search=///. When the dates are filled article/title/0/search=/2017-08-01/2017-08-09/.
In my template, I need my url to be like this :{% url "view" filter page search date1 date2 %}
Can someone help me and correct me if i did it in the wrong way?
EDIT
I'll try to re-ask my problem in another ways:
In my template, in have a form which have 3 fields search, date1 and date2 not required, so they can be None (this is my problem). I have some links that need to change only one of the view parameters filter, page and keep the field param in the url.
When the form is POST to my view (which is actually like this def AllArticle(request, filter, page, search="", date1="", date2="")), I use them to filter my ArticleModel object (I don't need help for this, already done and work).
According to #Cory_Madden, I never use this method before and I don't know how to use it. I just tried it and django return me a MultiValueDictKeyError.

This is not how you use GET parameters. You need to access them from the request object. So let's say you have a function based view, this is how you would access any GET parameters appended to your URL:
def index(request, name='World'):
search_param = request.GET['search']
...
And your url in this case looks like this:
url(r'/(?P<name>.*)', views.index)
A request path in your address bar would then look like:
/Joe?search=search-term
And request.GET['search'] would return "search-term".

Related

Getting Field 'None' expected a number but got 'update'. when using UpdateView in Django

I am using UpdateView for my update page, but I get this error:
Field 'None' expected a number but got 'update'.
my urls.py looks like this:
path('post/<pk>/update/', PostUpdateView.as_view(), name='post_update'),
Everything works fine if I change my update URL to anything other than "post". For example, this works fine:
path('abcxyz/<pk>/update/', PostUpdateView.as_view(), name='post_update'),
I would like to use the word "post" in URL, because i also use it in the other URLs and they work just fine (except for delete view, which gives me the same error). Is there any way to fix this error without changing the URL?
Note: It has worked before, but it broke at some point when I was trying to use django-PWA. I'm not sure if this is related though.
Thank you for your help!
This is likely because you have another path like:
path('post/update/update/', PostUpdateView.as_view(), name='post_update'),
or something similar. It is possible that one or both update/s are URL parameters.
If you then for example visit post/update/update, and your PostUpdateView is defined first, the it will trigger the view with pk='update'.
If the primary key is simply a number, you can make use of the <int:…> path converter to prevent triggering the view when pk is something else than a sequence of digits:
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post_update'),
EDIT: Based on your comment, there was another view before this one with:
path('post/<year>/<month>/', FilteredPostListView.as_view(), name='filtered_post')
If one thus visits post/123/update, it will trigger the FilteredPostListView with 123 as year, and update as month, and hence it will raise an error.
You can put the path below that of the ProductUpdateListView, and you furthermore might want to use the <int:…> as well to only trigger the view when both parameters are sequences of digits:
path('post/<int:year>/<int:month>/', FilteredPostListView.as_view(), name='filtered_post')

Django: How To Pass Only Selected Arguments Through URL

I am trying to create a search page where buttons can be clicked which will filter the posts like in this page [Splice Sounds][2] (i think you need an account to view this so ill add screenshots).
To do this i think i need to pass a list so that i can filter by that list but i can't find a way to do this.
having a GET form for each genre (which is being created by a for loop) would allow me to filter by one genre at a time but i want to filter by multple genres at once so that won't work
in the site that i linked to: they pass the genres/tags into the url so how could i do this in django?
Also: i could make seperate url paths and link to those but then i would have to do this for every combination of genres/tags which would be too much so i can't do that.
the link shows a site which passes tags through url like this https://splice.com/sounds/search?sound_type=sample&tag=drums,kicks
here is some relevant code:
this is how i want to filter which is why i need to pass a list of args
for arg in args:
Posts = Posts.filter(genres=arg)
urls
urlpatterns = [
path('', views.find, name='find'),
path('searchgenres=<genres_selected>', views.find_search, name='find_search'),
]
EDIT: I have tried this many ways such as using ajax but i couldn't get that to work well
EDIT 2: i have changed the question to How To Pass Only Selected Arguments Through URL
To pass a list into a request you could:
Use html checkboxes and in views aggregate them into a list
Use a single textbox and parse in views
If you obtain the request as a list, you could use Post.objects.filter(genre__in=genres).
It might also be helpful to know that Django allows for complex lookups with Q objects from django.db.models import Q. The | character represents OR. This allows complex filtering. For instance:
Posts.objects.filter(Q(genre='Pop') | Q(genre='Rock') | Q(genre='Jazz'))

ı wanna post two id from .html to views

html file ı wanna take two id to views.py can ı get it ?
path('yorum_sil/<int:id>',views.yorum_sil,name="yorum_sil")
I want to do this code like the below
path('yorum_sil/<int:comment_id> and <int:post_id>',views.yorum_sil,name="yorum_sil")
That is possible, although you should not use spaces like that. You can for example use a slash like:
path('yorum_sil/<int:comment_id>/<int:post_id>',views.yorum_sil,name="yorum_sil")
Your view function (here yorum_sil) then of course needs to accept the two parameters, like:
# app/views.py
def yorum_sil(request, comment_id, post_id):
# ...
return ...
and if you perform a reverse lookup, you need to pass the two parameters. For example in a template like:
some_link
If I translated yorum sil correctly it means delete comments, note that typically GET requests should not have side effects. In order to delete/create/... an entity, you should use a POST request.

How to capture HTML5 data attribute when form is submitted to views.py of Django

As you can probably tell from the nature of my question, I'm a little new to this. I have read similar post on this subject matter but most of it went right past my head and I did not feel like it was 100% applicable to the circumstance that I was facing so I thought I'd ask the question in a simplified way.
The question:
let's say I'm running the below HTMl form and a user submits the form to my views.py as shown in the views section below, I would able to store the value of the user selection by using: car_selection = request.POST.get('car') .
My question is, how would I be able to capture the HTML5 data of " data-animal-type="spider" " ?
I know there are Gurus out there but please do not explode my head. I would really need simplified help.
Thanks for helping.
Example HTML Form:
<select name="carlist" >
option data-car-type="premium" name= "car" value="audi">Audi</option>
</select>
Example Django View Function
def getcar(request):
...
if request.method == 'POST'
...
selected_carn = request.POST.get('car')
Well, it actually is possible. Say your view looks like this:
def getcar(request):
...
if request.method == 'POST'
myform = MyForm(request.POST)
...
myform includes uncleaned form in html. The you can use BeautifulSoup to extract data. Something like this:
from bs4 import BeautifulSoup
test = BeautifulSoup(str(myform))
data-values = [item["data-car-type"] for item in test.find_all() if "data-car-type" in item.attrs]
This will extract values from data-car-type attributes.
That being said, this does seem like a bad design. I surely would never go to such length to get the "car type" data. It's probably written somewhere in your database. Get it from there.
I know this question is 4 year old but I came across this page when a similar question arose in my mind.
Short answer
It's not possible, unless your use Javascript on the front end side as a workaround. The accepted answer is false.
Explanation
Indeed, in the example above, try to print(request.POST) and you'll see that the QueryDict object request.POST received by the view does not contain any reference to the HTML5 data attribute you want to fetch. It's basically a kind of Python dictionary (with a few distinctive features, cf. documentation). Admittedly, if you print(myform) in the same example, you'll see some HTML code. But, this code is generated retroactively, when you associate data with the form. Thus, BeautifulSoup will never be able to find what you're looking for. From the Django documentation:
If the form is submitted using a POST request, the view will [...] create a form instance and populate it with data from the
request: form = NameForm(request.POST). This is called “binding data to
the form” (it is now a bound form).
Workaround
What I've done on my side and what I would suggest you to do is to use some Javascript on the client side to add the missing information to the form when it's submitted. For instance, it could look like this:
document.querySelector("#form_id").addEventListener("submit", function(e) {
const your_data_attribute = document.getElementById("XXX").dataset.yourInfo;
const another_hidden_field = document.getElementById("YYY");
another_hidden_field.value = your_data_attribute;
});

How can I use multiple variables(paramaters) in a url in django

I can get the filler variable from the URL below just fine.
url(r'^production/(?P<filler>\w{7})/$', views.Filler.as_view()),
In my view I can retrieve the filler as expected. However, if I try to do use a URL like the one below.
url(r'^production/(?P<filler>)\w{7}/(?P<day>).*/$', views.CasesByDay.as_view()),
Both variables (filler, day) are blank.
You need to include the entire parameter in parenthesis. It looks like you did that in your first example but not the second.
Try:
url(r'^production/(?P<filler>\w{7})/(?P<day>.*)/$', views.CasesByDay.as_view()),
See the official documentation for more information and examples: URL dispatcher

Categories

Resources