Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django inlineformset - 'CapForm' object has no attribute 'cleaned_data'
I am facing attribute error, 'CapForm' object has no attribute 'cleaned_data' This is my post method def post(self,request,*args,**kwargs): user = request.user.id form = SesForm(request.POST,request.FILES,user=request.user) if form.is_valid(): frm = form.save(commit=False) frm.user = request.user frm.status = False obj = frm.save() cap_formset = CapFormSet(request.POST) cap_formset.instance = frm # Tried obj also it throws - 'NoneType' object has no attribute '_state' cap_formset.save() Can any one help me pointing where the issue is -
Django 1.10: Error Installing django_debug_toolbar
I'm trying to install django-debug-toolbar Whenever I add the middleware in the settings, I'm getting the following error: File "<project_path>/.env/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 153, in __init__ self.load_middleware() File "<project_path>/.env/lib/python3.5/site-packages/django/core/handlers/base.py", line 82, in load_middleware mw_instance = middleware(handler) TypeError: __init__() takes 1 positional argument but 2 were given my settings.py contains all the necessary stuff: INSTALLED_APPS = [ #... 'django.contrib.staticfiles', 'debug_toolbar', #... ] MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', #.... #.... ] MIDDLEWARE_CLASSES = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] -
DRF - serializer is no defined
I try to make a serializer that containts several models. My serializers.py looks like this class ProfilePicSerializer(ModelSerializer): class Meta: model = ProfilePic fields = [ 'profilePic' ] class ProfileFieldsSerializer(ModelSerializer): class Meta: model = ProfileFields fields = [ 'user', 'title', 'text', 'order' ] And i try to make a serializer that will contain user, profilepic and profile field doing it like so class UserSerializer(ModelSerializer): profile = ProfileSerializer(many=False) profile_pic = ProfilePicSerializer(many=False) profile_fields = ProfileFieldsSerializer(many=True) class Meta: model = User fields = [ 'id', 'username', 'password', 'email', 'profile' ] write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], ) user.set_password(validated_data['password']) user.save() return user But I get error NameError: name 'ProfilePicSerializer' is not defined What Am I doing wrong ? -
Switching database backend in Mezzanine
I am trying to script a series of examples where the reader incrementally builds a web application. The first stage takes place with Mezzanine's default configuration, using built-in SQLlite: sudo pip install mezzanine sudo -u mezzanine python manage.py createdb After the initial examples are complete, I want to switch the existing setup to a mysql backend. If that is too complex, I at least want to re-create the built-in examples that come with Mezzanine on the new backend, but Mezzanine won't allow re-running createdb CommandError: Database already created, you probably want the migrate command This seems like something that should be incredibly simple, yet I can't seem to get it quite right (and migrate alone did not do the trick). Google and official docs not helping either. -
Mezzanine gallery images not found in search
I would like the mezzanine search engine to find also results for the images uploaded into the gallery (there is a description field when uploading images).. but what I type in the description field its not on the search results... -
ImportError: No module named app.views django 1.10 python
I just have started learning django in its 1.10 version. In a project (called refugio) I have created an app called mascota. This is my views.py file for my app: from __future__ import unicode_literals, absolute_import from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Index") Also, I already have written my urls.py file for it: from django.conf.urls import url from apps.mascota.views import index urlpatterns = [ url(r'^$/', index), ] And I have modified the url.py file of my project: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('apps.mascota.urls')), ] But when I run the server of my project, it sends me the next error message: I know this is a dummy question, but I don't know what is wrong, I have already checked my urls sentences, but I see everything ok. I will appreciate your help. Ps.: My app is located inside a folder called apps. Regards. -
How to transfer edit method of an ID to a button/links? Django
So this is the code in my ulrs.py url(r'^viewguides/detail/(?P<id>\d+)/edit/$', views.post_update, name='update'), No I want to make it look like this: <a href="/detail/(?P<id>\d+)/edit" class="btn btn-default btn-lg" style="background-color: transparent;"><font color="Orange"> EDIT </font></a><hr> So that I can edit the certain ID that I want to. But it gives me an error. How do you guys do it? or is there any other way? I'm new to django. pls HALP!! -
django stream json data that is created by request
how can we stream data in django i saw many tutorials but still can figure it out, i requested a data inside view.py and send it through the context to template.html, but i want to update the data once it got changed so i need to keep sending request but how can i create that type of connection? basically some thing like this: webserver ---------> Wsgi -----------> urls.py | | | | | keep sending data | keep requesting data templat.html<--------------------- views.py -------------------------> request i dont now if we need to use sockets or how to approach this problem. -
DRF auth tokens fail in tests: django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed
any time I try to read the response.content of hitting the usual /api-token-auth/ in my test, I get django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed. This is not a template, I am hitting the url using request factory. Using postman I get it each time: POST: localhost:8000/api-token-auth/ {"username": "cchilders", "password": "blahblah"} Body { "token": "4c3008f5130b94e15a52937b56a3cc0ae1e1ee79" } curl even works. tests do not $ http POST 127.0.0.1:8000/api-token-auth/ username='cchilders' password='blahblah' HTTP/1.0 200 OK Allow: POST, OPTIONS Content-Type: application/json Date: Sun, 16 Oct 2016 04:18:02 GMT Server: WSGIServer/0.1 Jython/3.5.1 X-Frame-Options: SAMEORIGIN { "token": "4c3008f5130b94e15a522342j234234ae1e1ee79" } tests: from django.contrib.auth.models import User from django.urls import reverse from model_mommy import mommy from api.login.views import customer_login from api.mixins import AppUserViewsTests class LoginViewTests(AppUserViewsTests): def setUp(self): super().setUp() self.view = customer_login self.token_url = reverse('auth-token') self.token_test_url = reverse('api:login:token-test') self.payload = {'username': 'cchilders', 'password': 'blahblah'} self.make_user() def test_auth_token_works(self): response = self.run_assertion_test(self.token_url, data=self.payload, expected_status_code=200) import ipdb; ipdb.set_trace() # can't do response.content or response.META def test_protected_url_with_no_token_given_fails_400(self): self.run_assertion_test(self.token_test_url, expected_status_code=400) def test_protected_url_with_token_given_works(self): response = self.call_view(self.token_url, data=self.payload) self.run_assertion_test(self.token_test_url, expected_status_code=200) def make_user(self): user = mommy.make(User, **self.payload) the mixin from copy import copy from django.contrib.auth.models import User from django.test import TransactionTestCase from rest_framework.test import APIRequestFactory from users.models import AppUser class AppUserViewsTests(TransactionTestCase): def setUp(self): self.factory … -
Django: Slug in Vietnamese working not correctly
I begin to develop website online store using Django framework. I have faced with problem that I want to change the name in Vietnamese "những-viên-kẹo" to "nhung-vien-keo". I have read this article: http://stackoverflow.com/questions/1605041/django-slug-in-vietnamese and I do something like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.template.defaultfilters import slugify class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True,help_text = 'Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text = 'Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.slug: vietnamese_map = { ord(u'ư'): 'u', ord(u'ơ'): 'o', ord(u'á'): 'a', ord(u'n'): 'n', ord(u'h'): 'h', ord(u'ữ'): 'u', ord(u'n'): 'n', ord(u'g'): 'g', ord(u'v'): 'v', ord(u'i'): 'i', ord(u'ê'): 'e', ord(u'n'): 'n', ord(u'k'): 'k', ord(u'ẹ'): 'e', ord(u'o'): 'o', } self.slug = slugify(unicode(self.slug).translate(vietnamese_map)) super(Category, self).save(*args, **kwargs) class Meta: db_table = 'categories' ordering = ['-created_at'] verbose_name_plural = 'Categories' def __unicode__ (self): return self.name @models.permalink def get_absolute_url(self): return ('catalog_category', (), { 'category_slug': self.slug }) But when I type "những-viên-kẹo" in the Name field of Admin page, the slug field … -
Django FileNotFoundError in a view when returning HTML using codecs
I am creating a view in Django that returns a static HTML page, and my code for that view is as follows: from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response import codecs # Basic HTTP response that returns my html index # To call this view, map it to a URLconf def index(request): # When a request is called, return my index.html html = codecs.open("index.html", "r") return HttpResponse(html.read()) When I fire up the Django dev. server and navigate to my app, instead of the rendering of index.html that I expect, I am confronted with a FileNotFoundError at /myapp/ as well as [Errno 2] No such file or directory: 'index.html'. I know for a fact that index.html is a real file in the same directory as myviews.py, and I have also tried debugging by opening a debug.txt in the same directory and returning that, but with the same result. When I open the python shell in the same directory and try to open the same file, it works without a hitch. Any insight would be appreciated, as I am thouroughly stumped. -
ModuleNotFoundError: No module named 'oauth2_provider'
I followed all the directions in importing Facebook into my python django app. However, when I try to migrate , I get an error "No module named'oauth2_provider' I am using Windows 10, Python 3.6.0. (app) C:\Users\Corey Shaw\Desktop\goodrvirtualenv\app\Scripts\app>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\COREYS~1\Desktop\GOODRV~1\app\lib\site-packages\django-1.10-py3.6.egg\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\COREYS~1\Desktop\GOODRV~1\app\lib\site-packages\django-1.10-py3.6.egg\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Users\COREYS~1\Desktop\GOODRV~1\app\lib\site-packages\django-1.10-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\COREYS~1\Desktop\GOODRV~1\app\lib\site-packages\django-1.10-py3.6.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\COREYS~1\Desktop\GOODRV~1\app\lib\site-packages\django-1.10-py3.6.egg\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\COREYS~1\Desktop\GOODRV~1\app\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'oauth2_provider' -
How do I remove the circular dependency in my Organization-Owner-Member models?
Heyo, I'm fairly new to this stuff so please pardon me if this is a stupid question. I'm trying to create an app where users can create organizations and join already existing ones. My requirements are: an organization may have only one user designated the owner (the user who creates it) users must be able to join several organizations users must be able to create organizations and therefore be owners of multiple organizations So far I've got the following models.py: from django.db import models from django.utils.translation import ugettext_lazy as _ from myapp.users.models import User class TimeStampedModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Org(TimeStampedModel): name = models.CharField( _('Organization name'), max_length=255, ) owner = models.OneToOneField('OrgOwner') members = models.ManyToManyField( 'OrgMember', related_name='organization_members' ) users = models.ManyToManyField( User, related_name='organization_users' ) def __str__(self): return self.name class OrgMember(TimeStampedModel): user = models.ForeignKey( User, related_name='user_profile' ) organization = models.ForeignKey( Org, related_name='member_organization' ) def __str__(self): return self.user.username class OrgOwner(TimeStampedModel): member = models.OneToOneField(OrgMember) organization = models.OneToOneField(Org) def __str__(self): return self.member.__str__() My issue is that the way I've designed the models so far, I have a circular dependency. In order for a user to create an Org from scratch he needs to be an OrgMember of … -
django 1.10 Exception while resolving variable 'is_popup' in template 'admin/login.html'
I create a new django project with python3.5 and django1.10.0,I keep getting an error in the admin whenever I want access localhost:8000/admin, He`re's the error: [DEBUG]- Exception while resolving variable 'is_popup' in template 'admin/login.html'. Traceback (most recent call last): File "C:\Python\Python35\lib\site-packages\django\template\base.py", line 885, in _resolve_lookup current = current[bit] File "C:\Python\Python35\lib\site-packages\django\template\context.py", line 75, in __getitem__ raise KeyError(key) KeyError: 'is_popup' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\Python35\lib\site-packages\django\template\base.py", line 891, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'RequestContext' has no attribute 'is_popup' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\Python35\lib\site-packages\django\template\base.py", line 900, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'is_popup' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\Python35\lib\site-packages\django\template\base.py", line 907, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_popup] in "[{'True': True, 'None': None, 'False': False}, {'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x04A2D1D0>, 'DEFAULT_MESSAGE_LEVELS': {'WARNING': 30, 'SUCCESS': 25, 'ERROR': 40, 'INFO': 20, 'DEBUG': 10}, 'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x04A0A590>>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x04A0A490>, 'request': <WSGIRequest: GET '/admin/login/?next=/admin/'>, 'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x04581C90>>}, {}, … -
memcached fails after running for a while
I am using Django with memcached with somewhat high volume of requests. At first the memcached works fine, however, after a while it starts raising errors from time to time. The error messages are also inconsistent. After spending a lot of time I can't even find out what exactly the errors mean, nor how to resolve it. Setup: Django + default memcached backend memcached is started using Docker: docker up -d memcached -m 3072m -I 10m -c 4096 memcached uses its own dedicated host Host spec: 4 CPU + 3.5GB ram swappiness = 0 Stats stats STAT pid 1 STAT uptime 38718 STAT time 1476576775 STAT version 1.4.31 STAT libevent 2.0.21-stable STAT pointer_size 64 STAT rusage_user 73.432000 STAT rusage_system 565.536000 STAT curr_connections 10 STAT total_connections 346393 STAT connection_structures 4070 STAT reserved_fds 20 STAT cmd_get 710031 STAT cmd_set 373473 STAT cmd_flush 0 STAT cmd_touch 0 STAT get_hits 681898 STAT get_misses 28133 STAT get_expired 1295 STAT get_flushed 0 STAT delete_misses 0 STAT delete_hits 0 STAT incr_misses 0 STAT incr_hits 0 STAT decr_misses 0 STAT decr_hits 0 STAT cas_misses 0 STAT cas_hits 0 STAT cas_badval 0 STAT touch_hits 0 STAT touch_misses 0 STAT auth_cmds 0 STAT auth_errors 0 STAT bytes_read 294333584541 STAT bytes_written … -
Django {% block %} explanation
I'm a Django beginner and I wanted to try and learn some of the Django-CMS basics. When I started editing the default template that was generated by the installer, I noticed there are {% block ... %} blocks, but I couldn't find any documentation on what block means or more specific what block title and block content mean. Both the Django and the Django-CMS documentation lacks of such an explanation, which is weird given the fact that this seems pretty basic. When I removed the block title block, the title got messed up. I'm using: Django 1.8.15 django-cms 3.4.1. -
Cannot find import pdfkit in Django
I installed pdfkit on my server using the following command >> pip install pdfkit This installed the pdfkit in the path /home/admin/lib/python2.7/pdfkit Now however in my django app I get the error ImportError at / No module named 'pdfkit So I further added that path to my PYTHONPATH. And then to check that I did this >>> import sys >>> print sys.path ['', '/home/admin/lib/python2.7/pip-8.1.2-py2.7.egg', '/home/admin/lib/python2.7', '/home/admin/lib/python2.7/pdfkit', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/PIL', '/usr/lib64/python2.7/site-packages/geos', '/usr/lib/python2.7/site-packages'] Now even though the path /home/admin/lib/python2.7/pdfkit is in there yet i am getting an import error. Any suggestions on how I can fix this ? -
Django Copy All Data From Table
Currently have written a custom User model in Django specifically for extending the length of the username. Change all references to the user to use the settings.AUTH_USER_MODEL and change any foreign key references that are needed. The existing app has existing users in the table. Whats the best way to clone all the data from the auth.user to the custom user table using a custom migration. Currently using Django 1.9 -
Using Foundation Modals with Django
I had an html file using Foundation to display a simple signup login template that was working as desired before using Django. I made a Django project and app and was able to get everything displaying as it was before except for modals. The section looks like this: <a data-open="signup" class="button">Sign up</a> <div class="reveal" id="signup" data-reveal> I've used this http://foundation.zurb.com/sites/docs/reveal.html but it's not actually displaying the modal when I run the Django server. Any help is appreciated! -
While using Django : Command '['wkhtmltopdf', '--encoding', u'utf8'] returned non-zero exit status 1
In Django, I get this error code while using wkhtmltopdf. It uses the default path(which has been set under windows) for the command. This is my url: url(r'^marche/$', PDFTemplateView.as_view(template_name='hello.html', filename='my_pdf.pdf'), name='pdf'), Any ideas? Thanks -
Mezzanine 404 and 500 errors template not overriding
I'm working with Mezzanine and want to override the generic Django 404 and 500 page template. I copied the errors folder into: my_theme/templates/errors the 404.html and 500.html templates inside errors should override the generic template but they do not... -
using while loop jinja inside django for displaying the data from requests
i could not find any documentation for while loop in jinja, is there any way we can create an infinite loop in jinja, i am using django framework. i want to request for data and keep updating the data in side the webpage. in views have r = requests.get(URL).json() def index(request): context = {'R' : r} return render(request,'market/detail.html',context) in the html i want something like this {{ while ture}} {{ R }} -
why is feedparser returning fewer results than there actually are?
I am using feed parser along with beautifulsoup. There is no key explicitly for the youtube embed code. Instead it is inside of the html via the 'content' key like this 'content': [{'value': '<h4><strong>Video:</strong> cangel Ft De La – ose (Official Video)<span id="more-125869"></span></h4>\n<p>&nbsp;</p>\n<div class="lyte-wrapper"></div>\n<p><span id="more-2331"></span><iframe src="https://www.youtube.com/embed/HFiDh_TcvNE" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p>',}], so I created a function to get the src code and image code like this def pan_task(): url = 'http://elrealsonidodelakalle.net/feed/' name = 'elrealsonidodelakalle' live_leaks = [i for i in feedparser.parse(url).entries][:3] the_count = len(live_leaks) ky = feedparser.parse(url).keys() oky = [i.keys() for i in feedparser.parse(url).entries][1] # shows what I can pull def embed_image(html_doc): soup = BeautifulSoup(html_doc, "html5lib") embed = soup.iframe.get('src') remove = 'https://www.youtube.com/embed/' remaining_pic_code = embed.replace(remove, '') the_img = 'http://i1.ytimg.com/vi/' + remaining_pic_code + '/hqdefault.jpg' results = {'src': the_img, 'embed': embed} return results results = [{ 'name': name, 'text': i.title, 'url': i.id, 'comments': i.title, 'src': embed_image(i.content[0]['value'])['src'], 'embed': embed_image(i.content[0]['value'])['embed'], 'author': None, 'video': True, 'status': 'published' } for i in live_leaks] for entry in results: post = Post() # post.title = entry['text'] # title = post.title # if not Post.objects.filter(title=title): post.title = entry['text'] post.name = entry['name'] post.url = entry['url'] post.body = entry['comments'] post.image_url = entry['src'] post.video_path = entry['embed'] post.author = entry['author'] post.video = entry['video'] post.status … -
urls.py entry for django v1.10 mysite.com:8000/index.html
I'm having trouble getting the url entry in my app's urls.py file how I want it. When a person enters mysite.com:8000/, I want it to use the same view as mysite.com:8000/index.html I can use url(r'^index.html$', views.index, name='index'), and the view is properly displayed when I type mysite.com:8000/index.html into the chrome address bar, or I can trim the .htmloff both the urls.py entry and the address bar and it's ok, but I figured with regex, I could get this to display for / or for index* lots of googling hasn't let me to an answer yet... -
Convert QueryDict into list of arguments
I'm receiving via POST request the next payload through the view below: class CustomView(APIView): """ POST data """ def post(self, request): extr= externalAPI() return Response(extr.addData(request.data)) And in the externalAPI class I have the addData() function where I want to convert QueryDict to a simple list of arguments: def addData(self, params): return self.addToOtherPlace(**params) In other words, what I get in params is somethin like: <QueryDict: {u'data': [u'{"object":"a","reg":"1"}'], u'record': [u'DAFASDH']}> And I need to pass it to the addToOtherPlace() function like: addToOtherPlace(data={'object':'a', 'reg': 1}, record='DAFASDH') I have tried with different approaches but I have to say I'm not very familiar with dictionaries in python. Any help would be really appreciated. Thanks!