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

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})

Related

NoReverseMatch at /purchase_form/ Reverse for 'purchase_form' not found. 'purchase_form' is not a valid view function or pattern name

#models.py
from django.db import models
from django.utils import timezone
from django.urls import reverse,reverse_lazy,resolve
# Create your models here.
class Purchase(models.Model):
purchase_date = models.DateField()
components = models.ForeignKey(Components,on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
remarks = models.TextField(max_length=500,blank=True,null=True)
def __str__(self):
return str(self.pk)
#views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import (View, ListView, DetailView, CreateView, UpdateView, DeleteView)
from myinventory.models import Purchase
# Create your views here.
class PurchaseCreateView(CreateView):
model = Purchase
fields = '__all__'
success_url = reverse_lazy("purchase_form")
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['purchases'] = Purchase.objects.all()
return context
project urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('myinventory.urls','myinventory')),
]
app urls.py
from django.urls import path,reverse_lazy
from django.views.generic import CreateView
from myinventory import views
app_name = 'myinventory'
urlpatterns = [
path('purchase_form/', views.PurchaseCreateView.as_view(),name="purchase_form"),
]
purchase_form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Purchase</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
{% for purchase in purchases %}
<h2>{{ purchase.purchase_date }}</h2>
<h2>{{ purchase.components }}</h2>
<h2>{{ purchase.quantity }}</h2>
<h2>{{ purchase.remarks }}</h2>
{% endfor %}
</form>
</body>
</html>
admin.py
from django.contrib import admin
from myinventory.models import *
# Register your models here.
admin.site.register(Purchase)
Traceback
I'm getting following error:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/purchase_form/
Django Version: 3.1.7
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myinventory']
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 (most recent call last):
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\edit.py", line 142, in post
return self.form_valid(form)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\edit.py", line 126, in form_valid
return super().form_valid(form)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\edit.py", line 57, in form_valid
return HttpResponseRedirect(self.get_success_url())
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\views\generic\edit.py", line 11m2, in get_success_url
if self.success_url:
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\utils\functional.py", line 135, in wrapper
res = func(*self.__args, **self.__kw)
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\Hp\anaconda3\envs\MyRLXEnv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /purchase_form/
Exception Value: Reverse for 'purchase_form' not found. 'purchase_form' is not a valid view function or pattern name.
When you set app_name in your app's urls.py you namespace your urls, i.e. now whenever you want to reverse your url you should use <app_name>:<url_name>. So in your view PurchaseCreateView instead of:
success_url = reverse_lazy("purchase_form")
You should write:
success_url = reverse_lazy("myinventory:purchase_form")

Django - Render is not working in my project

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 %}

Django 1.10 / AttributeError: 'list' object has no attribute '_meta'

