I'm relatively new to python/django. I'm having an issue with sending to IDs through my urls.py.
I am trying to add an admin to a business profile page in my project.
My views.py:
#login_required
def make_admin(request, bus_id, user_id):
user = request.user
u = get_object_or_404(User, pk = user_id)
b = get_object_or_404(Business, pk = bus_id)
b.admin.add(u)
followcount = b.followers.count()
photo = BusinessLogo.objects.all().filter(business_link = bus_id)[:1]
return render_to_response('business/followers.html',
{'user':user, 'b':b, 'followcount':followcount, 'photo':photo, 'u':u}, context_instance=RequestContext(request))
In my template I am trying to pass the bus_id as well as the user_id but I keep getting a syntax error, which I am assuming is related to my urls.
My template:
...
{% if follow in b.admin.all %}
[Remove Admin]
{% else %}
[Make Admin]
{% endif %}
...
My urls.py at the moment:
url(r"^make/(?P<bus_id>\d+)/(?P<user_id>\d+)/$", make_admin, name="make_admin"),
url(r"^remove/(?P<bus_id>\d+)/(?P<user_id>\d+)/$", remove_admin, name="remove_admin"),
I am just having a hard time figuring out how to add the user_id to my urls. The above example does not work.
Thanks everyone,
Steve
EDIT: The error Im presented with is:
Caught NoReverseMatch while rendering: Reverse for 'remove_admin' with arguments '(1L, '')' and keyword arguments '{}' not found.
The only thing i can see that seems wrong is {% if follow in b.admin.all %} there's no follow variable in your context in the code you posted.
If you posted more details of your error, or the stack trace, it would be most helpful.
EDIT: Ok, your error is helpful :)
Caught NoReverseMatch while rendering: Reverse for 'remove_admin' with arguments '(1L, '')' and keyword arguments '{}' not found.
This means that the url reversal function got two arguments 1L and ''.
1L i just the integer 1 as a python long integer, the '' means that you passed in None or a blank string.
Since you called the url reversal in your template with {% url remove_admin b.id u.id %} the second argument is the value of u.id. Check the value of the u variable, it seems to not have a valid id attribute, so it's probably not what you expect (I'd guess it's not a User object at all)
You're not referencing the user object in the way you pass it to the context - you pass it as user, but in the template you use u.id.
Related
I am having trouble with passing arguments to a Flask route from a Form. I am new to Flask so my apologies if this is something simple. I have been re-doing and re-coding things all morning but to no avail. I am trying to return an HTML page with the user input values from a form. I have done it successfully with one field form the form (coin), but when I add a second variable the exact same way I keep getting the "missing 1 required positional argument" error.
Flask Code Below
#app.route('/addcoin/', methods=['POST', 'GET'])
def addcoin():
if request.method == "POST":
coin = request.form['Symbol']
high_price = request.form['High Price']
api = request.form['API']
channel = request.form['Channel']
# return f"<h1>{coin}{high_price}{api}{channel}</h1>"
print('High Price is ' + high_price)
print(coin)
print(type(high_price))
limit = float(high_price)
print(limit)
return redirect(url_for('coin_added', coin_added=coin, limit=limit))
else:
return render_template('addcoin.html')
#app.route('/new-coin/<coin_added>')
def coin_added(coin_added, limit):
return render_template('new_coin.html', coin=coin_added, high_price=limit)
I am trying to render the below HTML template:
{% extends "index.html" %}
{% block content %}
<h1>{{ coin }} has bee added!</h1>
<h1>{{ high_price }} is the cutoff price!</h1>
{% endblock %}
I have no issues when only using the "coin" argument within the coin_added() function of the '/new-coin/<coin_added>' route. But when I try and add the limit and high price variable it insists that the argument is missing. I am even printing out the "limit" variable to console to see if it exists and it prints out successfully before the redirect line. I am not sure why this is not getting passed to the coin_added route as limit.
If I remove the "limit" argument from the coin_added function everything works fine. I am very confused as to why it is saying the "limit" argument is missing, when it is getting passed in right above this.
Error Message
TypeError: coin_added() missing 1 required positional argument: 'limit'
I think your route is missing the limit variable. It should be something like this
#app.route('/new-coin/<coin_added>/<limit>')
More information on how to have multiple parameters here.
I'm trying to make a picture the url to the post the picture represents, and I must be doing something wrong, but I don't know what.
I am getting this error when trying to visit the home page of my site.
Error during template rendering
In template .../home.html, error at line 48
Reverse for 'view_post' with keyword arguments '{'post_id': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$']
and the code it showcases
<img src="media/{{ item.image }}">
Also this is my view
def view_post(request, post_id):
post = get_object_or_404(Post,id=post_id)
return render(request,'gram/view_post.html',{'post': post})
And url
url(r'^post/(?P<post_id>[0-9]+)/$', views.view_post, name='view_post'),
Thank you for your help.
I make some assumptions based on your code examples. This line:
post = get_object_or_404(Post,id=post_id)
says that the class Post has a property id. However in your template you call post.post_id. Assuming that post is an object instance of the class Post, it should have the property id. Probably there is no such property like post_id in the class Post.
This means that in the template post.post_id won't return an output. Your urls, which are not shown here, expect an integer ['post/(?P[0-9]+)/$']. Therefore the error is thrown.
Try this snippet:
{% url 'view_post' post_id=post.id %}
and check what happens.
As I said, this is based on some presumptions and I don't guarantee success.
Turned out I'm just stupid and made it hard for myself. The problem was I've done <a href in my home.html and home view didn't know what post.id is - obviously. The problem is fixed.
I'm having trouble getting password_reset_confirm to work. I have looked at numerous solutions, but none seem to be working for me.
urls.py: (in particular, the third line)
(r'^resetpassword/passwordsent/$', 'django.contrib.auth.views.password_reset_done', name="reset_password"),
(r'^resetpassword/$', 'django.contrib.auth.views.password_reset', name="reset_password"),
(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>,+)/$', 'django.contrib.auth.views.password_reset_confirm'),
(r'^reset/done/$', 'django.contrib.auth.views.password_reset_complete'),
the password_reset_email.html:
{% load url from future %}
{% autoescape off %}
Someone asked for password reset for email {{ email }}. Follow the link below:
{{ protocol}}://{{ domain }}{% url 'django.contrib.auth.views.password_reset_confirm' uidb64=uid token=token %}
{% endautoescape %}
Everything seems to be working fine, until I submit my e-mail and get the following error:
Reverse for 'django.contrib.auth.views.password_reset_confirm' with arguments '()' and keyword arguments '{u'uidb64': 'OQ', u'token': u'3n2-0fee9d3f98dad36e63d8'}' not found. 2 pattern(s) tried: ['/$reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'reset/(?P<uidb64>[0-9A-Za-z_\\-]+)-(?P<token>,+)/$']
I am using Django 1.6.
Any help is much appreciated! Thanks!
You can see from the exception what's going on, although it's a little hard to spot. If you look at what patterns it tried:
2 pattern(s) tried: ['/$reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'reset/(?P<uidb64>[0-9A-Za-z_\\-]+)-(?P<token>,+)/$']
You should notice that the first pattern is the one that should generally match, in the sense that it accepts a token with a - in it. But it has a stray $ prepending the rest of its content, so actually it can't match anything:
'/$reset/...'
You don't show the urls.py line that establishes that pattern - the third line you refer to can only match a token consisting of nothing but commas:
(?P<token>,+)
So while I can safely say that you need to correct your urls.py, I cannot say exactly where you need to correct it. If you intend to match that urls.py line, you should update the token group regexp to accept your actual token values, and should figure out why the other one is around to match at all. That said, if - is a valid character to appear as part of your token I think you'll find it easier overall to use / as a divider between your uidb64 field and your token, as your first regexp does except for the stray $.
trying to use the Django {%url %} template tag and keep failing.
the view is defined in sitename/transfers/views.py (where transfers is the django app name):
def description_ListView(requesst,**kwargs):
template_name = 'transfers/description.html'
o = get_list_or_404(Transfer, description =kwargs['description'])
#print ('o:',o)
context_object_name = "transfer_name_list"
return render_to_response(template_name,{context_object_name:o,'description':kwargs['description']})
(yes, I DO know that this code is a little strange. working on making this more generic and caught in the middle with this annoying problem)
and the url is mapped in transfers/urls.py
url(r'^description/(?P<description>[\w ]+)/$',
'transfers.views.description_ListView',
name = 'description_url')
and in the tag:
{% url "description_url" "blabla" %}
also tried:
{% url "transfers.views.Description_ListView" description = "blabla" %}
the error message:
Exception Type: NoReverseMatch
Exception Value:
Reverse for '"description_url"' with arguments '(u'blabla',)' and keyword arguments '{}' not found.
or when i Tried using the as somename syntax and calling it like this: `{{somename}}. just failed silently and didn't produce anything.
where I also tried importing the Description_ListView from the views and using it directly, didn't help.
Also, following the advice of numerous answers on this subject in various SO questions I changed to double quotes around the view, and reverted to using the url name instead of view but neither helped.
I'll be glad for any help with this
I don't think you need quotes. Try:
{% url description_url "blabla" %}
See https://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns
Okay I am having a bit of an issue.
I want to create a button with a link, and right now I am using action={% url views.contest_overview %} in hopes that the reverse lookup by Django will match (r'^category/$', views.contest_overview), in my urls.py. However, this is not working and I can't figure out the proper nomenclature, despite numerous guesses.
The error I get (with my best guess above) is:
Caught NoReverseMatch while rendering: Reverse for
'views.contest_overview' with arguments '()' and keyword arguments
'{}' not found.
Thank you very much for your time!
Use the application name in the url tag, e.g. {% url myapp.views.contest_overview %}
This is what I usually do; I give names to my url. For example:
url(r'^account/register/$', 'someapp.views.register_view', name='account_register'),
Therefore in template, I can do this:
{% url account_register as url_acc_register %}
<html>
..
..
Some link