Django - Render is not working in my project - django

I am dealing with form like 1 week but couldn't solve my issue. Probably i overlook something that can be found easy by other eyes, but totally, i don't know what to do. I recognize problem by starting build form. I had to use render for form and it failed in every try. I am able to connect db and showing data in html pages but whenever i use render instead of render_to_response it is failing. And i had to use render for post request as i know. Not only for form, render is not working for all. Even for a simple: def home(request): context = {'foo': 'bar'} return render(request, 'main.html', context)
models.py
class ModuleNames(models.Model):
ModuleName = models.CharField(max_length = 50)
ModuleDesc = models.CharField(max_length = 256)
ModuleSort = models.SmallIntegerField()
isActive = models.BooleanField()
ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True)
slug = models.SlugField(('ModuleName'), max_length=50, blank=True)
class Meta:
app_label = 'zz'
def __unicode__(self):
return self.status
forms.py
from django import forms
from MyApp.models import ModuleNames
class ModuleForm(forms.ModelForm):
moduleName = forms.CharField(label='Module Name', max_length=50)
ModuleDesc = forms.CharField(max_length = 256)
ModuleSort = forms.IntegerField()
isActive = forms.BooleanField()
ModuleType = forms.IntegerField()
class Meta:
model = ModuleNames
fields =('moduleName','ModuleDesc','ModuleSort','isActive','ModuleType')
view.py
from django.views.generic import TemplateView
from django.shortcuts import render,render_to_response, redirect
from django.template import RequestContext
import json
from django.core.serializers.json import Serializer
from django.http import HttpResponse, Http404, HttpResponseRedirect
from urllib.parse import urlparse
from django.urls import resolve
from django.db import connection
from collections import namedtuple
from django.db.models import F
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from MyApp.models import ModuleNames
from MyApp.forms import ModuleForm
def AddNewModule(request):
template_name = 'addnewmodule.html'
if request.method == 'GET':
form = ModuleForm()
posts = ModuleNames.objects.all()
args = {'form': form, 'posts': posts }
return render(request, template_name, args) #This part is showing data when i use render_to_response. But after clicking Save button on html page, it will give below first error.
if request.method == 'POST':
form = ModuleForm(request.POST)
if form.is_valid():
form.pop('csrfmiddlewaretoken', None)
post = form.save(commit=False)
post.save()
text = form.cleaned_data['post']
form = ModuleForm()
args = {'form': form, 'text': text}
return render(request, template_name, args)
Error that i have when using render_to_response
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
Error when i use render for any function
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/addnewmodule
Django Version: 2.1.3
Python Version: 3.7.1
Installed Applications:
['MyApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34.response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
126.response = self.process_exception_by_middleware(e, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
124.response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Cem/Documents/Projects/Python/Web/FirstApp/MyApp/views.py" in addnewmodule
132.return render(request, template_name, args)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/shortcuts.py" in render
36.content = loader.render_to_string(template_name, context, request, using=using)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/loader.py" in render_to_string
62.return template.render(context, request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/backends/django.py" in render
61.return self.template.render(context)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/base.py" in render
169.with context.bind_template(self):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py" in __enter__
112.return next(self.gen)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/template/context.py" in bind_template
246.updates.update(processor(self.request))
Exception Type: TypeError at /addnewmodule
Exception Value: 'module' object is not callable

Read about CSRF tokens in django, it's used for site protection/

You are missing the the csrf_token in your addnewmodule.html form, so,
you can get back to addnewmodule.html form and add the {% csrf_token %}just below the tag form action="" method="POST" like this
<form action="" method="POST">
{% csrf_token %}

Related

Django: NoReverseMatch Error production_id: None

Having an issue where I would fill out the form and when I click to save the input, it would show the info submitted into the query but my production_id value would return as None.
Here is the error:
Environment:
Request Method: POST
Request URL: http://192.168.33.10:8000/podfunnel/episodeinfo/
Django Version: 1.9
Python Version: 2.7.6
Installed Applications:
('producer',
'django.contrib.admin',
'django.contrib.sites',
'registration',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'storages',
'django_extensions',
'randomslugfield',
'adminsortable2',
'crispy_forms')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py" in dispatch
56. return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/vagrant/fullcast_project/producer/views/pod_funnel.py" in post
601. return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production_id}))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /podfunnel/episodeinfo/
Exception Value: Reverse for 'episodeimagefiles' with arguments '()' and keyword arguments '{'production_id': None}' not found. 1 pattern(s) tried: [u'podfunnel/episodeimagefiles/(?P<production_id>[0-9]+)/$']
Here is my pod_funnel.py view:
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render, get_object_or_404
from django.views.generic import View, RedirectView, TemplateView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms.client_setup import ClientSetupForm
from .forms.podcast_setup import PodcastSetupForm
from .forms.episode_info import EpisodeInfoForm
from .forms.image_files import EpisodeImageFilesForm
from .forms.wordpress_info import EpisodeWordpressInfoForm
from .forms.chapter_marks import EpisodeChapterMarksForm
from .forms.show_links import ShowLinksForm
from .forms.tweetables import TweetablesForm
from .forms.clicktotweet import ClickToTweetForm
from .forms.schedule import ScheduleForm
from .forms.wordpress_account import WordpressAccountForm
from .forms.wordpress_account_setup import WordpressAccountSetupForm
from .forms.wordpress_account_sortable import WordpressAccountSortableForm
from .forms.soundcloud_account import SoundcloudAccountForm
from .forms.twitter_account import TwitterAccountForm
from producer.helpers import get_podfunnel_client_and_podcast_for_user
from producer.helpers.soundcloud_api import SoundcloudAPI
from producer.helpers.twitter import TwitterAPI
from django.conf import settings
from producer.models import Client, Production, ChapterMark, ProductionLink, ProductionTweet, Podcast, WordpressConfig, Credentials, WordPressSortableSection, \
TwitterConfig, SoundcloudConfig
from django.core.urlresolvers import reverse
from producer.tasks.auphonic import update_or_create_preset_for_podcast
class EpisodeInfoView(LoginRequiredMixin, View):
form_class = EpisodeInfoForm
template_name = 'pod_funnel/forms_episode_info.html'
def get(self, request, *args, **kwargs):
initial_values = {}
user = request.user
# Lets get client and podcast for the user already. if not existent raise 404
client, podcast = get_podfunnel_client_and_podcast_for_user(user)
if client is None or podcast is None:
raise Http404
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', None)
if production_id:
production = get_object_or_404(Production, id=production_id)
# Ensure this production belongs to this user, if not Unauthorized, 403
if production.podcast_id != podcast.id:
return HttpResponseForbidden()
initial_values['production_id'] = production.id
initial_values['episode_number'] = production.episode_number
initial_values['episode_title'] = production.episode_title
initial_values['episode_guest_first_name'] = production.episode_guest_first_name
initial_values['episode_guest_last_name'] = production.episode_guest_last_name
initial_values['episode_guest_twitter_name'] = production.episode_guest_twitter_name
initial_values['episode_summary'] = production.episode_summary
form = self.form_class(initial=initial_values)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
client, podcast = get_podfunnel_client_and_podcast_for_user(request.user)
if form.is_valid():
# lets get the data
production_id = form.cleaned_data.get('production_id')
episode_number = form.cleaned_data.get('episode_number')
episode_title = form.cleaned_data.get('episode_title')
episode_guest_first_name = form.cleaned_data.get('episode_guest_first_name')
episode_guest_last_name = form.cleaned_data.get('episode_guest_last_name')
episode_guest_twitter_name = form.cleaned_data.get('episode_guest_twitter_name')
episode_summary = form.cleaned_data.get('episode_summary')
#if a production existed, we update, if not we create
if production_id is not None:
production = Production.objects.get(id=production_id)
else:
production = Production(podcast=podcast)
production.episode_number = episode_number
production.episode_title = episode_title
production.episode_guest_first_name = episode_guest_first_name
production.episode_guest_last_name = episode_guest_last_name
production.episode_guest_twitter_name = episode_guest_twitter_name
production.episode_summary = episode_summary
production.save()
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production_id}))
return render(request, self.template_name, {'form': form})
episode_info.py form:
from django import forms
class EpisodeInfoForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
episode_number = forms.IntegerField(widget=forms.NumberInput, required=True)
episode_title = forms.CharField(max_length=255, required=True)
episode_guest_first_name = forms.CharField(max_length=128)
episode_guest_last_name = forms.CharField(max_length=128)
episode_guest_twitter_name = forms.CharField(max_length=64)
episode_summary = forms.CharField(widget=forms.Textarea)
And url.py:
from django.conf.urls import url
from django.views.generic import TemplateView
import producer.views.pod_funnel as views
urlpatterns = [
url(r'^dashboard/', views.dashboard, name="dashboard"),
url(r'^clientsetup/', views.ClientSetupView.as_view(), name="clientsetup"),
url(r'^podcastsetup/', views.PodcastSetupView.as_view(), name="podcastsetup"),
url(r'^episodeinfo/$', views.EpisodeInfoView.as_view(), name="episodeinfo"),
url(r'^episodeinfo/(?P<production_id>[0-9]+)/$', views.EpisodeInfoView.as_view(), name="episodeinfo_edit"),
url(r'^episodeimagefiles/(?P<production_id>[0-9]+)/$', views.EpisodeImageFilesView.as_view(), name="episodeimagefiles"),
Any suggestion would be appreciated.
It looks like production_id can be None in your view, in which case you can't use it when you call reverse. It would be better to use production.id instead. You have just saved the production in your view, so production.id will be set.
return HttpResponseRedirect(reverse('podfunnel:episodeimagefiles', kwargs={'production_id':production.id}))
Note that you can simplify this line by using the redirect shortcut. Add the import,
from django.shortcuts import redirect
then change the line to
return redirect('podfunnel:episodeimagefiles', production_id=production.id)
You can't always redirect to episodeimagefiles if you didn't provide appropriate initial value for production_id:
# See if a production_id is passed on the kwargs, if so, retrieve and fill current data.
# if not just provide empty form since will be new.
production_id = kwargs.get('production_id', None) <-- here you set production_id variable to None if no `production_id` in kwargs
Look at your exception:
Exception Value: Reverse for 'episodeimagefiles' with arguments '()' and keyword arguments '{'production_id': None}' not found. 1 pattern(s) tried: [u'podfunnel/episodeimagefiles/(?P<production_id>[0-9]+)/$']
It means you passed None value for production_id variable, but episodeimagefiles pattern required some int value to resolve url, so it raises NoReverseMatch exception.
Your form is valid in EpisodeInfoView.post because you set required=False for production_id attribute in your form:
class EpisodeInfoForm(forms.Form):
production_id = forms.IntegerField(widget=forms.Field.hidden_widget, required=False)
I guess, if you debug your generated form before submit it, you can see something like <input type="hidden" name="production_id" value="None" />

django name render is not defined

I have an error when I try to import render in my program and I fear it is because it is not supported in django 1.9.
I am using python 3.4 and django 1.9.
When I try to run my server, I have the error:
ImportError: cannot import name render`.
Here is my code:
blog/views:
from datetime import datetime
from django.shortcuts import render
def date_actuelle(request):
return render(request, 'blog/date.html', {'date': datetime.now()})
def addition(request, nombre1, nombre2):
total = int(nombre1) + int(nombre2)
# Retourne nombre1, nombre2 et la somme des deux au tpl
return render(request, 'blog/addition.html', locals())
blog/urls:
from django.conf.urls import url, patterns
from . import views
urlpatterns = [
# url(r'^accueil/$', views.home),
# url(r'^article/(?P<id_article>\d+)$', views.view_article),
# url(r'^article/(?P<year>\d{4})/(?P<month>\d{2})$', views.list_articles),
# url(r'^redirection$', views.view_redirection),
url(r'^date/$', views.date_actuelle),
url(r'^addition/(?P<nombre1>\d+)/(?P<nombre2>\d+)/$', views.addition),
]
creps_bretonnes.urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^blog/', include('blog.urls')),
]
I have also tried from django.shortcuts import *, then the server is launched but when I try to access the page it says NameError: name 'render' is not defined.
Would you have an idea?
What is written on the server when I run it:
cmd values when trying to run the server with from django.shortcuts import render
traceback when using from django.shortcuts import * and trying to access localhost:8000/blog/date
Environment:
Request Method: GET
Request URL: http://localhost:8000/blog/date/
Django Version: 1.9.7
Python Version: 3.4.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sperney\Documents\Travail\creps_bretonnes\blog\views.py" in date_actuelle
37. return render(request, 'blog/date.html', {'date': datetime.now()})
Exception Type: NameError at /blog/date/
Exception Value: name 'render' is not defined
here it is:
"""
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
from django.template import loader
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
from django.db.models.manager import Manager
from django.db.models.query import QuerySet
from django.core import urlresolvers
def render_to_response(*args, **kwargs):
"""
Returns a HttpResponse whose content is filled with the result of calling
django.template.loader.render_to_string() with the passed arguments.
"""
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
def redirect(to, *args, **kwargs):
"""
Returns an HttpResponseRedirect to the apropriate URL for the arguments
passed.
The arguments could be:
* A model: the model's `get_absolute_url()` function will be called.
* A view name, possibly with arguments: `urlresolvers.reverse()` will
be used to reverse-resolve the name.
* A URL, which will be used as-is for the redirect location.
By default issues a temporary redirect; pass permanent=True to issue a
permanent redirect
"""
if kwargs.pop('permanent', False):
redirect_class = HttpResponsePermanentRedirect
else:
redirect_class = HttpResponseRedirect
# If it's a model, use get_absolute_url()
if hasattr(to, 'get_absolute_url'):
return redirect_class(to.get_absolute_url())
# Next try a reverse URL resolution.
try:
return redirect_class(urlresolvers.reverse(to, args=args, kwargs=kwargs))
except urlresolvers.NoReverseMatch:
# If this is a callable, re-raise.
if callable(to):
raise
# If this doesn't "feel" like a URL, re-raise.
if '/' not in to and '.' not in to:
raise
# Finally, fall back and assume it's a URL
return redirect_class(to)
def _get_queryset(klass):
"""
Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
get_object_or_404 and get_list_or_404 more DRY.
"""
if isinstance(klass, QuerySet):
return klass
elif isinstance(klass, Manager):
manager = klass
else:
manager = klass._default_manager
return manager.all()
def get_object_or_404(klass, *args, **kwargs):
"""
Uses get() to return an object, or raises a Http404 exception if the object
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Note: Like with get(), an MultipleObjectsReturned will be raised if more than one
object is found.
"""
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
def get_list_or_404(klass, *args, **kwargs):
"""
Uses filter() to return a list of objects, or raise a Http404 exception if
the list is empty.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the filter() query.
"""
queryset = _get_queryset(klass)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
return obj_list
Thanks a lot
Finaly I have deployed a virtual env (ubuntu) using virtual box.
I had absolutely no issues on the ubuntu env to deploy it and follow the steps with the exact same code as above!
Thanks for your help anyway!

dictionary update sequence element #0 has length 4; 2 is required

I'm new here and django world..
I tried to find an answer about this error, but I didn't find one that fix my problem.
urls.py
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^menu_direcao/', "academico.views.menu_direcao", name='menu_direçao'),
url(r'^menu_direcao/add_prof/', "academico.views.add_prof", name='add_prof'),
]
if settings.DEBUG:
urlpatterns += patterns('', (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),)
models.py
from django.db import models
class AddProfessor(models.Model):
nome = models.CharField(max_length=20)
sobrenome = models.CharField(max_length=100)
nascimento = models.DateField()
matricula = models.IntegerField(max_length=20)
senha = models.CharField(max_length=20)
forms.py
from django import forms
from academico.models import AddProfessor
class FormAddProfessor(forms.ModelForm):
class Meta:
model = AddProfessor
fields = 'nome', 'sobrenome', 'nascimento', 'matricula'
views.py
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from academico.models import AddProfessor
from academico.forms import FormAddProfessor
def menu(request):
return render_to_response("menu_temp.html", context_instance = RequestContext(request))
def menu_direcao(request):
return render_to_response("menu_direcao.html", context_instance = RequestContext(request))
def add_prof(request):
if request.method == "POST":
form = FormAddProfessor(request.POST, request.FILES)
if form.is_valid():
form.save()
return render_to_response("salvo.html", {})
else:
form = FormAddProfessor()
return render_to_response("add_professor.html", {'form', form}, context_instance = RequestContext(request))
template/add_prof.html
{% extends 'base.html' %}
{% block corpo %}
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Adicionar</button>
</form>
{% endblock %}
ERROR:
ValueError at /menu_direcao/add_prof/
dictionary update sequence element #0 has length 4; 2 is required
Request Method: GET
Request URL: http://127.0.0.1:8000/menu_direcao/add_prof/
Django Version: 1.8.5
Exception Type: ValueError
Exception Value:
dictionary update sequence element #0 has length 4; 2 is required
Exception Location: C:\Python34\lib\site-packages\django\template\context.py in __init__, line 20
Python Executable: C:\Python34\python.exe
Python Version: 3.4.2
Python Path:
['c:\\Python34\\Scripts\\escola',
'C:\\WINDOWS\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Dom, 18 Out 2015 12:50:21 -0200
TRACEBACK:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/menu_direcao/add_prof/
Django Version: 1.8.5
Python Version: 3.4.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'academico')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "c:\Python34\Scripts\escola\academico\views.py" in add_prof
49. context_instance = RequestContext(request))
File "C:\Python34\lib\site-packages\django\shortcuts.py" in render_to_response
45. using=using)
File "C:\Python34\lib\site-packages\django\template\loader.py" in render_to_string
115. template_name, context, context_instance, dirs, dictionary)
File "C:\Python34\lib\site-packages\django\template\engine.py" in render_to_string
220. with context_instance.push(context):
File "C:\Python34\lib\site-packages\django\template\context.py" in push
55. return ContextDict(self, *args, **kwargs)
File "C:\Python34\lib\site-packages\django\template\context.py" in __init__
20. super(ContextDict, self).__init__(*args, **kwargs)
Exception Type: ValueError at /menu_direcao/add_prof/
Exception Value: dictionary update sequence element #0 has length 4; 2 is required
So, if you can help me, I'll be very greateful.
Thanks
Try this view:
from django.shortcuts import render
def add_prof(request):
if request.method == "POST":
form = FormAddProfessor(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request, "salvo.html")
else:
form = FormAddProfessor()
return render(request, "add_professor.html", {'form': form})

unbound method must be called with instance as first argument

I'm working with django and i'm getting this error: "unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)". I've read several answers to the same problem here but i'm not sure they are doing the same thing wrong as i am.
Here is the Model containing the method i'm trying to call:
from django.db import models
class SocialUrl(models.Model):
code = models.CharField(max_length=30)
def create():
socialUrl = SocialUrl(code = generateCode())
socialUrl.save()
return socialUrl
def __unicode__(self):
return self.code
and here is the method trying to call SocialUrl.create():
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
socialUrl = SocialUrl.create()
#print(SocialUrl.objects.all())
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))
Here is the stacktrace:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/su/asdadsf
Django Version: 1.6.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'SocialUrl')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Users\Sverker\.virtualenvs\coomba\lib\site- packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sverker\Dropbox\Coomba\SbrgCoomba\SocialUrl\views.py" in test
8. socialUrl = SocialUrl.create()
Exception Type: TypeError at /su/asdadsf
Exception Value: unbound method create() must be called with SocialUrl instance as first argument (got nothing instead)
Help would be appreciated :)
You need to instantiate the class before calling a method on the class. Change your view to:
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
socialUrl = SocialUrl()
socialUrl.create()
#print(SocialUrl.objects.all())
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))
Notice how you instantiate the object first (socialUrl = SocialUrl()) then you run create on the object you've instantiated. (socialUrl.create()).
However, I'm not sure your create method is going to work as you intend. What are you trying to accomplish with the create method?
EDIT to address comments:
I'm not familiar with Java static methods, but I think the standard way to what you want to do is as follows:
First, define your model as you've done. Note that I removed the create method.
from django.db import models
class SocialUrl(models.Model):
code = models.CharField(max_length=30)
def __unicode__(self):
return self.code
Then, in your views, instantiate a model and populate it with the attributes you want.
from django.shortcuts import render
from django.template import RequestContext
from .general import generateCode
from .models import SocialUrl
def test(request):
my_code = generateCode()
socialUrl = SocialUrl()
socialUrl.code = my_code # Setting code attribute to the result of your generateCode function
socialUrl.save() # Saves instance of SocialUrl to database.
return render(request, 'test.html', RequestContext(request, {"title": socialUrl.code}))

unicode' object has no attribute 'get' in Django

I am trying to follow the [Django Tutorial 6][1] to do the user authenication. But i get stuck. I am getting this Attribute error: unicode' object has no attribute 'get'. The models,view and forms are provided below. Not sure where the error is... Need some help...
models.py
from django.db import models
from django.contrib.auth.models import User
class Drinker(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField()
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from drinker.forms import RegistrationForm
from django.contrib.auth.models import User
from drinker.models import Drinker
def DrinkerRegistration(request):
if request.POST:
form =RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],email=form.cleaned_data['email'])
password = form.cleaned_data['password']
user.save()
drinker=Drinker(user=user,name=form.cleaned_data['name'],birthday=form.cleaned_data['birthday'])
drinker.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html',{'form':form,},context_instance=RequestContext(request))
else:
form = RegistrationForm()
return render_to_response('register.html',{'form':form,},context_instance=RequestContext(request))
forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from drinker.models import Drinker
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label =(u'Email Address'))
password = forms.CharField(label =(u'Password'),widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label =(u'Verify Password'),widget=forms.PasswordInput(render_value=False))
class Meta:
model = Drinker
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken. Please select another")
def clean(self):
password = self.cleaned_data['password']
password1= self.cleaned_data['password1']
if password and password1 and password != password1:
raise forms.ValidationError("The passwords did not match. Please try again")
return password
error:
Environment:
Request Method: POST
Django Version: 1.4
Python Version: 2.7.1
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'drinker')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/cnnlakshmen_2000/Projects/Permissions/drinker/views.py" in DrinkerRegistration
12. if form.is_valid():
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
124. return self.is_bound and not bool(self.errors)
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
115. self.full_clean()
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
272. self._post_clean()
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
311. exclude = self._get_validation_exclusions()
File "/Users/cnnlakshmen_2000/Projects/env/lib/python2.7/site-packages/django/forms/models.py" in _get_validation_exclusions
297. field_value = self.cleaned_data.get(field, None)
Exception Type: AttributeError at /register/
Exception Value: 'unicode' object has no attribute 'get'
You're returning password from the clean() method, rather than self.cleaned_data.