I have my URL defined as follows:
(r'^article/edit/(.*)/$', 'mysite.views.edit_article')
And the function defined as:
def edit_article(request, article_id):
However, it seems that any request to this page results in the wrong value being passed in for article_id. If I redefine my URL as
(r'^article/(.*)/$', 'mysite.views.edit_article')
Minus the "edit/" it seems to work. Any suggestions on how to fix this?
Try this:
url (r'^article/edit/(?P<article_id>\d+)$', 'mysite.views.edit_article'),
Take a look at the Named Groups in the Django documentation
Related
I an trying to make url router in Django which supports following URLs :
http://localhost:8000/location/configuration
http://localhost:8000/location/d3d710fcfc1391b0a8182239881b8bf7/configuration
url(r'^locations/configuration$',
location_config.as_view(), name="location-config"),
url(r'^locations/(?P<location_key>[\w]+)/configuration$',
location_config.as_view(), name="location-config-uri")
Whenever I tried to hit http://localhost:8000/location/configuration, it picked up the second URL routing format instead of picking up first one.
Error:
TypeError at /locations/configuration/ get() missing 1 required
positional argument: 'location_key'
Can anyone help me here what goes wrong with the url routing format?
Nope, it does pick the first pattern which has no arguments, however you're using the same view in both patterns and location_config view has required argument location_key which is not provided when first pattern matches the URL. That's what error message is saying.
So write another view which will not require location_key argument or alter this view definition: add default to the parameter
def location_config(request, location_key=None):
....
now it is not a "required positional argument".
django Will look for a pk when you are using a detail view by default. you have to override it by using get_object()
in your case
def get_object(self, queryset=None):
location_key = self.kwargs.get('location_key')
obj = Model.objects.get(id=location_key)
return obj
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.
For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"
My url pattern for this is:
url(r'^<slug:url>', views.item, name='products')
with the view:
def item(request, url=""):
products = product.objects.get(url=url)
return render(request, 'shop\product.html', {'products', products})
As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?
If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.
Also I'm on django 1.11.7 for this project.
The url pattern you are trying to use (slug:url) is only valid in Django 2.
If you are on Django 1.11 then you need to use a regular expression - something like this:
url(r'^?P<url>[\w-]+', views.item, name='products')
Always make sure you're looking at the documentation for your version of Django ;-).
Please change url pattern to:
url(r'^?P<url>[\w-]+', views.item, name='products')
I want to redirect URL without slug, to the one with slug, at the urls.py level.
My endpoints looks as follows:
(r'/invoices/<:(-?\d+)>/print/', PrintHandler, 'ShortPrintHandler')
(r'/invoices/<:(-?\d+)>/<:([\w-]*)>/print/', PrintHandler, 'FullPrintHandler')
Is there any way I can pass first, decimal, argument from short URL to the long one, on redirect? Generating URLs without slug is already covered at handler level.
Tried to handle it with
RedirectRoute(r'/invoices/<:(-?\d+)>/print/', PrintHandler, redirect_to_name='FullPrintHandler')
But an error was thrown:
KeyError: 'Missing argument "1" to build URI.'
You can't do that with just a RedirectRoute; you need to get the slug value from somewhere.
You'll need to write a standard route, and in the handler you should get the object from the datastore and return a redirect to the full path using the slug.
Something like (untested):
class RedirectToFullPath(webapp2.RequestHandler):
def get(self, invoice_id):
invoice = Invoice.get_by_id(invoice_id)
self.redirect_to('FullPrintHandler', invoice_id, invoice.slug)
I'm having issues getting the following code (below) to work (there are no errors) . In my template I'm outputting item.get_settings_url but I get nothing. What I'm I doing wrong here?
In my models I have the following model method:
def get_settings_url(self):
return reverse('sms.views.keyword_settings', args=[str(self.keyword)])
urls:
url(r'^keyword/^(?P<keyword>[\.\w-]+)/settings/$', views.keyword_settings, name='keyword_settings')
view:
def keyword_settings(request, keyword):
return render_to_response('keyword_settings.html', context_instance=RequestContext(request))
Your URL contains a named parameter. Hence, you need to pass that name when calling reverse. Also, you should use the name of the URL to make the reverse lookup short and easier to maintain:
return reverse('keyword_settings', kwargs={'keyword': str(self.keyword)})
I am making a stock application, where, after a user types in a stock such as MSFT, they are redirected to .../stock?s=MSFT I have successfully made this part, but now I need Python to grab this current, unique URL so that I can parse the quote (in this case, the MSFT) out if it and save it as a new variable.
The easiest way I can think of is just to get the current URL, although I cannot seem to find a way to do this; using self.request... but this returned the error:
NameError: global name 'self' is not defined
The other ideas I came across was to use a form of urllib as it contains a specific .request_qs() method, although this requires me to pass the URL as a parameter, which should be unique every time because of the change in stock.
Here is the Python I currently have:
#app.route('/', methods=['GET', 'POST'])
def home_search():
if request.method == 'POST':
st = request.form['s']
return redirect(url_for('stock')+'?s='+st)
return render_template('stk.html')
#app.route('/stock', methods=['GET', 'POST'])
def stock():
#here I need to save the variable 'name' as the current URL. I can parse it later.
url="http://finance.yahoo.com/d/quotes.csv?s="+name"&f=snl1"
text=urllib2.urlopen(url).read()
return render_template('stock.html')
Many thanks in advance.
It's request (imported from the flask package), not self.request
The Flask docs have, as always, thorough documentation about variables in the URL: http://flask.pocoo.org/docs/quickstart/#variable-rules
#app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
On that occasion, you should read the whole Quickstart from the Flask docs: http://flask.pocoo.org/docs/quickstart/
You haven't posted any info on where the error occurs :) And I can't see where you're trying to access self.requests.
Looking at other Flask apps, it seems you should just access request instead.
Take a look at these examples: https://github.com/mitsuhiko/flask/tree/master/examples