I am trying to render the url of the movie clicked among numerous other movies. The url should be in the format
url/moviename. However, I am getting this error
movie_detail() got an unexpected keyword argument 'movie_name'
Please help me.... I am very new to Django, as you can see.
views code:
def movie_detail(request, movie_name):
movieneed = movies.objects.get(title = movie_name)
movieneed = movieneed.replace("_", " ")
return render(request, 'app/movie.html', {'movie':movieneed})
template code:
{% for movie in movies %}
<li data-id="{{ movie.id }}"><span class="title">
<a href="{% url "movie" movie_name=movie.movie_name %}">
{{ movie.title }}</a></span> ({{ movie.year }}) - {{ movie.genre}}<a class="delete">X</a></li>
{% endfor %}
url code:
url(r'^(?P<movie_name>)/$', views.movie_detail, name='movie'),
Ordinarily, that exception would mean that you don't have a movie_name parameter in your movie_detail function, but clearly you do.
I'm not positive, but I think the problem may be that you don't actually have anything to match in there. For example, say you only allow movie titles with letters, numbers, and hyphens (no punctuation, spaces, etc.) Then you need to use a regular expression like this:
url(r'^(?P<movie_name>[-\w]+)/$', views.movie_detail, name='movie')
I think the problem is on the url regex. read this doc, can be helpful.
url(r'^(?P<movie_name>)/$', views.movie_detail, name='movie'),
To:
url(r'^(?P<movie_name>[\w-]+)/$', views.movie_detail, name='movie'),
Named groups¶
The above example used simple, non-named regular-expression groups
(via parenthesis) to capture bits of the URL and pass them as
positional arguments to a view. In more advanced usage, it’s possible
to use named regular-expression groups to capture URL bits and pass
them as keyword arguments to a view.
In Python regular expressions, the syntax for named regular-expression
groups is (?Ppattern), where name is the name of the group and
pattern is some pattern to match.
You might want to change the movie name in the url for a slug field, slugs are specially suited fields to convert arbitrary strings into valid url strings
as for your problem, your url is not getting properly matched, try this:
url(r'^(?P<movie_name>[-\w]+)/$', views.movie_detail, name='movie'),
Related
So I know I can pass one argument like this: {%url '...path...' argument%} but I want to pass 2 arguments like {%url '...path...' argument1 argument2%}
Here is my exact code:
search.html:
{% for id, title, thumbnail in videos%}
<img src="{{thumbnail}}">{{title}}<p style="display:inline;"> | </p>Add to playlist
<br>
{%endfor%}
urls.py:
path('select/<id>/<title>', views.select, name='select'),
I get the following error:
Reverse for 'select' with arguments '('omPiA5AsGWw', 'PRESLAVA - POSLEDEN ADRES / Преслава - Последен адрес, 2007')' not found. 1 pattern(s) tried: ['select/(?P[^/]+)/(?P[^/]+)$']
Your title contains a slash. You should specify path as path converter:
path('select/<id>/<path:title>', views.select, name='select'),
That being said, I'm not sure it is a good idea to encode such titles in the url, it will make ugly URLs with a lot of percentage encoded characters. You might want to look at slugs instead [Django-doc].
I am not sure why you want to pass two paths but you could look at using condition tags in template to avoid a lot of hardcoded templates
I'm working on configurable email template and need to validate if only available_variables are used in the content. So if user put {{ apple }}, the form should return ValidationError('This variable is unavailable').
models.py:
email_content = models.TextField()
forms.py:
def clean_email_content(self):
email_content = self.cleaned_data['email_content']
available_variables = ['{{ company_name }}', '{{ user_name }}']
required_variables = ['{{ company_name }}']
for required_variable in required_variables:
if not required_variable in email_content:
raise forms.ValidationError("{} is required".format(required_variable))
# how to check if there are only `available_variables` in the content?
TL;DR
email_content cannot contain other variables (strings that starts with {{ and ends with }}) than specified in available_variables
Should I use regex or can I validate this using some method from Django Template Engine?
You may want to use the template engine's lexer instead (nb: django 1.11 code, might need to be adapted if you use django 2.x):
from django.template import base
lexer = base.Lexer("{{ var_one }} is one {% if var_two %}{{ var_two|upper }} is two {% endif %}")
tokens = lexer.tokenize()
for t in tokens:
if t.token_type == base.TOKEN_VAR:
print("{}: {}".format(t, t.contents)
I leave it up to you to read the template.base code to find out other useful features...
Also in your validation method you definitly want to catch ALL errors at once (instead of raising as soon as you found an error) so the user can fix all errors at once (unless you really want to drive your users mad, that is).
And finally, as Gasanov suggests in his answer, you also want to use sets to find both missing required vars and illegal ones - this is much more efficient than doing sequential lookups.
We can use regex to find all tags from email_content. After that we convert them to set and substract all available_variables from it to find all incorrect ones. If any exists - we throw ValidationError.
Note that available_variables is set itself and contains just tags, without curly brackets.
Our regex checks for any numbers of spaces between brackets and tag, so your users shouldn't be able to cheat.
import re
def clean_email_content(self):
email_content = self.cleaned_data['email_content']
available_variables = {'company_name', 'user_name'}
finds = re.findall(r"{{[ ]*(.*?)[ ]*}}", email_content)
invalid_tags = set(finds) - available_variables
if invalid_tags:
raise forms.ValidationError(
"Should not contain invalid tags: " + str(invalid_tags)
)
return email_content
I am trying to render dynamic Url in Django template as follows
<a href={{'jibambe_site_detail/'|add: site.id}}>{{ site }}</a>. This however is returning a TemplateSyntaxError at /jibambe_sites/
add requires 2 arguments, 1 provided. What am I missing or how should I render this dynamic URL, I want it to produce something like jibambe_site_detail/1
OP's strategy changed on this one but OP's original error seems to be because of the space after colon.
Use add:site.id instead of add: site.id
See a similar question about default here
From #schwobaseggl comment, I was able to add a dynamic url variable as follows <a href={% url 'site_details' pk=site.id %}>{{ site.name }}</a>
then in the urls.py urlpatterns, I gave the path to jibambe_site_details a name path('jibambe_site_detail/<slug:pk>', JibambeSitesDetails.as_view(), name='site_details'),
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 $.
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