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.
Related
I'm building a GIS-related web application, and the way it displays the contents of the database on a map is pretty straightforward: the view collects several (currently 122) GeoJSON files and passes them to the template. The template iterates all of them and displays them (using Leaflet). However, I cannot manage to make it work, as every attempt results in a Memory Error.
The database I'm using is a PostgreSQL one, in case it helps. I'm also using a TextField in the model, is it possible that to be source of the issue?
Any advice will be much appreciated :)
The view:
geodata = GeojsonData.objects.filter(connection = my_con).iterator()
view = "map"
return render(request, "map.html", {'geojsonData': geodata})
The template:
{% for dat in geojsonData %}
{% with dat.name as name %}
{% with dat.geodata as gj %}
{{gj}}
L.geoJSON(name).addTo(map);
{% endwith %}
{% endwith %}
{% endfor %}
The model:
class GeojsonData(models.Model):
name = models.CharField(max_length=2000, unique=True)
connection= models.ForeignKey(Connection, related_name='Connection', default=1)
geodata = models.TextField()
The traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/map/1/
Django Version: 1.11.4
Python Version: 3.6.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.myappConfig']
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\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "C:\Users\Xabi\Desktop\...\views.py" in mapa
92. return render(request, "map.html", {'geojsonData': geodata})
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render
31. return HttpResponse(content, content_type, status)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\http\response.py" in __init__
303. self.content = content
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\http\response.py" in content
336. content = self.make_bytes(value)
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\http\response.py" in make_bytes
247. return bytes(value.encode(self.charset))
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py" in _curried
15. return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
File "C:\Users\Xabi\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\safestring.py" in _proxy_method
107. return SafeBytes(data)
Exception Type: MemoryError at /map/1/
Exception Value:
Not sure if you've already solved your problem. But maybe instead of doing the loop in your template, you can do the loop in python and pass the end result to your template?
I am trying to call a view recursively. Below is my code.
views.py
def survey_start(request):
post = models.Post.objects.all().order_by('id')
return HttpResponseRedirect(reverse('post_form_upload',args=(post[0].id,)))
def post_form_upload(request, id):
post = get_object_or_404(models.Post, id=id)
if request.method == 'GET':
content = post.content
form = CommentModelForm(content = content)
else:
form = CommentModelForm(request.POST)
if form.is_valid():
message = form.cleaned_data['message']
created_at = form.cleaned_data['created_at']
post1 = models.Comment.objects.create(post = id,
message = message,
created_at = created_at)
return HttpResponseRedirect(reverse('post_form_upload',
args= (post.next_id,)))
return render(request, 'survey_forms/post_form_upload.html',{
'form':form,
})
urls.py
urlpatterns = [
url(r'^post/form_upload.html$',views.survey_start, name='survey_start'),
url(r'^post/(?P<id>\d+)/post_form_upload.html$',views.post_form_upload, name='post_form_upload'),
]
I have two questions.
1. I keep on getting this error. It does enter the view. I printed a counter to check.
Reverse for 'post_form_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['survey_forms/post/(?P<id>\\d+)/post_form_upload.html$']
Here is the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/survey_forms/post/1/post_form_upload.html
Django Version: 1.8.3
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'survey',
'dynamic_forms',
'crispy_forms',
'formtools',
'survey_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',
'dynamic_forms.middlewares.FormModelMiddleware')
Template error:
In template /Users/Desktop/VtStudy/python/django/2dj_proto/mysurvey/survey_forms/templates/survey_forms/post_form_upload.html, error at line 1
Reverse for 'post_form_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['survey_forms/post/(?P<id>\\d+)/post_form_upload.html$']
1 : <form action=" {% url 'post_form_upload' %} " method='post'>
2 : {% csrf_token %}
3 :
4 : {{form.as_p}}
5 : <input type='submit' value='Submit'/>
6 : </form>
Traceback:
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Desktop/VtStudy/python/django/2dj_proto/mysurvey/survey_forms/views.py" in post_form_upload
132. 'form':form,
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/shortcuts.py" in render
67. template_name, context, request=request, using=using)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/loader.py" in render_to_string
99. return template.render(context, request)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/template/backends/django.py" in render
74. return self.template.render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/base.py" in render
209. return self._render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/base.py" in _render
201. return self.nodelist.render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/template/base.py" in render
903. bit = self.render_node(node, context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/debug.py" in render_node
79. return node.render(context)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/template/defaulttags.py" in render
507. six.reraise(*exc_info)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/template/defaulttags.py" in render
493. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site- packages/django/core/urlresolvers.py" in reverse
579. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/Users/.virtualenvs/2dj_proto/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
496. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /survey_forms/post/1/post_form_upload.html
Exception Value: Reverse for 'post_form_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['survey_forms/post/(? P<id>\\d+)/post_form_upload.html$']
Each post is displayed in one single page. The user must navigate from one page to other on clicking "next". So I am calling this view post_upload_form recursively. Is this the right approach?
Thanks.
For first point: problem is in the template:
<form action=" {% url 'post_form_upload' %} " method='post'>
post_form_upload in your urls.py takes one non-empty argument, but you're not providing that in above line.
For second point: this is not an recursion, technically speaking. You are just redirecting user to next url, which is handled by same view function. And it is right approach, there is nothing wrong with that.
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
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.)
Sorry to post yet another question related to the error:
'WSGIRequest' object has no attribute 'find'
But I really can't find the answer anywhere.
I'm trying to use the django_model_comments app, which extends django's included comment app.
Did everything the page tells, however when running the server, I get the following:
Environment:
Request Method: GET
Request URL: http://localhost:8000/feed/1
Django Version: 1.4.3
Python Version: 2.7.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'model_comments',
'django.contrib.comments',
'pinax_theme_bootstrap_account',
'pinax_theme_bootstrap',
'django_forms_bootstrap',
'account',
'metron',
'user_app',
'feed_app']
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 D:\Docs\Work\repo\project\feed_app\templates\feed.html, error at line 10
'WSGIRequest' object has no attribute 'find'
1 : {% load model_comment_tags %}
2 : {% get_comment_form for feed as post_form %}
3 : {% render_comment_form post_form %}
Traceback:
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "D:\Docs\Work\repo\project\feed_app\views.py" in get_user_feed
37. 'feed': private_feed})
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\defaulttags.py" in render
281. return nodelist.render(context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "D:\Docs\Work\repo\so_virtual_env\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "D:\Docs\Work\repo\project\model_comments\templatetags\model_comment_tags.py" in render
26. return self.func(context)
File "D:\Docs\Work\repo\project\model_comments\templatetags\model_comment_tags.py" in wrap
75. form.set_request(request)
File "D:\Docs\Work\repo\project\model_comments\forms.py" in set_request
106. self.fields['from_url'].initial = unicode(Url(request))
File "D:\Docs\Work\repo\project\model_comments\url_util.py" in __init__
11. self.scheme, self.netloc, self.path, self.params, self.query_string, self.fragment = urlparse.urlparse(url)
File "C:\Python27\Lib\urlparse.py" in urlparse
134. tuple = urlsplit(url, scheme, allow_fragments)
File "C:\Python27\Lib\urlparse.py" in urlsplit
173. i = url.find(':')
Exception Type: AttributeError at /feed/1
Exception Value: 'WSGIRequest' object has no attribute 'find'
And the error happens when a templatetag is used:
html = "{% load model_comment_tags %} \
{% get_comment_form for feed as post_form %}\
{% render_comment_form post_form %}"
t = template.Template(html)
html = t.render(RequestContext(request, {'feed': private_feed}))
I've checked all my middleware, the order of apps, deleted .pyc files, and made all sorts of experiments in the template.
There's a bug in the django_model_comments library, because here they pass the HttpRequest object, not a string which is what the Url class here is expecting, so instead it should call the build_absolute_uri() method on the request object and then pass the string to the Url class.
So basically replace
unicode(Url(request))
with
unicode(Url(request.build_absolute_uri()))