django dynamic form ValueError - django

I want to get the select form which can display all the users who have the group name "sale".
My definition for my forms is like this:
class ArrangeUserForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ArrangeUserForm, self).__init__(*args, **kwargs)
user_choices = []
for user in User.objects.all():
if user.groups.filter(name="sale"):
user_choices.append(user.first_name)
self.fields['user_field'] = forms.ChoiceField(widget=forms.Select, choices=user_choices)
mobile = forms.CharField(widget=forms.TextInput, max_length=11, min_length=11)
and my view is like this:
class ArrangeUserHandler(View):
def get(self, request):
form = ArrangeUserForm()
return render(request, 'student/student_form.html', {'form': form,})
def post(self, request):
pass
when I run my code and request for that view, I got the following error:
ValueError at /student/arrangeuser/
too many values to unpack
could anyone told me what's going wrong here?
Traceback:
request Method: GET
Request URL: http://domain/student/arrangeuser/
Django Version: 1.5
Python Version: 2.7.3
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',
'accounts',
'student',
'order')
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')
Template error:
In template /home/rogerliu/newproject/crm/templates/student/student_form.html, error at line 7
too many values to unpack
1 :
2 : <form method="post">
3 : {% csrf_token %}
4 : {% for field in form %}
5 : <div class="fieldWrapper">
6 : {{ field.errors }}
7 : {{ field.label_tag }}: {{ field }}
8 : </div>
9 : {% endfor %}
10 : <input type="submit" value="submit" />
11 :
12 : </form>
13 :
14 :
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = 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/views/generic/base.py" in dispatch
86. return handler(request, *args, **kwargs)
File "/home/rogerliu/newproject/crm/student/views.py" in get
318. return render(request, 'student/student_form.html', {'form': form,})
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
177. return t.render(context_instance)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
140. return self._render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in _render
134. return self.nodelist.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/base.py" in render
830. bit = self.render_node(node, context)
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render_node
74. return node.render(context)
File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py" in render
188. nodelist.append(node.render(context))
File "/usr/local/lib/python2.7/dist-packages/django/template/debug.py" in render
87. output = force_text(output)
File "/usr/local/lib/python2.7/dist-packages/django/utils/encoding.py" in force_text
99. s = s.__unicode__()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in __str__
411. return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
458. return widget.render(name, self.value(), attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render
555. options = self.render_options(choices, [value])
File "/usr/local/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
579. for option_value, option_label in chain(self.choices, choices):
Exception Type: ValueError at /student/arrangeuser/
Exception Value: too many values to unpack
~

As per my comment, choices needs to be a key, value mapping, use:
tuple(enumerate(user_choices))

My questions are: How did you define your models?
Can you get the users from the group?
Can you get the groups from the user?
something like that:
groups = Group.objects.get(pk=1)
groups.users
user = User.objects.get(pk=1)
user.groups
You can do that writing this in you code:
#models.py
class User(Model):
name = CharField(max_length=200)
class Group(Model):
name = CharField(max_length=200)
users = ManyToManyField(User, related_name="groups")
#forms.py
class ArrangeUserForm(forms.Form):
def __init__(self, *args, **kwargs):
super(ArrangeUserForm, self).__init__(*args, **kwargs)
groups = groups.objects.filter(name="sale")
user_choices = User.objects.filter(groups_in=groups)
self.fields['user_field'] = forms.ChoiceField(widget=forms.Select, choices=user_choices)
mobile = forms.CharField(widget=forms.TextInput, max_length=11, min_length=11)
#And you views.py
class ArrangeUserHandler(FormView):
form_class = ArrangeUserForm
template_name = 'student/student_form.html'
def form_valid(self, form):
#When the form is valid
return super(ArrangeUserHandler, self).form_valid(form)
def form_invalid(self, form):
#When the form is invalid
return super(ArrangeUserHandler, self).form_invalid(form)
I think that It should work fine and quickly.
Will you tell me if this lines work?
# ...
groups = groups.objects.filter(name="sale")
user_choices = User.objects.filter(groups_in=groups)
# ...
I hope that helps.
see the Documentation of ManyToMany field and
FormView if you are in django 1.5

Related

AttributeError at /tickets/ticket/1/like/ 'str' object has no attribute 'fields'

I have a url that is called when a button is pressed but I am getting an attribute error. The strange thing is I only get the attribute error when I run my app on Heroku, when it is running locally I don't get any errors at all. I have checked and heroku is running my latest code in github so I am really confused as to what is happening here!
Traceback:
Environment:
Request Method: GET
Request URL: https://dm-issuetracker.herokuapp.com/tickets/ticket/1/like/
Django Version: 1.11
Python Version: 3.6.12
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_forms_bootstrap',
'accounts',
'tickets',
'checkout']
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',
'whitenoise.middleware.WhiteNoiseMiddleware']
Template error:
In template /app/templates/base.html, error at line 0
'str' object has no attribute 'fields' 1 : {% load staticfiles %}
2 :
3 : <html>
4 :
5 : <head>
6 : <meta charset="UTF-8">
7 : <meta name="viewport" content="width=device-width, initial-scale=1.0">
8 : <meta http-equiv="X-UA-Compatible" content="ie=edge">
9 : <title>IssueTracker{% block page_title %}{% endblock %}</title>
10 : <link rel="icon" href="media/img/bug.jpg">
Traceback:
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/tickets/views.py" in ticket_vote
71. return render(request, "ticketdetail.html", {'ticket':ticket})
File "/app/.heroku/python/lib/python3.6/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py" in render
66. return self.template.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
207. return self._render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/loader_tags.py" in render
177. return compiled_parent._render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in _render
199. return self.nodelist.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/loader_tags.py" in render
72. result = block.nodelist.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/defaulttags.py" in render
322. return nodelist.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
990. bit = node.render_annotated(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render_annotated
957. return self.render(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in render
1040. output = self.filter_expression.resolve(context)
File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in resolve
736. new_obj = func(obj, *arg_vals)
File "/app/.heroku/python/lib/python3.6/site-packages/django_forms_bootstrap/templatetags/bootstrap_tags.py" in as_bootstrap_inline
41. form = _preprocess_fields(form)
File "/app/.heroku/python/lib/python3.6/site-packages/django_forms_bootstrap/templatetags/bootstrap_tags.py" in _preprocess_fields
17. for field in form.fields:
Exception Type: AttributeError at /tickets/ticket/1/like/
Exception Value: 'str' object has no attribute 'fields'
Here is urls.py:
from django.conf.urls import url
from .views import get_tickets, ticket_detail, create_or_edit_ticket, ticket_vote, ticket_vote_list
urlpatterns = [
url(r'^$', get_tickets, name='get_tickets'),
url(r'^(?P<pk>\d+)/$', ticket_detail, name = 'ticket_detail'),
url(r'^(?P<pk>\d+)/$', ticket_vote, name = 'ticket_vote'),
url(r'^tickets/(?P<pk>[0-9]+)/like/$', ticket_vote_list, name='ticket_vote_list'),
url(r'^ticket/(?P<pk>[0-9]+)/like/$', ticket_vote, name='ticket_vote'),
url(r'^new/$', create_or_edit_ticket, name = 'new_ticket'),
url(r'^(?P<pk>\d+)/edit/$', create_or_edit_ticket, name = 'edit_ticket')
]
urls.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Ticket
from .forms import TicketsForm, TicketCommentForm
def get_tickets(request):
"""
Create a view that will return a list of tickets that were published and
render them to 'issuetrackertickets.html' template
"""
tickets = Ticket.objects.filter(published_date__lte=timezone.now
())
return render(request, "issuetrackertickets.html", {'tickets':tickets})
def ticket_detail(request,pk):
"""
Create a view that will return a single ticket object based on the ticket id
and render it to the 'ticketdetail.html' template
"""
print("ticket detail")
ticket = get_object_or_404(Ticket,pk=pk)
ticket.views +=1
ticket.save()
# Display comments
comments = ticket.ticketcomment_set.all().order_by('comment_date')
# Form for adding a comment
if request.method == 'POST' and request.POST.get('submit'):
comment_form = TicketCommentForm(request.POST, request.FILES)
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.author = request.user.username
comment.ticket = ticket
comment.save()
return redirect(ticket_detail, pk=ticket.pk)
# Form for upvoting tickets
elif request.method == 'POST' and not request.POST.get('submit'):
comment_form = TicketCommentForm()
else:
comment_form = TicketCommentForm()
return render(request, 'ticketdetail.html', {'ticket': ticket, 'comments': comments, 'comment_form': comment_form})
#login_required
def create_or_edit_ticket(request, pk=None):
"""
Create a view that allows us to create or edit a ticket depending if
the tickets id is null or not.
"""
ticket = get_object_or_404(Ticket, pk=pk) if pk else None
if request.method == "POST":
form = TicketsForm(request.POST, request.FILES, instance=ticket)
if form.is_valid():
ticket = form.save()
ticket.author = request.user.username
return redirect(ticket_detail, ticket.pk)
else:
form = TicketsForm(instance=ticket)
return render(request, "issuetrackerticketform.html", {'form':form})
def ticket_vote(request,pk):
"""
Create a view that will increase the upvotes for the current ticket
and render it to the 'ticketdetail.html' template
"""
print("ticket_vote")
ticket = get_object_or_404(Ticket,pk=pk)
ticket.upvotes +=1
ticket.save()
return render(request, "ticketdetail.html", {'ticket':ticket})
def ticket_vote_list(request,pk):
"""
Create a view that will increase the upvotes for the current ticket in the list
and render it to the 'ticketdetail.html' template
"""
print("ticket_vote_list")
ticket = get_object_or_404(Ticket,pk=pk)
ticket.upvotes +=1
ticket.save()
tickets = Ticket.objects.filter(published_date__lte=timezone.now
())
return render(request, "issuetrackertickets.html", {'tickets':tickets})
models.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Ticket(models.Model):
"""
Add a ticket
"""
TYPE_CHOICES = (
('BUG', 'Bug'),
('NEW_FEATURE', 'New feature')
)
STATUS_CHOICES = (
('TO_DO', 'To do'),
('UNDER_REVIEW', 'Under Review'),
('DECLINED', 'Declined'),
('PLANNED', 'Planned'),
('IN_PROGRESS', 'In Progress'),
('COMPLETED', 'Completed')
)
title = models.CharField(max_length=225,blank=False)
author = models.CharField(max_length=150, default='')
content = models.TextField()
ticket_type = models.CharField(choices=TYPE_CHOICES, default='BUG', max_length=11)
created_date = models.DateTimeField(auto_now_add=True)
published_date = models.DateTimeField(blank=True, null=True, default=timezone.now)
views = models.IntegerField(default=0)
upvotes = models.IntegerField(default=0)
image = models.ImageField(upload_to="img", blank=True, null=True)
status = models.CharField(choices=STATUS_CHOICES, default='TO_DO', max_length=12)
def __unicode__(self):
return self.title
class TicketComment(models.Model):
"""Model that can create comments"""
author = models.CharField(max_length=150, default='')
comment = models.TextField(blank=False)
comment_date = models.DateTimeField(auto_now_add=True)
ticket = models.ForeignKey(Ticket, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.author

Django Error while saving avatar : expected str, bytes or os.PathLike object, not NoneType

there is an error on cleaned_data['avatar'] (in forms.py) : expected str, bytes or os.PathLike object, not NoneType
this error appears when I sign in with an image for avatar.
I m using Django-allauth but not used to it.... So I add an avatar field which appears in sign_in form but I've the error when submitting.
this is my code: models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
def get_path_name(instance, filename):
path = 'media/avatar/'
name = instance.user.id + "-" + instance.user.email
path = path + name
return path
# custom User model
class CustomUser(AbstractUser):
avatar = models.ImageField(upload_to= get_path_name, blank=True, null=True)
my form:
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.core.files.images import get_image_dimensions
from django import forms
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ('email', 'username', 'avatar')
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
w, h = get_image_dimensions(avatar)
# validate dimensions
max_width = max_height = 100
if w > max_width or h > max_height:
raise forms.ValidationError(
u'Please use an image that is '
'%s x %s pixels or smaller.' % (max_width, max_height))
# validate content type
main, sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
raise forms.ValidationError(u'Please use a JPEG, '
'GIF or PNG image.')
# validate file size
if len(avatar) > (20 * 1024):
raise forms.ValidationError(
u'Avatar file size may not exceed 20k.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return avatar
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = get_user_model()
fields = ('email', 'username', 'avatar')
my template:
{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% block title %}
{% endblock title %}
{% block content %}
<h2>Sign Up</h2>
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-success" type="submit">Sign Up</button>
</form>
{% endblock content %}
my settings:
AUTH_USER_MODEL = 'accounts.CustomUser'
I've check that migrations works as I can see field in database. But of course empty du to previous error.
I've another issue is that avatar field does not appears in /admin/change/user but I put the field in CustomUserChangeForm(UserChangeForm):
and this is my admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
from .forms import CustomUserCreationForm, CustomUserChangeForm
CustomUser = get_user_model()
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
list_display = ['email', 'username', 'avatar']
admin.site.register(CustomUser, CustomUserAdmin)
error traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/accounts/signup/
Django Version: 3.1.2
Python Version: 3.7.7
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap4',
'crispy_forms',
'allauth',
'allauth.account',
'django.contrib.sites',
'accounts',
'home']
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 "/Users/hima/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/hima/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 215, in dispatch
return super(SignupView, self).dispatch(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 81, in dispatch
**kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 193, in dispatch
**kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch
return handler(request, *args, **kwargs)
File "/Users//hima/venv/lib/python3.7/site-packages/allauth/account/views.py", line 103, in post
if form.is_valid():
File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 177, in is_valid
return self.is_bound and not self.errors
File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 172, in errors
self.full_clean()
File "/Users//hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 374, in full_clean
self._clean_fields()
File "/Users/hima/venv/lib/python3.7/site-packages/django/forms/forms.py", line 395, in _clean_fields
value = getattr(self, 'clean_%s' % name)()
File "/Users//hima/accounts/forms.py", line 15, in clean_avatar
w, h = get_image_dimensions(avatar)
File "/Users/hima/venv/lib/python3.7/site-packages/django/core/files/images.py", line 47, in get_image_dimensions
file = open(file_or_path, 'rb')
Exception Type: TypeError at /accounts/signup/
Exception Value: expected str, bytes or os.PathLike object, not NoneType

django how to add a MinLengthValidator validator in a form

I have a search form and I want to validate that the input 'seach_word' has at least 4 letters. I'm getting this error when I'm trying to validate my forms
The response content must be rendered before it can be iterated over.
#views.py
class SearchFormView(FormView):
form_class = PostSearchForm
template_name = 'lineup/post_search.html'
def form_valid(self, form):
schWord = form.cleaned_data['search_word']
search_type = form.cleaned_data['search_type']
context = {}
if search_type == 'store':
post_list = Store.objects.filter(
Q(cie_name__icontains=schWord)).distinct()
context['object_type'] = 'store'
context['object_list'] = post_list
if search_type == 'city':
post_list = Address.objects.filter(
Q(city__icontains=schWord)).distinct()
context['object_type'] = 'city'
context['object_list'] = post_list
context['form'] = form
context['search_term'] = schWord
return render(self.request, self.template_name, context)
def form_invalid(self, form):
schWord = form.cleaned_data['search_word']
messages.add_message(
self.request, messages.WARNING, _('Please correct this...'))
context = super(SearchFormView, self).form_invalid(form)
return render(self.request, self.template_name, context)
content of forms.py
#forms.py
class PostSearchForm(forms.Form):
SEARCH_TYPE_CHOICES = (
('city', 'city'),
('store', 'store'),
('product', 'product'),
)
search_type = forms.ChoiceField(choices=SEARCH_TYPE_CHOICES, required=True)
search_word = forms.CharField(label='Search Word',
validators=[MinLengthValidator(4)], required=True)
'''
def clean_search_word(self):
cd = self.cleaned_data
if len(cd['search_word']) < 4:
raise forms.ValidationError('too short.')
return cd['search_word']
'''
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Fieldset(
'',
Field('search_type', css_class='span6'),
Field('search_word', css_class='span6'),
),
FormActions(
Submit('submit', 'Go', css_class='btn btn-primary')
)
)
super(PostSearchForm, self).__init__(*args, **kwargs)
tracenack
Environment:
Request Method: POST
Request URL: http://localhost:8000/search/
Django Version: 1.10.3
Python Version: 3.5.2
Installed Applications:
['grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'debug_toolbar',
'stripe',
'vote',
'django_messages',
'pinax.notifications',
'admin_honeypot',
'easy_thumbnails',
'django_extensions',
'crispy_forms',
'datetimewidget',
'lineup',
'allauth',
'allauth.account',
'allauth.socialaccount']
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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.locale.LocaleMiddleware']
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/views/generic/edit.py" in post
185. return self.form_invalid(form)
File "/home/laptopguy/Documents/lineupNovember/lineup/views.py" in form_invalid
58. return render(self.request, self.template_name, context)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
68. return template.render(context, request)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/backends/django.py" in render
64. context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in make_context
267. context.push(original_context)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in push
59. return ContextDict(self, *dicts, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/context.py" in __init__
18. super(ContextDict, self).__init__(*args, **kwargs)
File "/home/laptopguy/Documents/lineupNovember/python3env/lib/python3.5/site-packages/django/template/response.py" in __iter__
123. 'The response content must be rendered before it can be iterated over.'
Exception Type: ContentNotRenderedError at /search/
Exception Value: The response content must be rendered before it can be iterated over.
The traceback shows that your problem is in your form_invalid method. You are capturing the result from the superclass call as context, and passing it into the render function. But the superclass method returns a response, not a context - it has already rendered the template for you, you just need to return it.
def form_invalid(self, form):
schWord = form.cleaned_data['search_word']
messages.add_message(
self.request, messages.WARNING, _('Please correct this...'))
return super(SearchFormView, self).form_invalid(form)

Django Crispy Forms Rendering Issue 'cannot convert dictionary update sequence element #0 to a sequence'

Struggling to figure this one out. I've seen several issues where this error code shows up but all seem to have to do with data not being passed into the context for the template to render. I know my data is getting through to the template. Crispy forms must be doing something behind the scenes that is throwing me off? Weird thing is this literally worked 20 minutes ago. I don't know what I could have changed that would have affected this.
Here is my view:
class ContactListView(View):
template = 'support_tracker/contact_list.html'
def get(self,request,*args,**kwargs):
staff_id = kwargs.pop('staff_id',False)
if staff_id:
staff = Staff.objects.get(pk=staff_id)
else:
staff = request.user.staff
contact_list = staff.contacts.all()
search_term = request.GET.get('search_term',False)
sort_by = request.GET.get('sort_by',False)
filter_by = request.GET.get('filter_by',False)
##applying search term to determine contact_list
...
##
##sorting of contact_list
....
##
##filtering of contact_list
....
##
search_form = SearchForm()
sort_form = ContactListSortForm()
filter_form = FilterByStageForm()
##pagination to determine contacts
...
##
context = {
'staff':staff,
'contacts':contacts,
'search_form':search_form,
'sort_form':sort_form,
'filter_form':filter_form,
'filter_by':filter_by,
'search_term':search_term,
'sort_by':sort_by,
}
print context
return render(request,self.template,context)
My Forms:
##forms.py
class SearchForm(forms.Form):
search_term = forms.CharField(max_length=30,label='')
def __init__(self,*args,**kwargs):
super(SearchForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-inline'
self.helper.form_method = 'GET'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
InlineField('search_term',placeholder='Search'),
Submit('','Go',css_class='btn btn-primary'),
)
class FilterByStageForm(forms.Form):
filter_by = forms.ChoiceField(choices=get_stage_option_list(),required=False)
def __init__(self,*args,**kwargs):
super(FilterByStageForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-inline'
self.helper.form_method = 'GET'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
InlineField('filter_by',placeholder='Filter By'),
Submit('','Filter',css_class='btn btn-primary'),
)
class ContactListSortForm(forms.Form):
sort_by = forms.ChoiceField(choices=(##options),required=False)
def __init__(self,*args,**kwargs):
super(ContactListSortForm,self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-inline'
self.helper.form_method = 'GET'
self.helper.field_template = 'bootstrap3/layout/inline_field.html'
self.helper.layout = Layout(
InlineField('sort_by',placeholder='Sort By'),
Submit('','Sort',css_class='btn btn-primary'),
)
My template:
{% extends 'co_tools/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class='container'>
<div class='col-md-3 well'>
<h3><u>Search:</u></h3>
## This is the part that trips it up. If I take the forms out, the rest of the page loads fine
{% crispy search_form %}
{% crispy sort_form %}
{% crispy filter_form %}
<a href='/support/new_contact/' class='btn btn-primary'>New Contact</a>
</div>
...body...
</div>
{% endblock content %}
The full traceback
Request Method: GET
Request URL: http://127.0.0.1:8000/support/contact_list/
Django Version: 1.10.2
Python Version: 2.7.11
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'support_tracker',
'donor_reports',
'staff',
'financial_reports']
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']
Template error:
In template C:\...\project\support_tracker\templates\support_tracker\contact_list.html, error at line 8
cannot convert dictionary update sequence element #0 to a sequence 1 : {% extends 'co_tools/base.html' %}
2 : {% load crispy_forms_tags %}
3 :
4 : {% block content %}
5 : <div class='container'>
6 : <div class='col-md-3 well'>
7 : <h3><u>Search:</u></h3>
8 : {% crispy form %}
9 : <a href='/support/new_contact/' class='btn btn-primary'>New Contact</a>
10 : </div>
11 : <div class='col-md-9'>
12 : <table class='table table-condensed table-hover'>
13 : <thead>
14 : <th>Contact Name</th>
15 : <th>Phone Number</th>
16 : <th>Email</th>
17 : <th>Street Address</th>
18 : <th>City</th>
Traceback:
File "C:\...\project\env\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\...\project\env\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\...\project\env\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\...\project\env\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\...\project\env\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\...\project\support_tracker\views.py" in get
185. return render(request,self.template,context)
File "C:\...\project\env\lib\site-packages\django\shortcuts.py" in render
30. content = loader.render_to_string(template_name, context, request, using=using)
File "C:\...\project\env\lib\site-packages\django\template\loader.py" in render_to_string
68. return template.render(context, request)
File "C:\...\project\env\lib\site-packages\django\template\backends\django.py" in render
66. return self.template.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
208. return self._render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
994. bit = node.render_annotated(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render_annotated
961. return self.render(context)
File "C:\...\project\env\lib\site-packages\django\template\loader_tags.py" in render
174. return compiled_parent._render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in _render
199. return self.nodelist.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
994. bit = node.render_annotated(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render_annotated
961. return self.render(context)
File "C:\...\project\env\lib\site-packages\django\template\loader_tags.py" in render
70. result = block.nodelist.render(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render
994. bit = node.render_annotated(context)
File "C:\...\project\env\lib\site-packages\django\template\base.py" in render_annotated
961. return self.render(context)
File "C:\...\project\env\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py" in render
215. c = self.get_render(context)
File "C:\...\project\env\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py" in get_render
126. response_dict = self.get_response_dict(helper, context, is_formset)
File "C:\...\project\env\lib\site-packages\crispy_forms\templatetags\crispy_forms_tags.py" in get_response_dict
160. attrs = helper.get_attributes(template_pack=self.template_pack)
File "C:\...\project\env\lib\site-packages\crispy_forms\helper.py" in get_attributes
364. if self.form_action:
File "C:\...\project\env\lib\site-packages\crispy_forms\helper.py" in form_action
237. return reverse(self._form_action)
File "C:\...\project\env\lib\site-packages\django\urls\base.py" in reverse
91. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "C:\...\project\env\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
344. self._populate()
File "C:\...\project\env\lib\site-packages\django\urls\resolvers.py" in _populate
217. dict(defaults, **pattern.default_kwargs),
Exception Type: TypeError at /support/contact_list/
Exception Value: cannot convert dictionary update sequence element #0 to a sequence
I have no idea what is causing this. Any help would be greatly appreciated.
Ok solved the issue. I have no clue why this particular bit of code was causing the problem though.
In my urls.py, I had added the following four url expressions...
from django.conf.urls import url, include
import views
urlpatterns = [
...
#meeting urls
url(r'^record_meeting/(?P<meeting_id>[0-9]+)/',views.EditMeetingView.as_view(),{'record':True}),
url(r'^record_meeting/$',views.EditMeetingView.as_view(),{'record':True}),
url(r'^edit_meeting/(?P<meeting_id>[0-9]+)/',views.EditMeetingView.as_view(),{'record':False}),
url(r'^add_meeting/$',views.EditMeetingView.as_view()),
]
The fourth one was originally url(r'^add_meeting/$',views.EditMeetingView.as_view(),{'record':False}), which apparently, based on trial and error, was causing the issue. After removing the additional arguments, the problem went away. Does anyone know why this was an issue in the first place? I still don't understand.

Django IntegrityError (1048, "Column 'network_id' cannot be null")

Ok, so i searched high and low for this, and both the docs, and almost every page on google tells me my code should be legit.
Let me start with models.py:
class Network(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=500)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.id
class NetworkForm(ModelForm):
class Meta:
model = Network
class Range(models.Model):
network = models.ForeignKey(Network)
range_start = models.GenericIPAddressField(unpack_ipv4=True)
range_end = models.GenericIPAddressField(unpack_ipv4=True)
range_title = models.CharField(max_length=50)
range_description = models.CharField(max_length=300)
def __unicode__(self):
return self.range_title
class RangeForm(ModelForm):
class Meta:
model = Range
exclude = ('network',)
Then my views.py:
#login_required(login_url='/login/')
def add_network(request):
if request.method == "POST":
net_form = NetworkForm(request.POST)
range_formset = RangeForm(request.POST)
if net_form.is_valid and range_formset.is_valid:
net_form.save(commit=False)
range_formset.network = net_form
range_formset.save()
net_form.save()
return HttpResponseRedirect('/')
else:
net_form = NetworkForm()
range_form = RangeForm()
return render_to_response('networks/add.html', {
"net_form": net_form,
"range_form": range_form,
}, context_instance=RequestContext(request))
And my template:
{% extends 'base.html' %}
{% block title %}Add Network{% endblock %}
{% block content %}
<div class="row-fluid">
<div class="span7 offset2 well">
<h3>Add network:</h3>
<hr />
<form class="form-horizontal" method="post" action="">
{% csrf_token %}
{{ net_form }}
<h4>Add a range to the network:</h4>
<hr />
<div class="form-inline">
{{ range_form }}
</div>
<hr />
<button type="submit" class="btn btn-primary btn-large">Add network</button>
</form>
</div>
</div>
{% endblock %}
Now, there most be something obvious i'm missing here, just failing to make the last connection. If somebody could enlighten me that would be great.
PS: In case anybody wondered i validated my model by looking in MySQL Workbench, MySQL Commandline client, and manage.py dbshell and inspectdb, all id columns are present. I even dropped the whole db and recreated it with manage.py.
Its been grinding my gears for about a week now, so time to ask for help. If anybody would be so kind to help me solve this, it would be great!
Here is the traceback:
Environment:
Request Method: POST
Request URL: http://localhost:8000/network/add/
Django Version: 1.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django_nose',
'networks')
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',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/home/alexander/PycharmProjects/NOC/networks/views.py" in add_network
29. range_form.save()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save
370. fail_message, commit, construct=False)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save_instance
87. instance.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
546. force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
650. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
215. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1673. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
937. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
41. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
127. six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
120. return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py" in execute
174. self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py" in defaulterrorhandler
36. raise errorclass, errorvalue
Exception Type: IntegrityError at /network/add/
Exception Value: (1048, "Column 'network_id' cannot be null")
You have at least four errors.
Firstly, you have to actually call is_valid: it is a method, not a property.
Secondly, form.save(commit=False) returns the model instance. It doesn't magically convert the form object into an instance. You need to assign it to a variable which you then set the extra attributes on.
Thirdly, you're doing the commit=False on the wrong object - you should be doing it on the one you subsequently want to modify.
Fourth, don't redirect unless the forms are valid.
So:
range_form = RangeForm(request.POST)
if net_form.is_valid() and range_form.is_valid():
net_obj = net_form.save()
range_obj = range_form.save(commit=False)
range_obj.network = net_obj
range_obj.save()
return HttpResponseRedirect('/')
else:
net_form = NetworkForm()
range_form = RangeForm()
return render_to_response('networks/add.html', {
"net_form": net_form,
"range_form": range_form,
}, context_instance=RequestContext(request))
(And don't call things formsets when they're not, they're just forms. Except that of course you actually should probably be using inline formsets for the range forms, but that's a separate question.)