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

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

Related

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 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.

'str' object has no attribute 'attname'

I am trying to display a link to the next and previous object according the title field using get_next_or_previous_by_FIELD. Django 1.6 is throwing me this error.
Error during template rendering
'str' object has no attribute 'attname'
Error occurs here in template.
{% with next_lesson=lesson.get_next_by_title %}
And here in my models.
return self._get_next_or_previous_by_FIELD('title', is_next=True)
Here is my model.
class LessonManager(models.Manager):
def all(self):
return super(LessonManager, self).filter(active=True)
class Lesson(models.Model):
active = models.BooleanField(default=False)
title = models.CharField(max_length=65)
slug = models.SlugField(unique=True)
objects = LessonManager()
def __unicode__(self, ):
return self.title
class Meta:
ordering = ['title']
def get_absolute_url(self):
return reverse('lesson', args=[str(self.slug)])
def get_next_by_title(self):
try:
return self._get_next_or_previous_by_FIELD('title', is_next=True)
except Lesson.DoesNotExist:
return None
def get_previous_by_title(self):
try:
return self._get_next_or_previous_by_FIELD(order='title', is_next=False)
except Lesson.DoesNotExist:
return None
And here is my template.
<a class="col-md-6" href="{{ lesson.get_previous_by_title.get_absolute_url }}" title="{% trans "View previous post" %}">« {{ lesson.get_previous_by_title.title }}</a>
<a class="col-md-6" href="{{ lesson.get_next_by_title.get_absolute_url }}" title="{% trans "View previous post" %}">« {{ lesson.get_next_by_title.title }}</a>
Here is the full traceback as requested.
Environment:
Request Method: GET
Request URL: /tutorials/lesson/lesson-name/
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',
'blog',
'ckeditor',
'tutorials')
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')
Template error:
In template C:\Users\Shaun\Desktop\sg\static\templates\tutorials\lesson.html, error at line 22
'str' object has no attribute 'attname'
12 : {% endif %}
13 : {% if lesson.get_next_by_timestamp %}
14 : <a class="right" href="{{ lesson.get_next_post.get_absolute_url }}">{{ lesson.get_next_post.title|truncatewords:'4' }} »</a>
15 : {% endif %}
16 :
17 : <div class='clearfix'></div>
18 :
19 : <h2>{{ lesson.title|upper }}</h2>
20 : <p>{{ lesson.content|safe }}</p>
21 :
22 : <a class="col-md-6" href=" {{ lesson.get_previous_by_title.get_absolute_url }} " title="{% trans "View previous post" %}">« {{ lesson.get_previous_by_title.title }}</a>
23 : <a class="col-md-6" href="{{ lesson.get_next_by_title.get_absolute_url }}" title="{% trans "View previous post" %}">« {{ lesson.get_next_by_title.title }}</a>
24 :
25 : {% endblock %}
Traceback:
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Shaun\Desktop\sg\src\tutorials\views.py" in single_lesson
13. return render_to_response('tutorials/lesson.html', locals(), context_instance=RequestContext(request))
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\shortcuts\__init__.py" in render_to_response
29. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\loader.py" in render_to_string
169. return t.render(context_instance)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
840. bit = self.render_node(node, context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render_node
78. return node.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\loader_tags.py" in render
123. return compiled_parent._render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
840. bit = self.render_node(node, context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render_node
78. return node.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\loader_tags.py" in render
62. result = block.nodelist.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in render
840. bit = self.render_node(node, context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render_node
78. return node.render(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\debug.py" in render
88. output = self.filter_expression.resolve(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in resolve
585. obj = self.var.resolve(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in resolve
735. value = self._resolve_lookup(context)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\template\base.py" in _resolve_lookup
789. current = current()
File "C:\Users\Shaun\Desktop\sg\src\tutorials\models.py" in get_previous_by_title
64. return self._get_next_or_previous_by_FIELD('title', is_next=False)
File "C:\Users\Shaun\Desktop\sg\lib\site-packages\django\db\models\base.py" in _get_next_or_previous_by_FIELD
708. param = force_text(getattr(self, field.attname))
Exception Type: AttributeError at /tutorials/lesson/setting-up-your-django-blog-application/
Exception Value: 'str' object has no attribute 'attname'
_get_next_or_previous_by_FIELD isn't supposed to be something you call yourself.
The main problem you're having is that it is expecting a Field object, not a string, hence the error. This is because the method is actually used as part of a curried function that is created by the field class itself, which in turn is called by the model metaclass when the model is first imported.
The currying creates the actual get_next_by_foo and get_previous_by_foo methods. In fact, these are only created for Date and Datetime fields.
Note that the uncurried method name begins with an underscore, which - with the exception of Model._meta - is a good sign that you're not supposed to be using it in your own code.

django dynamic form ValueError

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

CSRF fails when trying to upload ImageField

I have a django template with an ImageField form to allow users to upload pictures on the site.
1) The form contains {% csfr_token %}
2) I render a template with render variables.
Also, I have set enctype="multipart/form-data" in the form in the template?
Still I get a CSFR verif. fail. Can anyone help?
Code from the template.html
<form enctype="multipart/form-data" action='{% url photo username %}' method="post">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.profile_picture.label_tag }} {{ form.profile_picture.help_text }}</p>
<p>
{{ form.profile_picture.errors }}
{{ form.profile_picture }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
The view:
def upload_photo(request, nick):
#c = {}
#c.update(csrf(request))
if request.method == 'POST':
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
newpic = Picture(profile_picture = request.FILES['profile_picture'])
newpic.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('profiles.views.upload_photo', args=[nick]))
else:
form = PictureForm() # A empty, unbound form
# Load documents for the list page
pictures = Picture.objects.all()
# Render list page with the documents and the form
return render_to_response(
'profile.html',
#various render variables here
})
UPDATE:traceback
Environment:
Request Method: POST
Request URL: localhost/hello/john/
Django Version: 1.4.2
Python Version: 2.7.2
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',
'friendship',
'search',
'tour',
'profiles')
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 "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/mike/Documents/ics/django/ics/profiles/views.py" in upload_photo
18. newpic.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
551. 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
203. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1593. 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
909. for sql, params in self.as_sql():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in pre_save
249. file.save(file.name, file, save=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in save
85. name = self.field.generate_filename(self.instance, name)
File "/home/mike/Documents/ics/django/ics/profiles/models.py" in get_image_name
8. name = str(instance.user_id) + ".jpg"
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py" in __get__
343. raise self.field.rel.to.DoesNotExist
I found that the error is here (models.py):
def get_image_name(instance, filename):
return str(instance.user_id) + ".jpg"
#str(____) + ".jpg" causes the exception
class Picture(models.Model):
user_id = models.ForeignKey(User)
profile_picture = models.ImageField(storage=OverwriteStorage(), upload_to=get_image_name)
Any thoughts why this happens?
What I'm trying to do is save the image the user uploads with their username. But how can I get the user's username within the models.py?
Since you are not manually updating your context with the csrf token you must use a RequestContext in your render to response method
return render_to_response('profile.html', {
..your data dict.. }, context_instance=RequestContext(request))
Please see https://docs.djangoproject.com/en/1.2/ref/templates/api/#subclassing-context-requestcontext as well (I link to an old version of django since you still use function-style views)
EDIT:
Now that the csrf problem is fixed, you're dealing with a separate, new error. Try changing 'user_id' to 'user' (for consistency) in your Picture model and use str(instance.user.username) in your get_image_name. Even if this does not work (which it normally should), please post a new question as the original request has been answered. People could search for csrf and end up here, reading for an unrelated problem.