ı wanna post two id from .html to views - python

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.

Related

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'))

QueryString in Django

I need one small help. I have one django application already with me and everything is working fine. Now requirement is without making change in existing functions we want to pass urls parameter as a query string
path('my-app/', include('myapp.urls', namespace='myapp')),
# I added this line because I want to use dcid as a querystring
url(r'^my-app/(?:(?P<dcid>\w+)/)',include('myapp.urls', namespace='myapp')),
and my function is already written like this
def orders_b2b_open_list_pageable(request):
We don't want to change in above functions but we want dcid in query string. How can we achieve that
I am doing this but when requesting like this
http://localhost:8002/my-app/1/orders/b2b/open/pageable/
I am getting following error
Thank You in advance
There's no need to parse it in your urls.py, that would change your function signiture.
You can handle it in your view, by pulling the querystring value from the request:
def orders_b2b_open_list_pageable(request):
dcid = request.GET.get('dcid', None)
...

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;
});

Django url multiple parameter

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".

Django: Arbitrary number of unnamed urls.py parameters

I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:
/browse/<name1>/<value1>/<name2>/<value2>/ .... etc ....
where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.
Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.
Ideally each name/value pair will be passed to the view function as a parameter named name1, name2, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?
So, it seems I need to do something like this:
urlpatterns = patterns('',
url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"),
)
It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:
urlpatterns = patterns('',
url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"),
)
... and got the same problem, but this time *args only includes the last matched pattern.
Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?
A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:
urlpatterns = patterns('',
url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'),
)
def view(request, match):
pieces = match.split('/')
# even indexed pieces are the names, odd are values
...
No promises about the regexp I used, but I think you understand what I mean.
(Edited to try and fix the regexp.)
I agree with Adam, but I think the pattern in urls.py should be:
... r'^browse/(?P<match>.+)/$' ...
The '\w' will only match 'word' characters, but the '.' will match anything.
I've an alternative solution, which isn't quite different from the previous but it's more refined:
url(r'^my_app/(((list\/)((\w{1,})\/(\w{1,})\/(\w{1,3})\/){1,10})+)$'
I've used unnamed url parameters and a repetitive regexp. Not to get the "is not a valid regular expression: multiple repeat" i place a word at the beginning of the list.
I'm still working at the view receiving the list. But i think ill' go through the args or kwargs.. Cannot still say it exactly.
My 2 cents
Same answer came to me while reading the question.
I believe model_browse view is the best way to sort the query parameters and use it as a generic router.
I think the answer of Adam is more generic than my solution, but if you like to use a fixed number of arguments in the url, you could also do something like this:
The following example shows how to get all sales of a day for a location by entering the name of the store and the year, month and day.
urls.py:
urlpatterns = patterns('',
url(r'^baseurl/location/(?P<store>.+)/sales/(?P<year>[0-9][0-9][0-9][0-9])-(?P<month>[0-9][0-9])-(?P<day>[0-9][0-9])/$', views.DailySalesAtLocationListAPIView.as_view(), name='daily-sales-at-location'),
)
Alternativly, you could also use the id of the store by changing (?P<store>.+) to (?P<store>[0-9]+). Note that location and sales are no keywords, they just improve readability of the url.
views.py
class DailySalesAtLocationListAPIView(generics.ListAPIView):
def get(self, request, store, year, month, day):
# here you can start using the values from the url
print store
print year
print month
print date
# now start filtering your model
Hope it helps anybody!
Best regards,
Michael

Categories

Resources