I am new to Django and I am just trying to pass arguments to Django generic base View and it is not showing up in terminal as I am printing the arguments passed.
views.py
from django.views.generic import View
class CartView(View):
def get(self, request, *args, **kwargs):
item = request.GET.get('item')
qty = request.GET.get('qty')
print item, qty
return HttpResponseRedirect('/')
urls.py:
urlpatterns = [
url(r'^home/$', 'newsletter.views.home', name='home'),
url(r'^contact/$', 'newsletter.views.contact', name='contact'),
url(r'^about/$', 'dressika.views.about', name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('registration.backends.default.urls')),
url(r'^', include('products.urls')),
url(r'^categories/', include('products.urls_categories')),
url(r'^cart/', CartView.as_view(), name='cart'),
When I add some data in browser like "localhost:8000/cart/?item=2&qty=5" it is not showing the arguments in terminal according to above code. By only typing "localhost:8000/cart/" it does redirects me to homepage. But with arguments it shows 404.
It sounds like you may have to fix the entry in urls.py routing to the view. Could you post your urls.py as well?
Related
I am very new to django. I have followed the steps from a video on youtube on how to create a simple blog. Basically, I have a portfolio main page that displays several things including the latest blogs. It all works well. I can see the latest posts on the main page. I can also click in each of them and they open up fine.
However, now, I want to create a new page (blog.html) that will hold all the posts. I created a blog.html and did the necessary settings in views.py and urls.py. However, for some reason I get an error when trying to access localhost/blog/
This is my urls.py:
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name='work'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('blog/', views.blog, name='blog'),
]
Here views.py:
def home(request):
posts = Post.objects.all()
return render(request, 'home.html', {'posts': posts})
def post_detail(request, slug):
post = Post.objects.get(slug=slug)
return render(request, 'post_detail.html', {'post': post})
def blog(request):
posts = Post.objects.all()
return render(request, 'blog.html', {'posts': posts})
This happens if you trigger the post_detail view with a slug, and no Post with that slug exists. But here you simply trigger the wrong view. This is because <slug:slug>/ will also match blog/, so you will never trigger the blog/ view. You should reorder the views, so:
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name='work'),
# before <slug:slug>
path('blog/', views.blog, name='blog'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
]
It might however be better to make non-overlapping patterns, since now if you ever make a Post with blog as slug, that post is inacessible. You thus might want to rewrite the path to:
urlpatterns = [
path('', views.home, name='home'),
path('work/', views.work, name='work'),
path('blog/', views.blog, name='blog'),
# non-overlapping patterns
path('post/<slug:slug>/', views.post_detail, name='post_detail'),
]
Note: It is often better to use get_object_or_404(…) [Django-doc],
then to use .get(…) [Django-doc] directly. In case the object does not exists,
for example because the user altered the URL themselves, the get_object_or_404(…) will result in returning a HTTP 404 Not Found response, whereas using
.get(…) will result in a HTTP 500 Server Error.
Site doesn't show admin panel. What should I do?
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8001/admin/
Raised by: news.views.PageViews
With what it could be connected? I don't know what to do.
class PageViews(ListView):
template_name = 'page.html'
paginate_by = 8
context_object_name = 'posts'
ordering = ['-datetime']
model = Page
paginate_orphans = 1
def dispatch(self, request, *args, **kwargs):
slug = kwargs.get('slug')
try:
self.category = Category.objects.get(slug=slug)
except Category.DoesNotExist:
raise Http404
return super().dispatch(request, *args, **kwargs)
def get_queryset(self):
return Page.objects.filter(category=self.category)
My urls below:
path("register/", views.register, name="register"),
path("logout/", views.logout_request, name="logout"),
path("login/", views.login_request, name="login"),
path("profile/", views.account, name="account"),
path('', HomeView.as_view(), name='home'),
path('<slug:slug>/', views.PageViews.as_view(), name='page'),
path('robots.txt', views.robots_view),
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('summernote/', include('django_summernote.urls')),
I'd bet that your url controller for PageViews is too broad and Django tries to execute PageViews with slag 'admin' instead of opening the admin site.
Please, note that it's just a wild guess - you question is very hard to answer. Read this before posting another one: How do I ask a good question
Django checks URL patterns in order. Since "admin" would be valid as a slug, the URL matches against the PageViews pattern and that view is called.
The solution is to put the more specific URLs, in this case admin, at the top of the list.
You just need to change the order of your URLs. Django tries them from top to bottom. What is happening is that Django is processing 'admin' as a slug and trying to find a url with a slug with admin.
Change your urls.py to something like this:
path("register/", views.register, name="register"),
path("logout/", views.logout_request, name="logout"),
path("login/", views.login_request, name="login"),
path("profile/", views.account, name="account"),
path('admin/', admin.site.urls), #move your admin/ to here
path('', HomeView.as_view(), name='home'),
path('<slug:slug>/', views.PageViews.as_view(), name='page'), #where your admin url is going to get 404ed
path('robots.txt', views.robots_view),
path('accounts/', include('django.contrib.auth.urls')),
path('summernote/', include('django_summernote.urls')),
I would like to support the above views in a single view in url ...in my search I came across this post which is no longer supported and all the tutorials i've found have been outdated, which demonstrate how to accomplish the task in django 1.8.3.
In 'products/views.py' I have created a views for products and details. ProductListView will display all products, while ProductDetailView will display a single product detail (title, description, price etc).
products/views.py
class ProductListView(ListView):
queryset = Product.objects.all()
template_name = "products/list.html"
class ProductDetailView(DetailView):
queryset = Product.objects.all()
template_name = "products/detail.html"
products/urls.py include path to the views for ProductListView and ProductDetailView. ProductListView appears to be correct. ProductDetailView is incorrect! I'm getting the following warnings:
WARNINGS: ?: (2_0.W001) Your URL pattern '^products/(?P\d+)/$'
[name='details'] has a route that contains '(?P<', begins with a '^',
or ends with a '$'. This was likely an oversight when migrating to
django.urls.path().
ecommerce.py/urls.py is where i've included products and details urls
ecommerce/urls.py:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from .views import home, about, contact
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home'),
path('about/', about, name='about'),
path('products/', include('products.urls'), name='products'),
path('products/', include('products.urls'), name='details'),
path('contact/', contact, name='contact'),
path('account/', include('allauth.urls'), name='login'),
path('register/', include('allauth.urls'), name='register'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
products/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.ProductListView.as_view(), name='products'),
path(r'^products/(?P<id>\d+)/$', views.ProductDetailView.as_view(), name='details')
]
You've got that warning because Django unable to match the url to any of your urlpattern. Shortly you can use this to solve your problem:
# products/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.ProductListView.as_view(), name='products'),
path('products/<int:pk>/$', views.ProductDetailView.as_view(), name='details')
]
or if you want to use regex to match your url then:
# products/urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.ProductListView.as_view(), name='products'),
re_path(r'^products/(?P<pk>\d+)/$', views.ProductDetailView.as_view(), name='details')
]
The reason is because your ProductDetailView are inheriting from DetailView of Django. That View already implemented some mixin to get the object from pk key instead of id that's why when you change to use <int:pk> it'll works.
You can take a look at the source code to see how Django implementing to query the object. (Keep you eyes on SingleObjectMixin mixin and property pk_url_kwarg = 'pk'.
I also recommend you to change the value of pk_url_kwarg in ProductDetailView view and also remember to change pk in the urlpattern into the new value which match with pk_url_kwarg value.
I have created custom index view. urls.py:
url(r'^', include('cms.urls')),
url(r'^', 'myapp.views.index', name='index'),
in views.py:
from cms.utils import get_template_from_request
def index(request):
template = get_template_from_request(request)
.....
return render(request, template)
When i try to access django admin 127.0.0.1:8000/admin i get an error
'NoneType' object has no attribute 'pk'
because in my index.html is templatetag {% product_list request.current_page %} which requires current_page to be in request. I think this happens because django renders my index page in django admin, where it shouldn't. What can i do to fix this?
I think the easiest way to fix your problem is to include the urls of the admin site before those 'index' and 'cms' as explained in the Django documentation site. Your url patterns in the urls.py file would be something like this:
...
url(r'^admin/', admin.site.urls),
url(r'^', include('cms.urls')),
url(r'^', 'myapp.views.index', name='index'),
...
Previously i had url(r'^myapp/', include('myapp.urls')), changed to url(r'^', include('myapp.urls')) and it's working.
I'm having a problem with the way my URL's look in Django. I have a view like this:
def updatetext(request, fb_id):
Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])
fb = get_object_or_404(Account, pk=fb_id)
return render(request, 'myapp/account.html', {
'success_message': "Success: Settings updated.",
'user': fb
})
When a user clicks on the URL to update the text they are then redirected to the account page but the URL then looks like 'account/updatetext/'. I would like it just be 'account/'.
How would I do this in Django. What would I use in place of render that would still allow me to pass request, 'success_message' and 'user' into the returned page but to not contain the 'updatetext' within the URL?
[edit]
The urls.py file looks like this:
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^home/$', views.index, name='index'),
url(r'^(?P<fb_id>\d+)/$', views.account, name='account'),
url(r'^(?P<fb_id>\d+)/updatetext/$', views.updatetext, name='updatetext'),
url(r'^(?P<fb_id>\d+)/updatepages/$', views.updatepages, name='updatepages'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^admin/$', views.useradmin, name='admin'),
)
You need to actually redirect the user to '/account/'. Rather than returning a call to render you can do the following:
from django.http import HttpResponseRedirect
def updatetext(request, fb_id):
Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])
fb = get_object_or_404(Account, pk=fb_id)
return HttpResponseRedirect(reverse('account', kwargs={"fb_id": fb_id}))
However, it would be better to pass in a call to reverse into the HttpResponseRedirect constructor, but since I don't know your urls.py I just wrote the relative url.