I got this error:
Internal Server Error: /QOP/1/editar/
Traceback (most recent call last):
...
opts = instance._meta
AttributeError: 'list' object has no attribute '_meta'
[25/Nov/2016 19:17:00] "GET /QOP/1/editar/ HTTP/1.1" 500 77572
models.py
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from django.core.urlresolvers import reverse
from modulos.modPessoas.models import Postos
# Quadro Orgânico Pessoal
class Qop(models.Model):
class Meta:
ordering = ['qop_ref']
verbose_name = 'Quadro Orgânico Pessoal'
verbose_name_plural = 'Quadro Orgânico Pessoal'
qop_ref = models.CharField(max_length=255, null=True, blank=True, verbose_name='Referência')
qop_nome = models.CharField(max_length=255, null=True, blank=True, verbose_name='QOP Nome')
qop_dt_arov = models.DateField(null=True, blank=True, verbose_name='Data de Aprovação')
qop_atv = models.BooleanField(default=True, verbose_name='Ativo?')
def __str__(self):
return '{} {}'.format(self.qop_ref, self.qop_nome)
def get_absulute_url(self):
return reverse("QOP:detalhe", kwargs={"pk": self.id})
views.py
def qop_editar(request, pk=None):
instance = get_list_or_404(Qop, id=pk)
form = QopForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
contexto = {
"titulo": "QOP Editar",
"instance": instance,
"form": form
}
return render(request, "modQOP/editar.html", contexto)
urls.py
from django.conf.urls import url
from .views import (index,
qop_lista,
qop_detalhe,
qop_criar,
qop_editar)
urlpatterns = [
url(r'^$', index),
url(r'^criar/$', qop_criar),
url(r'^lista/$', qop_lista),
url(r'^(?P<pk>\d+)/detalhe/$', qop_detalhe, name='detalhe'),
url(r'^(?P<pk>\d+)/editar/$', qop_editar, name='editar'),
]
template
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
Nome: {{ form.qop_nome }}<br>
Nº de Referência: {{ form.qop_ref }}<br>
Data de Aprovação: {{ form.qop_dt_arov }}<br>
Ativo? {{ form.qop_atv }}<br>
<button type="submit" class="button">Guardar</button>
</form>
What is wrong with code?
Thanks in advance!
edit:
Full traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/QOP/1/editar/
Django Version: 1.10.3
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'smart_selects',
'modulos.modAutenticacao',
'modulos.modQOP',
'modulos.modPessoas']
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 "C:\Users\Filipe\envRTm\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Users\Filipe\envRTm\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Filipe\envRTm\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Filipe\Documents\GitHub\rhead\modulos\modQOP\views.py" in qop_editar
36. form = QopForm(request.POST or None, request.FILES or None, instance=instance)
File "C:\Users\Filipe\envRTm\lib\site-packages\django\forms\models.py" in __init__
282. object_data = model_to_dict(instance, opts.fields, opts.exclude)
File "C:\Users\Filipe\envRTm\lib\site-packages\django\forms\models.py" in model_to_dict
87. opts = instance._meta
Exception Type: AttributeError at /QOP/1/editar/
Exception Value: 'list' object has no attribute '_meta'
You can't pass the result from get_list_or_404 to a ModelForm instance as it will return an QuerySet. You need to use get_object_or_404 to return an instance of the model.

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" />

adding new registered users to the database and their login system in django

i have created a form in which the user enters data and that data is saved onto the database.but the form is not s![enter image description here][1]aving the data is there any wrong in the coding?please help..
my code is here:-
1) views.py
-----------------------------------------------------------
from django.http import HttpResponse
#from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from forms import SignupForm
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
form.cleaned_data('username')
form.cleaned_data('email')
form.cleaned_data('password1')
form.save()
return HttpResponse('/login/') #havent did the login method yet...
else:
t = loader.get_template('signup.html')
cform = SignupForm()
c = RequestContext (request, {'form' : cform,})
return HttpResponse(t.render(c))
#def login(request):
# newform = SignupForm()
#if newform.is_valid():
2) forms.py-
from django.contrib.auth.models import User
from django import forms
class SignupForm(forms.Form):
username = forms.CharField(max_length=255, label="Username")
email = forms.CharField(max_length=255, label="E-Mail Address")
password1 = forms.CharField(max_length=255, label="Password", widget=forms.PasswordInput)
password2 = forms.CharField(max_length=255, label="Repeat Password", widget=forms.PasswordInput)
def clean_username(self):
try:
User.objects.get(username=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError("This username is already in use.Please choose another.")
def clean(self):
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("You must type the same password each time")
return self.cleaned_data
def save(self):
new_user = User.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1'])
return new_user
3)urls.py:-
from django.conf.urls import patterns, include, url
from django.contrib import admin
#from salary import settings
#from salarylive.views import signup
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'salary.views.home', name='home'),
#url(r'^salary/', include('salary.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^signup/$', 'salarylive.views.signup'),
#url(r'^login/$', 'salarylive.views.login'),
)
error traceback :-
error traceback :- Environment:
Request Method: POST
Request URL: http://localhost:8000/signup/
Django Version: 1.4.3
Python Version: 2.7.0
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'salarylive')
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 "c:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "e:\Software Installations\Aptana Workspace\salary\salarylive\views.py" in signup
10. form.cleaned_data('username')
Exception Type: TypeError at /signup/
Exception Value: 'dict' object is not callable
You have some indentation errors. The first return HttpResponse should be indented one additional level, so that it only happens if the form is valid. The second return HttpResponse and the line above it should be indented one less level, so that it catches the fall-through from the if statement.
The way you have it, the code always redirects, even if the form is not valid and the data is not saved. With those changes, the second return will re-render the form with errors when it is not valid.