I am using djangos built in comments framework presented in this example: https://docs.djangoproject.com/en/1.3/ref/contrib/comments/example/
And there is a sample code of how to implement a basic comment submission form
{% render_comment_form for entry %}
and when I use this code i get an error that my news model doesent have "add_comment" attribute. but there's no word about it in the example so I am asking how this "add_comment" shoudl work ?
Caught ViewDoesNotExist while rendering: Tried add_comment in module news.views. Error was: 'module' object has no attribute 'add_comment'
You probably have an error in urls.py file in your "news" app. It seems like one of URL patterns there is referring to a non-existing "add_comment" function.
Did you added comments in urls.py?
like so:
url(r'^comments/', include('django.contrib.comments.urls')),
Related
I have been getting this error for almost a week. I have googled and checked the docs and looked for youtube videos. I cannot find an answer to this seemingly simple and obvious question: What is the syntax for re_path() in the included urls from my apps?
error:
Reverse for 'jhp_url' with keyword arguments '{'slug': ''}' not found. 1 pattern(s)
tried: ['(?P<twodigit>[a-z]{2,3})/courts/(?P<slug>[-a-zA-Z0-9_]+)/$']
That pattern is correct! So obviously, the problem is slug has an empty string. But why? I have it in reverse():
def get_absolute_url(self):
return reverse('jhp_url', kwargs={'slug': self.slug})
Q1:Why isn't it seeing the kwarg from reverse() and using self.slug?
If I try to put self.slug in the view or the url as extra arguments, PyCharm complains.
Putting the namespace in reverse() and the template makes absolutely no difference! I get the same error.
BUT, if I take the namespace out of those two(1) places, I get a different error:
Reverse for 'jhp_url' not found. 'jhp_url' is not a valid view function or pattern name.
(1) as opposed to having it in one but not the other
So it seems like the first error I mentioned here is closer to being right.
My debug_toolbar template context says:
'slug': '^(?P<slug>[-a-zA-Z0-9_]+)/$'
I'm pretty sure that's wrong. It should be the actual slug and not the pattern. That's why I have focused on the app urls.py. But, as I said at the top of this rant. I have not been able to find anything on the syntax of re_path() in the included app urls!
bench.urls.py:
urlpatterns = [
re_path(r"^$", twodigit_testt1, {'slug': r"^(?P<slug>[-a-zA-Z0-9_]+)/$"},
name='tdr'),
re_path(r"(?P<slug>[-a-zA-Z0-9_]+)/$", courtdetail, name='jhp_url'),
Of course I still get these errors, but my point here is that the interpreter runs with that. But when I try things like
re_path(r"^$", twodigit_testt1, {'slug': r'^(?P=slug)/$'}, name='tdr'),
I just get syntax errors.
Finally, please note that these errors are coming because the list template that twodigit_test1 is calling has urls to the individual detail pages in it. If I take the detail urls out of the template, it works. But if I go directly to the detail page, after importing my app views into the project urls, that works, too! It's only the list template + detail urls combination that is the problem - and if you can't list your details on your list page, what's the point? I have tried both the url template tag and get_absolute_url in the template. Finally, I did ask an earlier version of this question. I know some people don't like that but it did not resolve this issue. I have reworked and refocused the question so it is not identical. Plus, I wasn't using re_path() then.
Info
I have two simple models in Django, with one-to-one relationship
I'm using generic views
There are Issues and Solutionss in the database, numbered 1 through 10
Loading the Issue via the DetailView (e.g. localhost:8000/myapp/6/) works great
Error
When trying to load the Solution view in a browser (e.g. localhost:8000/myapp/6/solution/), I get Page not found (404), No solution found matching the query.
Code
models.py:
class Issue(models.Model):
def __str__(self):
return self.issue_text
issue_text = models.CharField(max_length=200)
class Solution(models.Model):
def __str__(self):
return self.solution_text
issue = models.OneToOneField(Issue, on_delete=models.CASCADE)
solution_text = models.CharField(max_length=200)
views.py:
class DetailView(generic.DetailView):
model = Issue
template_name = 'my_templates/detail.html'
class SolutionView(generic.DetailView):
model = Solution
template_name = 'my_templates/solution.html'
urls.py:
urlpatterns = [
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/solution/$', views.SolutionView.as_view(), name='solution'),
]
Question
I suspect that maybe the relationship between the models is incorrect - I can see that the view raises the 404 error because it can't find a solution object (though there are a few solution objects in the database, for every Issue).
I've been going through Django's docs on generic views and making Django queries to the database but I think I'm confusing the two.
Also, debugging with pdb just makes the browser lose the object for some reason.
Did I get the one-to-one relationship wrong?
Which Django Version did you use? try this...
urls.py
urlpatterns = [
path('solution/<int:pk>/', SolutionView.as_view(), name='solution'),
]
views.py
class SolutionView(DetailView):
model = Solution
template_name ="my_templates/solution.html"
def get_object(self):
some_pk = self.kwargs.get("pk")
return get_object_or_404(Solution, pk=some_pk)
Tested. This works for me fine. It´s django 3.0 but i guess down to version 2.x this should also work.
you have to send the integer variable from your request to your class based view some_pk so that django can get the right object.
page not found relates also to your template path - so check it.
Don´t forget to set the right template_name and to import everything.
There was a mismatch between the app name and the object instance.
In this case, the app, the module and the model objects were named differently. For example - following django's tutorial: the name of the app should be polls and the templates sub-directory should also be polls/templates/polls, but in this case the app was named something like polls_app and the templates sub-directory something like polls_templates. Any other naming mismatch results in the same way.
I found this while trying to run tests in django - even though everything else worked (other than this specific, generic view), the tests failed with an error. Investigating that error led me to the tests runner code (see here or here) and loadTestsFromName in it.
So I guess that django relies on the object name (in the example above - it was searching for polls in polls_templates or something similar), but I couldn't find how this can be configured. Trying to debug it with pdb wans't great either, since I was getting way deep into django's source code.
I created a new app, with everything named the same, and now tests are running ok, and also the SolutionView, so having everything called by the same name solved the question for me.
I assume that there's a similar name-relying module in django's url which does the same thing.
I'm encountering an odd problem with namespaced url in Django, and I cannot find what I am doing wrong while it is working on simpler examples and using the
Basically, my project is made of two apps, user and model. In my general urls.py, I defined :
url(r'^model/', include('model.urls', namespace="model")),
url(r'^user/', include('user.urls', namespace="user")),
In the user.urls.py file, I defined the following url:
url(r'^duo/(?P<pseudo>[a-z]+)/$',views.duo, name='duo'),
The duo view is rather simple :
def duo(request,pseudo):
print pseudo
return render(request,"user/duo.html",locals())
Therefore, when I use in my templates:
{% url 'user:duo' lena %}
I expect the url to be resolved as /user/duo/lena. Instead, I got the following NoReverseMatch:
Reverse for 'duo' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'user/duo/(?P<pseudo>[a-z]+)/$']
I take any guess to fix my mistake !
Ok, Pynchia and Bernhard comments help me to fix my bug ! Now, I am using
"{% url 'user:duo' "lena" %}"
in my template and it's running smoothly ! Many thanks to you !
Edited according to the dicussion:
You need to quote your paramater. Also keyword parameters might make things clearer:
{% url 'user:duo' pseudo='lena' %}
If you don't quote the value, Django assumes this is a context variable and as lena is not a context variable in your case this evaluates to None. The error actually tells you, you didn't provide args or kwargs for the reverse lookup.
I want to use the {% url %} tag to get the url of a named view that takes a parameter.
I want to get the URL without the parameter and pass the parameter later using javascript. So I don't know the value of the parameter when the template renders ! If I try the url without parameters then it says "reverse not found"... I know I can hard code the url in my javcascript code but that's not DRY !!!
Thanks !
When I've had to do this in the past, I've used a sentinel value for the parameters, ie one that I know will never be passed for real, and used a regex in Javascript to replace it with the real ones.
{% url my_view "anobviouslyfakeparameter1" "anotherparamthatwillneverhappenforreal" %}
You can try the following:
url(r'^test/(\d+)/$', 'test_view', name='test-view'),
url(r'^test/$', 'test_view', name='test-view'),
And return a 404 if the parameter is not provided (in case someone would actually access this uri).
In my urls.py file, I have:
from myapp import views
...
(r'^categories/$', views.categories)
Where categories is a view function inside myapp/views.py. No other URLconf lines reference views.categories.
In a unit test file, I’m trying to grab this URL using django.core.urlresolvers.reverse(), instead of just copying '/categories/' (DRY and all that). So, I have:
from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
When I run my tests, I get a NoReverseMatch error:
NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
It matches just fine if I make the URL pattern a named pattern, like this:
url(r'^categories/$', views.categories, 'myapp-categories')
And use the pattern name to match it:
url = reverse('myapp-categories')
But as far as I can tell from the reverse documentation, I shouldn’t need to make it a named URL pattern just to use reverse.
Any ideas what I’m doing wrong?
Jack M.'s example is nearly correct.
It needs to be a url function, not a tuple, if you want to use named urls.
url(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
After futher investigation, turns out it was an issue with how I was importing the views module:
How do I successfully pass a function reference to Django’s reverse() function?
Thanks for the help though, guys: you inspired me to look at it properly.
This does work, and all the code that you've pasted is correct and works fine (I just copied it into a clean test/project app and it reversed the URL without any problem). So there's something else going on here that you haven't showed us. Simplify down to the bare-bones basics until it works, then start adding complexity back in and see where it's breaking.
Also, you can do "./manage.py shell" and then interactively import the reverse function and your view function and try the reverse. That'll remove the test setup as a possible cause.
The reverse function actually uses the "name" of the URL. This is defined like so:
urlpatterns = patterns('',
(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
(r'^admin/(.*)', admin.site.root),
)
Now you would call reverse with the string "no-monkeys" to get the correct url.
Ninja Edit: Here is a link to the django docs on the subject.