when i acess to my url i only get: <django.forms.fields.ChoiceField object at 0x026D1CD0>
i want the number Choicefield
i have the folowing models.py in my app:
from django.db import models
from django.forms import ModelForm
class Zonas(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class ZonasForm(ModelForm):
class Meta:
model = Zonas
I guess the problem is in my views.py:
from django import forms
from testApp.models import Zonas
from django.shortcuts import render_to_response
def menuForm (request):
z = list (Zonas.objects.all())
numbers = forms.ChoiceField(z)
return render_to_response('hello.html', {'numbers':numbers})
menuForm is used on my urls.py as:
from django.conf.urls import patterns, include, url
from testApp.views import menuForm
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^hello/$', menuForm ),
)
my html page, is as simple as it can be:
<html>
<body>
{{numbers}}
</body>
</html>
Any help appreciated
Your url for the page is not correct, change it to
url(r'^hello/$', menuForm),
As mentioned in the doc, it is of the form
(regular expression, Python callback function [, optional_dictionary [, optional_name]])
Also, change definition of the view function as
def menuForm (request):
....
Related
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 am trying to define a class in views.py which is inheriting generic view. The code is as follows. On running server I get the error that
class UserFormView(View):
NameError: name 'View' is not defined
although I have imported generic. Please let me know the reason.
from django.views import generic
from django.utils import timezone
from django.shortcuts import render, get_object_or_404,render_to_response,redirect
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth import authenticate,login
from django.core.context_processors import csrf
from .forms import UserForm
# Create your views here.
def home(request):
return render(request, 'fosssite/home.html')
def login(request):
c={}
c.update(csrf(request))
return render_to_response('fosssite/login.html',c)
class UserFormView(View):
form_class=UserForm
template_name='fosssite/signup.html'
def get(self,request):
form=self.form_class(None)
return render(request,self.template_name,{'form':form})
#validate by forms of django
def post(self,request):
form=self.form_class(request.POST)
if form.is_valid():
# not saving to database only creating object
user=form.save(commit=False)
#normalized data
username=form.cleaned_data['username']
password=form.cleaned_data['password']
#not as plain data
user.set_password(password)
user.save() #saved to database
def auth_view(request):
username=request.POST.get('username', '')
password=request.POST.get('password', '')
user=auth.authenticate(username=username,password=password)
if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/loggedin')#url in brackets
else:
return HttpResponseRedirect('/invalid')
def loggedin(request):
return render_to_response('fosssite/loggedin.html',{'fullname':request.user.username})
def logout(request):
auth.logout(request)
return render_to_response('fosssite/logout.html')
def invalid_login(request):
return render_to_response('fosssite/invalid_login.html')
`
You need to either import View explicitly:
from django.views.generic import View
or refer to it as generic.View:
class UserFormView(generic.View):
# ...
The View name needs to be imported. Add the following import statement:
from django.views.generic import View
Or use the already imported generic module in
class UserFormView(generic.View)
# ^
in urls.py
from my_app import views
eg code:
urls.py
from django.conf.urls import url
from django.contrib import admin
from pro1 import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^admin/', admin.site.urls),
]
views.py
from django.shortcuts import render
def home(request):
template="home.html"
context={}
return render(request,template,context)
guess it will solve the problem.
I am trying to use class based views, and get a strange error. The way I'm using the view seems to be the normal way:
ingredients/models.py:
from django.db import models
from django.utils import timezone
class Ingredient(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
def get_prices():
purchases = self.purchase_set.all()
prices = [purchase.price for purchase in purchases]
ingredients/views.py:
from django.shortcuts import render, render_to_response, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.edit import CreateView
from .models import Ingredient, Purchase
def IngredientCreateView(CreateView):
model = Ingredient
fields = ['all']
ingredients/urls.py:
from django.conf.urls import patterns, include, url
from ingredients.views import IngredientCreateView
urlpatterns = patterns('',
url(r'^new_ingredient$', IngredientCreateView.as_view(), name='new-ingredient'),
)
I get
AttributeError at /ingredients/new_ingredient
'function' object has no attribute 'as_view'
I am on django 1.8.5. Why won't this view work? Thank you
IngredientCreateView should be a class.
So your views.py replace:
def IngredientCreateView(CreateView):
with:
class IngredientCreateView(CreateView):
In my case, the problem was that I tried to use a #decorator on the class-based view as if it was a function-based view, instead of #decorating the class correctly.
EDIT: From the linked page, here is a way to apply #login_required to a class-based view:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#method_decorator(login_required, name='dispatch')
class ProtectedView(TemplateView):
IngredientCreateView is a function, not a class.
The following line
def IngredientCreateView(CreateView):
should be replace with
class IngredientCreateView(CreateView):
def Some_def_View(CreateView):
#should be replaced with
class SomeClassView(CreateView)
In addition to what is already said here, Check the file name and class name if it is same then you might have to import the class properly.
File name /api/A.py
class A:
//some methods
In your main class
//App main class
from api.A import A
I faced the same problem but this solution worked for me..
in views.py file in viewclass you can use viewsets instead of CreateView
from rest_framework import viewsets
class YourClassView(viewsets.ModelViewSet):
in urls.py file you can use this routing pattern
from django.conf.urls import url
from rest_framework import routers
router = routers.DefaultRouter()
router.register('books',YourClassView)
urlpatterns = [
path('', include(router.urls)),
path('admin/', admin.site.urls)
]
I've been trying for days now to use get_absolute_url and whenever I click on the view on site button in the admin page or click submit on my add form page, I get this error:
NoReverseMatch at /admin/r/14/3/ (or NoReverseMatch at /blogs/add/)
Reverse for 'blog_detail' with arguments '()' and keyword arguments '{'pk': 3}' not found. 0 pattern(s) tried: []
If I go to mysite/blog/3 I do get the blog details page just fine as I have it set up. So I know the page works, but it seems like its not trying to find it since it says zero patterns tried.
Docs I'm looking at are:
https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-editing/
https://docs.djangoproject.com/en/1.7/ref/models/instances/#get-absolute-url
My code (what I think is relevant at least. If more info is needed let me know please)
blogs.models.py
from django.contrib.auth.models import User
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from audit_log.models.fields import CreatingUserField, CreatingSessionKeyField
class Blog(models.Model):
created_by = CreatingUserField(related_name = "created_categories")
created_with_session_key = CreatingSessionKeyField()
created_time = models.DateTimeField(auto_now_add=True)
blog_title = models.CharField('Blog Title', max_length=200)
short_description = models.TextField('Short Description', max_length=140)
blog_image = models.CharField('Image', max_length=200)
youtube_link = models.URLField('YouTube', max_length=200)
external_site_link = models.URLField('Website', max_length=200)
full_blog = models.TextField(max_length=10000)
def get_absolute_url(self):
return reverse('blog_detail', kwargs={'pk': self.pk})
def __unicode__(self):
return self.blog_name
urls.py
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^blogs/', include('blogs.urls', namespace='blogs')),
)
blogs.urls.py
from django.conf.urls import patterns, url
from blogs import views
urlpatterns = patterns('',
url(
regex=r'^$',
view=views.BlogListView.as_view(),
name='blog_list'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogDetailView.as_view(),
name='blog_detail'
),
url(
regex=r'^add/$',
view=views.BlogCreate.as_view(),
name='blog_add'
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BlogUpdate.as_view(),
name='blog_update'
),
url(
regex=r'^(?P<pk>\d+)/delete/$',
view=views.BlogDelete.as_view(),
name='blog_delete'
),
)
blogs.views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic import RedirectView
from django.views.generic import UpdateView
from django.views.generic import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
# Only authenticated users can access views using this.
from braces.views import LoginRequiredMixin
from .models import Blog
class BlogDetailView(DetailView):
model = Blog
class BlogListView(ListView):
model = Blog
class BlogCreate(LoginRequiredMixin, CreateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogUpdate(LoginRequiredMixin, UpdateView):
model = Blog
fields = ['blog title', 'short_description', 'blog_image',
'youtube_link', 'external_site_link', 'full_blog']
class BlogDelete(LoginRequiredMixin, DeleteView):
model = Blog
success_url = reverse_lazy('blog_list')
you need to address url with namespace blogs like this:
return reverse('blogs:blog_detail', kwargs={'pk': self.pk})
I'm experimenting with Django forms. I'm trying to create a form which will accept the name of a city as input and output coordinates as output. My apps name is rango. I'm having a lot of trouble in URL reverse after accepting the input of the form..
My project/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
import os
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/',include('rango.urls', namespace="rango")),
)
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}), )
My rango/urls.py (rango is the name of the app):
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns('',
url(r'^welcome/$', views.index, name='index'),
url(r'^about/$', views.about, name='about_page'),
url(r'^categories/(?P<name_dir>\w+)/$',views.cats,name='cats'),
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
url(r'^disp_page/$', views.disp_page, name='disp_page')
My forms.py:
from django import forms
from rango.models import Page, Category
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the name of the city.")
#url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
#views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
exclude = ('category','url','views')
My views.py:
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category,Page
from pygeocoder import Geocoder
from rango.forms import PageForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import operator
# Create your views here.
def geo(request,city):
context = RequestContext(request)
citydata=Geocoder.geocode(city)
codtuple=citydata[0].coordinates
codtuple=list(codtuple)
context_dict = {'cood':codtuple}
return render_to_response('coods.html',context_dict,context)
def disp_page(request):
# A HTTP POST?
if request.method == 'POST':
form = PageForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
#form.save(commit=True)
city = form.cleaned_data['title']
# context = RequestContext(request)
#citydata=Geocoder.geocode(cityname)
#codtuple=citydata[0].coordinates
#codtuple=list(codtuple)
#context_dict = {'cood':codtuple}
return HttpResponseRedirect(reverse('rango:geo', args=(request,city)))
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = PageForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'disp_page.html', {'form': form})
Basically the disp_page displays the form. I type the name of a city in the form(EX:NEWYORK) and then it has to redirect to the "geo" function in my views.py which would output the coordinates in a different view. This redirection doesn't seem to be happening. Any help is appreciated!!
change this line
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='coods'),
in rango/urls.py to :
url(r'^disp_page/(?P<city>\w+)/$',views.geo,name='geo'),
and use :
return HttpResponseRedirect(reverse('rango:geo', args=(city,)))