I can't figure out what I've done wrong here. I'm using Django 1.6.5 with Python 2.7.6 on Ubuntu 14.04. I have a project called research containing an app called notecards. Here is my research/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'research.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^notecards/', include('notecards.urls', namespace='notecards')),
)
And here is the call to it in notecards/views.py
def new_note(request):
if request.method == 'GET':
form = NotecardForm()
else:
form = NotecardForm(request.POST)
if form.is_valid():
content = form.cleaned_data['content']
source = form.cleaned_data['source']
page = form.cleaned_data['page']
tags = form.cleaned_data['tags']
return HttpResponseRedirect(reverse('notecards:index', ()))
return render(request, 'notecards/new_note.html', {'form': form,
})
And here is the error I'm getting: u'notecards' is not a registered namespace. I must be missing something obvious, and yet I can't figure it out.
In your code, change the reverse('notecards:index', ()) to reverse('notecards:index'). The signature of reverse is
reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)
You could see that urlconf mistakenly takes () instead of args taking it.
Moreover, have a look at the django.shortcuts.resolve_url, it's easier for normal use.
Related
I hope someone could maybe help me, please :
I am quite new to Django and currently trying to implement a simple login/logout for a test page.
However, for some reasons, the Django does not generate the name of application in the href (so where it should be xxxx/main/register, it is only xxx/register).
But when I put the app name manually in the href in Pycharm, it generates it two times (so it becomes xxx/main/main/register).
So for this:
Logout
I got this url:
http://127.0.0.1:8000/logout/
If I write this:
Logout
I got this url:
http://127.0.0.1:8000/main/main/logout/
But I need to get this:
http://127.0.0.1:8000/main/logout/
It worked before, but from one minute to another, it suddenly stopped directing to the good path. And django does the same thing with every links in my site.
main/urls.py:
from django.urls import path
from . import views
app_name = 'main' # here for namespacing of urls.
urlpatterns = [
path("", views.homepage, name="homepage"),
path("register/", views.register, name="register" ),
path("logout/", views.logout_request, name="logout"),
]
main/views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Tutorial
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages
def homepage(request):
return render(request = request,
template_name='main/home.html',
context = {"tutorials":Tutorial.objects.all})
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"New account created: {username}")
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
else:
form = UserCreationForm
return render(request = request,
template_name='main/register.html',
context={"form":form})
def logout_request(request):
logout(request)
messages.info(request, "Logged out successfully!")
return redirect("main:homepage")
mysite/urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('main/', include('main.urls')),
path('admin/', admin.site.urls),
path('tinymce/', include('tinymce.urls')),
]
The behaviour you observe has nothing to do with Django, it's a basic html feature: in the first case you're using an absolute path (=> starting with a slash) for your href, in the second one you're using a relative path (NOT starting with a slash) so it's resolved relatively to the current url path whatever it is. You'd have the very same issue with plain static HTML.
This being said, in Django, you should never hardcode urls, but use the {% url <name> %} template tag (or the django.utils.reverse() function in Python code) instead, so you can change your urls in the urls.py files without breaking anything.
<a href="{% url 'logout' %}">
Use the name in href tag that will work.
You should use the url name in the template. It should solve the problem. Like this:
Logout
Or with namespacing:
Logout
I'm following the djangoforgirls.org tutorial on making my first django site. I'm trying the stage "extending your template" to make a link to an article within my website that uses the general template.
I keep get thrown the error: "NoReverseMatch at /, Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$']"
Some variable and file names may seem strange, the use of the website was music sampling but I used the tutorial's names for things in case that was what was wrong.
My urls.py for entire project:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('sample.urls')),
]
My urls.py for the specific app (sample):
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
My views.py for the app:
from django.utils import timezone
from .models import AudioSample
from django.shortcuts import render, get_object_or_404
def post_list(request):
samples = AudioSample.objects.order_by('length')
return render(request, 'blog/post_list.html', {'samples': samples})
def post_detail(request, pk):
post = get_object_or_404(AudioSample, pk=pk)
return render(request, 'blog/post.html', {'post': post})
And the line of code from the base template that's the link to another page in the website:
How to sample
I saw another person that asked this question with a similar project here and got it fixed but I dont understand the answer enough to make the change to mine (I dont understand what the namespace is).
If you have more than one urls.py, namespace can tell django how to handle the request. So in normally, namespace is the APP name.
In your project urls.py, try replacing r'' with r'^'. The former matches all urls, while the latter matches the start of the string.
i am stuck with this error:
"Reverse for 'create' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'$create$']"
I can't see where the problem is.
The log is an app in my general project
Here is my Project/log/templates/log/index.html that contain my form:
<form action="{% url 'log:create' %}" method="post">
//...
</form>
Here is the Project/Project/urls/py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('log.urls', namespace='log')),
url(r'^log/', include('log.urls', namespace='log')),
url(r'^admin/', include(admin.site.urls)),
]
Here is my Project/log/urls.py :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login$', views.login, name='login'),
url(r'^logout$', views.logout, name='logout'),
url(r'^create$', views.create, name='create'),
]
Then I defined my function create in the Project/log/views.py :
def create(request):
if request.method == "POST" and request.POST['name'] and request.POST['password']:
name_p = escape(request.POST['name'])
pass_p = escape(request.POST['password'])
try:
login = User.objects.get(username=name_p)
except:
user = User.objects.create_user(name_p, name_p+'#email.com', pass_p)
user.save()
return HttpResponseRedirect('log:index')
else:
return render(request, 'log/index.html', {'error_message' : 'The login you chose already exists',})
else:
return render(request, 'log/index.html', {'error_message' : 'You did\'t fill the entire form',})
I don't know where is my mistake because the form is a simple one with no arguments passed and the regular expression in the url is a simple one too. It must be a problem in my function I think. If someone could lead me to the right path to fix this kind of error that would be great ;)
I am working with django in one of my web application where i am also using userena.In userena profile template(profile_detail.html) i have added a anchor tag such as..
<a href = {% url 'send_referral_code'%}>Click here</a>
now here the send_referral_code is name value which is declared in urls.py,the urls.py is..
from django.conf.urls import patterns, url, include
from django.conf import settings
from mail import views
urlpatterns = patterns('',
url(r'^$', views.send_referral_code,name='send_referral_code'),
)
and views.py is...
from accounts.models import MyProfile
from django.core.mail import send_mail
def send_referral_code(request):
referral_code = MyProfile.objects.get(user = request.user)
send_mail('referral_code','This is Your Referral Code','you#email',['user#example.com'],fail_silently = False)
in mention, both views.py and urls.py resides another app namely 'mail'
and this is my main urls.py ..
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
import photo
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'auth.views.home', name='home'),
# url(r'^shutterstock/', include('shutterstock.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^accounts/', include('userena.urls')),
url(r'^user_upload/',include('myprofile.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^showphoto/',include('photo.urls')),
url(r'^mailing/',include('mail.urls')),
)
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^something/hard/to/guess/', include('paypal.standard.ipn.urls')), )
now i am getting an error namely Reverse for 'send_referral_code' with arguments '()' and keyword arguments '{}' not found while i am trying to execute my site and its indicating the line
<a href = {% url 'send_referral_code'%}>Click</a>
in my profile_detail.html file of my userena apps.Now how can i solve this or whats the actual problem?
The reason its not working is because your view code is returning an error. All view methods must return a HttpResponse object.
Any method in Python that doesn't have have a return statement, returns None; and since you don't have a return statement in your view method it is returning None which causes the view to not work.
Try this instead:
from django.shortcuts import redirect
def send_referral_code(request):
referral_code = MyProfile.objects.get(user = request.user)
send_mail('referral_code',
'This is Your Referral Code',
'you#email.com',
['user#example.com'],
fail_silently=False)
return redirect('/')
I have found the answer of my own,the problem is occuring because ,i have put the variable value as a first argument of the send_mail function parameter,that is,
send_mail('referral_code','This is Your Referral Code','you#email', ['user#example.com'],fail_silently = False)
i have just change it just like that...
send_mail('Referral Code','This is Your Referral Code','you#email',['user#example.com'],fail_silently = False)
now its working well,probabely the error Reverse for 'send_referral_code' with arguments '()' and keyword arguments '{}' not found is showing because i have put the varible instead of a Simple subject.Since i have put the varible in the place of the subject,thats why its contradicting.
how can I get the URL path for App
def logout(request):
auth.logout(request)
# path defined for the app in the projects urls.py
return HttpResponseRedirect('??????')
I know I can hard code it but how can I get it?
urls.py file
urlpatterns = patterns('',
url(r'^chat/',include('djangoChat.urls')),
djangoChat.urls.py file
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^login/$',views.login,name='login'),
url(r'^logout/$',views.logout,name='logout')
)
i want logout method to redirect to /chat path
so views.index method gets called
To reverse lookup a URL by name, do:
from django.core.urlresolvers import reverse
def logout(request):
auth.logout(request)
return HttpResponseRedirect(reverse('index'))