I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.
Related
For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening?
urls.py
from . import views
urlpatterns = [
path('',views.index, name='index'),
path('proceedaction/<str:pk>/',views.ProceedAction.as_view(),name='proceedaction'),
path('uploadct/<str:pk>/',views.UploadCT.as_view(),name='uploadct'),
]
views.py
from django.shortcuts import render,redirect
from django.views import View
from .models import CreatePatient,PatientRecord,FileData
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .filters import RecordFilter
from django.http import HttpResponse
import json
# Create your views here.
def index(request):
return render(request,'index.html')
class UploadCT(View,LoginRequiredMixin):
def get(self,request,pk):
records = PatientRecord.objects.filter(id=pk)
context={
'record' : records,
}
return render(request,'ct_upload.html',context=context)
def post(self,request):
dbdata = FileData()
return redirect('index')
I had not specified method=POST in the corresponding HTML file. Solved this issue by doing that.
I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows:
parameters.py
class FilePathConverter:
regex = '^[/]'
def to_python(self, value):
value=str(value)
return value.replace("?", "/")
def to_url(self, value):
value=str(value)
return value.replace("/", "?")
urls.py
from django.urls import path
from . import views
from django.contrib import admin
from django.views import generic
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FilePathConverter, 'filepath')
urlpatterns = [
path('', views.index, name='webpanel-index'),
path('controlserver/<filepath:server_path>/<str:control>', views.index, name='controlserver'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Server
from django.contrib.auth.decorators import login_required
import subprocess
def controlserver(request, server_path, control):
if request.POST:
subprocess.call(['bash', server_path, control])
return render(request, 'index.html')
However, with this method, I get this error:
Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$']
you can use Slug to resolve this patterns by :
from django.utils.text import slugify
path('controlserver/use slug .....', views.index, name='controlserver'),
but you need to put slug at views and templates So check this list of slug and pk :
https://github.com/salah-cpu/migration/blob/master/PATH_slug_pk
I am making my first django practice project I have a view called PostListview :
from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from blog.models import Post, Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.views.generic import(TemplateView,ListView,DetailView,CreateView,UpdateView,
DeleteView)
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
I have this in in the urls:
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
And this is the template which is calling this view.
<li class="navbar-brand bigbrand" >My Tech Blog</li>
This view is also set as the default home view and it opens fine at the time i open the site url (localhost) but when I am clicking "My Tech blog " it gives a 404 error.
This is the main urls.py :
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'accounts/login/$',views.login, name = 'login'),
url(r'accounts/logout/$',views.logout, name = 'logout',kwargs={'next_page':'/'}),
]
Just change
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
with
url(r'',views.PostListView.as_view(), name= 'post_list'),
I am working on Django, django-rest project and as I have searched the problem, it is beleived I have circular problem, but I don`t think so...
Relevant parts of problem are here:
demo/views.py
from django.shortcuts import render
from rest_auth.models import Upload, UploadForm
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
# Create your views here.
def home(request):
if request.method=="POST":
img = UploadForm(request.POST, request.FILES)
if img.is_valid():
img.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
img=UploadForm()
images=Upload.objects.all()
return render(request,'home.html',{'form':img,'images':images})
rest_auth/models.py
from django.conf import settings
from rest_framework.authtoken.models import Token as DefaultTokenModel
from .utils import import_callable
from django.db import models
from django.forms import ModelForm
class Upload(models.Model):
pic = models.ImageField("Image", upload_to="images/")
upload_date=models.DateTimeField(auto_now_add =True)
# FileUpload form class.
class UploadForm(ModelForm):
class Meta:
model = Upload
and
demo/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView, RedirectView
from django.conf import settings
from django.conf.urls.static import static
from views import home
from rest_framework_swagger.views import get_swagger_view
import os
PROJECT_DIR=os.path.dirname(__file__)
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="home.html"), name='home'),
url(r'^upload/$', views.home, name='imageupload'),
url(r'^signup/$', TemplateView.as_view(template_name="signup.html"),
name='signup'),
Problem is as stated this:
File "/Desktop/zadnja/django-rest-auth/demo/demo/urls.py",
line 6, in
from views import home File "/Desktop/zadnja/django-rest-auth/demo/demo/views.py", line
2, in
from rest_auth.models import Upload, UploadForm ImportError: cannot import name Upload
You do not have circular imports since rest_auth/models.py does not import any component from demo/views.py
I'm assuming rest_auth is an app in you project. To import Upload and UploadForm you should use absolute import:
from project_name.rest_auth.models import Upload, UploadForm
I am following this tutorial. At the moment I am at this point but when I start my server with python manage.py runserver 0.0.0.0:8000 and open the url in my browser, I receive following Error:
name 'IndexView' is not defined
This is my urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns
from rest_framework_nested import routers
from authentication.views import AccountViewSet
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/v1/', include(router.urls)),
url('^.*$', IndexView.as_view(), name='index'),
)
I don't know how to solve this problem, since I never saw myself even declaring this IndexView somewhere. It would be awesome if you guys could give me some suggestions on this one.
Edit:
my views.py
from django.shortcuts import render
# Create your views here.
from rest_framework import permissions, viewsets
from authentication.models import Account
from authentication.permissions import IsAccountOwner
from authentication.serializers import AccountSerializer
class AccountViewSet(viewsets.ModelViewSet):
lookup_field = 'username'
queryset = Account.objects.all()
serializer_class = AccountSerializer
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
Account.objects.create_user(**serializer.validated_data)
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'Account could not be created with received data.'
}, status = status.HTTP_400_BAD_REQUEST)
You have to create that IndexView and import it in your urls.py.
Currently the interpreter complains since in the urls.py IndexView is unknown.
To create a new view you should create a new class in views.py, something like:
from django.views.generic.base import TemplateView
class IndexView(TemplateView):
template_name = 'index.html'
ps: please read the official Django docs, which is very good!
The IndexView class is in the boilerplate project's views file.
C:\...\thinkster-django-angular-boilerplate-release\thinkster_django_angular_boilerplate\views
Copy and paste that content into your project's views file.
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator
class IndexView(TemplateView):
template_name = 'index.html'
#method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(IndexView, self).dispatch(*args, **kwargs)
in your urls.py
from .views import IndexView
url('^.*$', IndexView.as_view(), name='index'),
(.views or yourProject.views)
in your views.py
do what daveoncode wrote