In my application, I want to show a list of items based on certain url. For example, when I type mysite.com/restaurants/chinese/, I want to show all the Chinese restaurants. If I type mysite.com/restaurants/american/, I want to show all the American restaurants and so on. But when I type mysite.com/restaurants/ I want to show all the restaurants, so I wrote this code:
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^restaurants/', include('restaurants.urls')),
]
restaurants/urls.py
from django.conf.urls import url
from django.views.generic import ListView
from .views import RestaurantLocationListView
urlpatterns = [
url(r'^(?P<slug>\w+)/$', RestaurantLocationListView.as_view()),
]
restaurants/views.py
from django.db.models import Q
from django.shortcuts import render
from django.views.generic import ListView
from .models import RestaurantLocation
class RestaurantLocationListView(ListView):
def get_queryset(self):
slug = self.kwargs.get('slug')
if slug:
queryset = RestaurantLocation.objects.filter(
Q(category__iexact=slug) | Q(category__icontains=slug)
)
else:
queryset = RestaurantLocation.objects.all()
return queryset
It's everything working well, except when I put only mysite.com/restaurants/. This gives me an 404 error instead the list of all restaurants and I don't know why. Can you guys help me?
Seems like a url issue. In your restaraunts/url.py you need to add a url for it.
urlpatterns = [
url(r'^$', RestaurantLocationListView.as_view()), # add it before
url(r'^(?P<slug>\w+)/$', RestaurantLocationListView.as_view()),
]
Related
there is a problem with a url i've created in django that it doesn't totally work
this is urls.py
from django.conf.urls import include, url
from django.contrib import admin
from pizza import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url('', views.home,name='home'),
url('order/', views.order,name='order'),
]
and this is views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Home page")
def order(request):
return HttpResponse("Order a pizza page")
That is incorrect syntax, try using path('') instead of url
If pizza it's your app you must use:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('pizza/', include('pizza.urls')),
]
in urls.py and add your app in settings.py inside INSTALLED_APPS
OR
If when you call from pizza import views is the name of Project you should import as import .views only
Update in project urls.py file.
I understand circular import error has been asked about a lot but after going through these questions I haven't been able to solve my issue. When I try to run my server in Django, it is giving me this error message:
django.core.exceptions.ImproperlyConfigured: The included URLconf 'starsocial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
The issue started when I added a new app which has a urls.py like the following:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
url(r'login/$',
auth_views.LoginView.as_view(template_name='accounts/login.html'),
name='login'),
url(r'logout/$',auth_views.LogoutView.as_view(), name='logout'),
url(r'signup/$',views.SignUp.as_view(), name='signup'),
]
My project urls.py has a line which points to the app and looks like the following code:
from django.contrib import admin
from django.urls import path,include
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^test/$', views.TestPage.as_view(), name='test'),
url(r'^thanks/$', views.ThanksPage.as_view(), name='thanks')
]
My application's view looks like the following:
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
My project's view looks like:
from django.views.generic import TemplateView
class TestPage(TemplateView):
template_name = 'test.html'
class ThanksPage(TemplateView):
template_name = 'thanks.html'
class HomePage(TemplateView):
template_name = 'index.html'
Can anyone please help me identify where I could possibly be going wrong.
You are importing auth.urls twice. Remove url(r'^accounts/', include('django.contrib.auth.urls')) from your project's urls.py
I am importing wrong URL configuration, instead of 'reverse' I should import 'reverse_lazy',
change
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse('login')
template_name = 'accounts/signup.html'
to
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView
from . import forms
# Create your views here.
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
Sorry, I am still new at django. I want to make custom view at admin site that is not related to my model. I have read the documentation (https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls), but does not work. Reading some tutorials does not work too...
Here is what I tried:
admin.py
from django.contrib import admin
from django.urls import path
from .models import Question
from django.http import HttpResponse
class CustomAdminView(admin.ModelAdmin):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'^my_view/$', self.admin_site.admin_view(self.my_view))
]
urls = my_urls + urls
return urls
def my_view(self, request):
return HttpResponse("Hello, world.")
admin.site.register(Question)
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
admin.autodiscover()
urlpatterns = [
path(r'polls/',include('polls.urls')),
path('admin/', admin.site.urls),
]
when I go to admin/my_view the result is 404 not found.
I tried by extending the AdminView too.
admin.py
from django.contrib.admin import AdminSite
from django.urls import path
from .models import Question
from django.http import HttpResponse
class CustomAdminView(AdminSite):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'my_view/', self.admin_view(self.my_view))
]
urls = my_urls + urls
return urls
def my_view(self, request):
return HttpResponse("Hello, world.")
custom_admin = CustomAdminView()
custom_admin.register(Question)
urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from polls.admin import custom_admin
admin.autodiscover()
urlpatterns = [
path(r'polls/',include('polls.urls')),
path('admin/', custom_admin.urls),
]
I don't get 404 error on admin/my_view. But, the default models(user, and others) are not displayed. There is only my 'Question' model there. The previous one still has the default models.
How can I make the custom admin view with the right way?
Thanks.
It is solved. I am using my second admin.py and urls.py snippets and register django's default model, based on this answer: Django (1.10) override AdminSite
admin.py
from django.contrib.admin import AdminSite
from django.http import HttpResponse
from django.urls import path
from .models import Question
from django.contrib.auth.models import Group, User #add these moduls
from django.contrib.auth.admin import GroupAdmin, UserAdmin #and these
class CustomAdminView(AdminSite):
def get_urls(self):
urls = super().get_urls()
my_urls = [
path(r'my_view/', self.admin_view(self.my_view))
]
urls = my_urls + urls
return urls
def my_view(self, request):
return HttpResponse("Hello, world.")
custom_admin = CustomAdminView()
custom_admin.register(Question)
#register the default model
custom_admin.register(Group, GroupAdmin)
custom_admin.register(User, UserAdmin)
I can't seem to get the urls to match in oscar. My oscar app is a subapp in my main app. My understanding is to create views and urls in the app.py in the sub modules in oscar.It keeps throwing NoReverseMatch. Oscar pages all loads, just not my custom views
in myapp/shop/dashboard/app.py
from django.contrib.auth import views as auth_views
from django.contrib.auth.forms import AuthenticationForm
from django.conf.urls import include, url
from oscar.core.application import DashboardApplication
from oscar.core.loading import get_class
from views import HomeViews
class DashboardApplication(DashboardApplication):
def get_urls(self):
urls = [
url(r'^someurl/', HomeViews.dosomething, name="hi"),
]
return self.post_process_urls(urls)
application = DashboardApplication()
in myapp/shop/dashboard/views.py
from django.conf import settings
from django.db.models import User
from oscar.app.partner.models import Partner
from django.middleware.csrf import get_token
from oscar.apps.dashboard.views import HomeView as CoreHomeView
class HomeView(CoreHomeView):
def dosomething(request):
return HttpResponse("hello")
in my main app, I registered the shop in my settings.py
INSTALLED_APPS =[
...
]] + get_core_apps(['shop'])
and in my main app url I have included oscar urls
from shop.app import application as shop_app
urlpatterns = i18n_patterns(
url(r'^shop/', include(shop_app.urls)),
You need to extend the existing urls list, not replace it. That is mostly why you get no reverse match errors because the default urls that oscar might have, don't exist anymore. For any other non-oscar-forked app, this would have been okay (just your own urls and nothing else).
class DashboardApplication(DashboardApplication):
def get_urls(self):
my_urls = [
url(r'^someurl/', HomeViews.dosomething, name="hi"),
]
default_urls = super(DashboardApplication, self).get_urls()
return self.post_process_urls(my_urls) + default_urls
I haven't found a satisfactory way of doing this: I have a djangocms setup that is working fine. But I need to add content from a table outside the CMS to my homepage and render that content on the template. I can do this, but editing the urls.py within CMS to use my views like so...
url(r'^', 'myapp.views.slideshow_info'),
... excludes any content from CMS. I understand that I just get my custom views to accommodate what CMS' views is doing, but how do I achieve this?
at the moment my app's views says:
from myapp.models import model1, model2
def slideshow_info(request):
return render_to_response('index.html', {'slideshow_list' : model1.objects.all()})
Many thanks
You can hook a custom app instance to any Django-CMS page. Here's the documentation on how to do so: http://docs.django-cms.org/en/2.1.3/extending_cms/app_integration.html#app-hooks You shouldn't need to alter the base url patterns to specifically re-route / to your view.
Before custom app-hooks were available, I would accomplish what you're trying to do with template tags.
Hope that helps you out.
Followup
Ok, in a recently completed site, I had to hook an app titled "portfolio" to display images on the home page of a Django-CMS site.
Here are the relevant portions of the code:
#portfolio/cms_app.py
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
class PortfolioAppHook(CMSApp):
name = _('Portfolio')
urls = ['portfolio.urls']
apphook_pool.register(PortfolioAppHook)
#portfolio/urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('portfolio.views',
url(r'^(?P<slug>[-\w]+)/$', 'project_detail', name='project_detail'),
url(r'^$', 'portfolio_index', name='portfolio_index'),
)
#portfolio/views.py
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
from portfolio.models import Project
def portfolio_index(request):
project_objects = Project.for_public if request.user.is_anonymous() \
else Project.objects
projects = project_objects.all().select_related(depth=1)
return render('portfolio/index.html',
{'projects' : projects}, request)
def project_detail(request, slug):
project = get_object_or_404(Project, slug=slug)
if not project.public and request.user.is_anonymous():
return HttpResponseRedirect('/?login=true')
return render('portfolio/project_detail.html',
{'project' : project}, request)
#urls.py (base urls)
from django.conf import settings
from django.conf.urls.defaults import *
from django.contrib import admin
from views import login_user, logout_user
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/filebrowser/', include('filebrowser.urls')),
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
url(r'^login/$', login_user, name='login_user'),
url(r'^logout/$', logout_user, name='logout_user'),
(r'^', include('sorl.thumbnail.urls')),
(r'^', include('cms.urls')),
)
if settings.SERVE_STATIC_MEDIA:
urlpatterns += patterns('',
(r'^' + settings.MEDIA_URL.lstrip('/'), include('appmedia.urls')),
) + urlpatterns
As you can see from this working example, I haven't altered my base URLs to accommodate the home page view, rather I've provided the URLs for my Portfolio app to Django-CMS through cms_app.py
Hope that gets you going.