Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Image Upload, Image Is Never Stored
I'm having some trouble with a django blog that I'm working on, and I was wondering if someone could help me out. https://github.com/kevin-reaves/Blog localhost:8000/posts/create Basically, when I go to create a blog post using the creation form everything seems to work aside from uploading the actual image. The admin console seems to think there's an image at the correct location, but nothing gets uploaded there. Here's the password for the admin console admin password123 Edit: Added some relevant code <form action="{% url 'create' %}" method="POST">{% csrf_token %} <p>Title:</p> <input type="text" name="title"/> <br/> <p>Image:</p> <input type="file" name="image"/> def create(request): if request.method == 'POST': if request.POST['title'] and request.POST['body']: post = Post() post.title = request.POST['title'] post.pub_date = timezone.datetime.now() post.image = request.POST['image'] post.body = request.POST['body'] post.author = request.user post.save() return redirect('home') class Post(models.Model): title = models.CharField(max_length=250) pub_date = models.DateTimeField() author = models.ForeignKey(User, db_column="user", default=1) image = models.FileField(upload_to='media', blank=True) body = HTMLField() -
UIWebView With Django
I have a UIWebView that simply displays a website with the following code: let str8REDURL = URL(string: "https://str8red.com/") let str8REDURLRequest = URLRequest(url: str8REDURL!) webView.loadRequest(str8REDURLRequest) The page is driven with Django in the background that handles login authentication. Is it possible to retrieve the django user id from and display it as a message within the app? I know within the HTML i can just use {{ user.id }}. If the user is not logged in the message could just say "Not Logged In". I am using Swift 3. Any help would be amazing. -
Relational database - Django Rest Framework
I am trying to build relations with my database tables. Im having a tutorial lesson at the moment with 3 tables. for example (auth_user table, partyEvent table, friends table). Now a user should be able to create just one partyEvent. Friends can join any number of partyEvent created by the users. The owner id in the Friends model tells the partyEvent and User 'the friend' belongs to. I am able to restrict the users to create only one partyEvent. But when i try to register friends to a partyEvent, the owner's id is not sent. Instead the default value in: owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1') is rather sent. Why is that happening? models class PartyEvent(models.Model): name = models.CharField(max_length=100, blank=False) location = models.CharField(max_length=100, blank=False) owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1') class Friends(models.Model): name = models.CharField(max_length=100, blank=False) owner = models.ForeignKey('auth.User',related_name = 'friends', on_delete=models.CASCADE, default='1') serializers class FriendsSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = Friends fields = ('id','name','owner') -
Streaming json data with django
After serch and research I dont find any way to make realtime HTTP comunication as RTP or like, specifically in python with django and jquery. Actually my concept the “realtime” is a loop SetInterval that makes a request every 1 second to the http server, django catching the request and process them after return a json response and one on my javascript fuction draw the data in a svg. Any one can you help me with other solution or best practice? Thank you! -
Setting up django with Apache on Amazon's ec2 instance
I am trying to setup Django with Apache using mod_wsgi on Amazon's ec2 instance. I was following this guide for the setup. But after modifying the httpd.conf file and checking it with configtest, /etc/init.d/httpd configtest I get the following error: 'Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration' error. The following are the lines from my httpd.conf file WSGIScriptAlias / /home/ec2-user/frontend/backend-django/backend/wsgi.py WSGIPythonHome /home/ec2-user/frontend/frontendenv WSGIPythonPath /home/ec2-user/frontend/backend-django WSGIDaemonProcess frontend python-home=/home/ec2-user/frontend/frontendenv python-path=/home/ec2-user/frontend/backend-django WSGIProcessGroup frontend <Directory /home/ec2-user/frontend/backend-django/backend> <Files wsgi.py> Require all granted </Files> </Directory> When I looked up at SO, I've learnt that I have to either enable wsgi mod in apache or load the module in httpd.conf. But I am getting No package a2enmod available and httpd: Syntax error on line 159 of /etc/httpd/conf/httpd.conf: Cannot load modules/mod_wsgi.so into server: /etc/httpd/modules/mod_wsgi.so: cannot open shared object file: No such file or directory errors respectively. The amazon's ec2 instance is running on Amazon Linux. Can anybody help me out here. Thank you. -
Why do I get KeyError: "MIGRATION_COMMANDS" when I upload my project to Divio Server?
I would like to know why I can't deploy my Django project in a Divio Server, since I get the error: File "/virtualenv/lib/python3.5/site-packages/aldryn_djang/cli.py",line 51, in migrate cmds = ctx_obj['settings']['MIGRATION_COMMANDS'] KeyError: 'MIGRATION_COMMANDS' -
How to (sort of) control android device from webapp?
I need to be able to control Android phone through my webapp. I need to know which permissions do I need to take from user from his/her google account. For example I need another user to be able to send an address to this user and this should open his Google Map with that address shown. Or send a message and it should be somehow opened on the user's phone. Is this all possible? If yes, then how. If no, what can be the closest we can achieve? -
Django Rest Framework - User field may not be null
I am learning Django and Django Rest Framework to create an API and cannot wrap my head around why when i run this command: http --json POST http://127.0.0.1:8000/api/v1/stocks/ book_code='Abook' 'Authorization: Token 123243434354353' i get an error which says: HTTP/1.0 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Date: Thu, 25 May 2017 19:16:37 GMT Server: WSGIServer/0.2 CPython/3.6.0 Vary: Accept X-Frame-Options: SAMEORIGIN { "user": [ "This field is required." ]} The 'user' field is required but I am expecting it to populate with the user based on the token I have provided i.e the authenticated user. This is the bookstock/models.py: from django.db import models from django.contrib.auth.models import User class Stock(models.Model): ''' Model representing the stock info. ''' user = models.ForeignKey(User) book_code = models.CharField(max_length=14, null=True, blank=True) def __str__(self): return self.book_code This is the api/serializer.py: from bookstock.models import Stock from rest_framework import serializers class StockSerializer(serializers.ModelSerializer): class Meta: model = Stock fields = ('id', 'user', 'book_code') This is the api/views.py: from rest_framework import generics from bookstock.models import Stock from api.serializers import StockSerializer from rest_framework.permissions import IsAuthenticated class StockList(generics.ListCreateAPIView): serializer_class = StockSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): user = self.request.user return Stock.objects.filter(user=user) def perform_create(self, serializer): serializer.save(user=self.request.user, ) def perform_update(self, serializer): serializer.save(user=self.request.user) This is … -
Django DecimalField Not Working
I am trying have a decimal field that can accept up to 8 digits and 3 decimal places but it keeps saying Please enter a valid value. The nearest two valid values are 12345678 and 12345679. model.py daily_demand = models.DecimalField(max_digits=12, decimal_places=3) forms.py daily_demand = forms.CharField(widget=forms.NumberInput()) -
Django Context Processors without the rest of Django?
I'm trying to use Django templates as a standalone application and I'm having issues with Engine.context_processors My main file is: from django.template import Template, Context, Engine template_content = """ -- HEADER --- {{ var|star_wrap }} {% fullpath "filename_123.txt" %} {{ abc }} -- FOOTER ---""" data = {'var': 'Ricardo'} engine = Engine( debug=True, builtins=['filters'], context_processors=( 'context_processors.my_context_processor' ) ) template = Template( template_content, engine=engine, ) context = Context(data) result = template.render(context) In my filters.py I have: from django import template # --- Filters register = template.Library() # pylint: disable=C0103 @register.filter(name='star_wrap') def star_wrap(value): return "** " + value + " **" @register.simple_tag(takes_context=True) def fullpath(context, arg): print(context) return "/tmp/"+str(arg) And in the context_processors.py I have: def my_context_processor(request): return {'abc': 'def'} Basically the data in my my_context_processor is ignored... the {{ abc }} is not being substituted. See the output of the code above. I also print the context: [{'False': False, 'None': None, 'True': True}, {'var': 'Ricardo'}] -- HEADER --- ** Ricardo ** /tmp/filename_123.txt -- FOOTER --- Any idea why the my_context_processor is being ignored? -
Django form in modal missing form fields
I'm trying to figure out how to add my create_user_form to a modal window on my template. The modal is loading, but none of the form fields are showing. I've checked everything I can think of in my views, forms, and templates. I think it has something to do with the {% include 'pages/modal_create_user.html' %} line, but I don't know of another way to call it from a separate file. Here are the code snippets I have: Views: def create_user(request): registered = False if request.method == 'POST': # Get info from "both" forms # It appears as one form to the user on the .html page user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save User Form to Database user = user_form.save() # Hash the password user.set_password(user.password) # Update with Hashed password user.save() # Now we deal with the extra info! # Can't commit yet because we still need to manipulate profile = profile_form.save(commit=False) # Set One to One relationship between # UserForm and UserProfileInfoForm profile.user = user # Check if they provided a profile picture if 'profile_pic' in request.FILES: print('found it') # If yes, then grab it from … -
Django filter which may include None
Is there a way to include None when filtering on a list of values? >>> MyModel.objects.filter(amount=10).count() 9 >>> MyModel.objects.filter(amount=None).count() 30 >>> MyModel.objects.filter(amount__in=[10]).count() 9 >>> MyModel.objects.filter(amount__in=[None, 10]).count() 9 I would expect the last call to return 39, rather than 9. In my actual use case None may or may not be included in the list of values to be filtered on. I could use an if/else block to check for None in the list of values and construct the query using Q objects if needed, but doing so for a large number of filters is going to be a mess. There must be a better way, right? -
avoiding /accounts/login/?next in django
urls.py #... from myapp.views import MyView from django.contrib.auth.decorators import login_required urlpatterns = [ #.... url(r'^terminator/', login_required(MyView.as_view()), name='sexy') ] views.py class MyView(View): def get(self, request): return render(request, 'itworks.html') I am accessing MyView class via Somelogin class which redirects to "terminator url". But the problem is: django redirects me to following url `http://127.0.0.1:8000/accounts/login/?next=/terminator of course, this address is not defined and gives me 404. I played with LOGIN_REDIRECT_URL in settings, but this just brings more confusion to code. So is there anyway to avoid this "default/next" in django and just go to "http://127.0.0.1:8000/terminator" Thanks -
django 1.11 with celery 4.0 and djcelery compatibility issues
I currently use django 1.11 and I'm forced to use an older version of celery (3.1) for compatibility reasons. I want to upgrade to celery 4.0 because another part of our application needs the later version of celery. Is there a combination of celery, django-celery and django 1.11 that is compatible? The docs say that celery 4.0 is compatible with all versions of django from 1.8 onwards, but this does not seem to be the case. -
HTTP2 with gunicorn
Is it possible to run a Django Application using Gunicorn and HTTP2? Currently we have Nginx in front of our application working as a reverse proxy, but we may drop it in the future, since we are starting to migrate to docker swarm. I could not find any docs/links regarding configuration of gunicorn with HTTP2. Does anybody knows if it is possible to do it, without using nginx? If not possible, please suggest other webservers that can achieve that. -
Django FormView Not Redirecting on Subclass
I have been trying to get back into the flow of OO programming. When I create an UploadServerInventory class and upload a file I get redirected back to root. However when I create UploadServerInventory and upload a file I get a "UploadServerInventory didn't return an HttpResponse object. It returned None instead." Shouldn't I be inhering everything from the parent class? It looks like I am passing everything back up to the Super class? What fundamental problem am I missing? class UploadExcelFile(FormView): template_name = 'cmdb/upload.html' form_class = UploadFileForm success_url = '/' def form_valid(self, form): return super(UploadExcelFile, self).form_valid(form) def set_excel_file(self): self.excel_dict = self.request.FILES['file'].get_book_dict() def form_invalid(self, form): return super(UploadExcelFile, self).form_invalid(form) class UploadServerInventory(UploadExcelFile): def form_valid(self, form): self.set_excel_file() super(UploadServerInventory, self).form_valid(form) def form_invalid(self, form): return super(UploadServerInventory, self).form_invalid(form) -
Django - 404 static files not found
I know theres about a millon of these questions but non of them have helped me out. I can't access my static files for deployment, I've slpit my settings file into base and production and put them in a folder in the settings.py orginal file. I've done everything neccessary but it still doesn't seem to be working and I can't work it out for the life of me. I've tried editing the path several time and no change. Maybe I've missed something obvious and someone else can see it. venv --project ----app1 ------static folder ----wsgi folder ------settings_old.py ------new settings folder ---------base.py ---------production.py base.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = ['django.contrib.staticfiles',] STATIC_URL = '/static/' STATIC_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'static_r') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) I've tried a couple of different things like changing from BASE_DIR to a new PROD_DIR that directly goes to the static file in index. PROD_ROOT = os.path.dirname(os.path.abspath('__file__' )) PROD_ROOT= os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath('__file__' )))) PROD_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) Nothing seems to be working. -
DRF - Nested Serialization Of m2m fields with through model
I am using a m2m field with a through model in DRF. Everything is working fine, EXCEPT when I try to nest the membership serializer. models.py class SweepStakes(models.Model): name = models.CharField(max_length=255) class Event(models.Model): sweepstakes = models.ManyToManyField(SweepStakes, through='EventSweepStakesMembership') class EventSweepStakesMembership(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) sweepstakes = models.ForeignKey(SweepStakes, on_delete=models.CASCADE) enabled = models.BooleanField(default=False) serializers.py class EventSweepStakesSerializer(serializers.ModelSerializer): name = serializers.ReadOnlyField(source='sweepstakes.name') class Meta: model = EventSweepStakesMembership fields = ('name', 'enabled',) class EventSerializer(BaseTenantSerializer): sweepstakes = EventSweepStakesSerializer(many=True, read_only=True) class Meta: model = Event fields = ('sweepstakes',) At this point, if I hook the EventSweepStakesMembership model and the EventSweepStakesSerializer up to a view, I get back exactly what I expect, output like this: {"name": "thingy", "enabled" true} However, when I hook the Event model and EventSerializer serializer into a view, the sweepstakes field returns an empty dictionary instead of the nested representation, like so: {"sweepstakes": [{}]} Note that it is NOT an empty array, in other words it does see the related through model, but simply does not serialize it correctly when displaying. There is no error, it is just empty. I have tried increasing the depth of the Event serializer to no avail. Am I missing something or maybe even going about this all wrong? Thanks! -
Automated way to populate each level in a tree in a Django template
I got a tree that have several levels. Bucky at thenewboston said not to break the first rule of coding - Never repeat the code. Well, here I am breaking this rule. Andcanät figure out how to avoid this. My plan is also to be able to individually collapse each branch. But first I want to populate the tree without typing out ten repeated code. This is how I print out my tree. {% block side-menu %} <div id="main-menu" role="navigation"> <div id="main-menu-inner"> {% load mptt_tags %} <ul class="navigation"> {% for a in nodes %} {% if a.item_parent is None %} <li> <i class="menu-icon glyphicon glyphicon-chevron-right"></i> <span class="mm-text">{{ a.item_title }} - {{ a.get_descendant_count }}</span> {% if a.get_descendant_count > 0 %} {% for b in a.get_children %} {% if b.get_previous_sibling is none %}<ul class="children">{% endif %} {% if a.item_title == b.item_parent|stringformat:"s" %} <li> <i class="menu-icon glyphicon glyphicon-chevron-right"></i> <span class="mm-text">{{ b.item_title }} - {{ b.get_descendant_count }}</span> {% if b.get_descendant_count > 0 %} {% for c in b.get_children %} {% if c.get_previous_sibling is none %}<ul class="children">{% endif %} <li> <i class="menu-icon glyphicon glyphicon-chevron-right"></i> <span class="mm-text">{{ c.item_title }} - {{ c.get_descendant_count }}</span> </li> {% if c.get_next_sibling is none %}</ul>{% endif %} {% endfor %} {% … -
Django 1.11 Horizontal choice field
I've just updated from Django 1.10 to 1.11.1. In my template new_house_edit.html I have the following: {{ form.rating }} In forms.py I used to have the following: class HorizontalRadioRenderer(forms.RadioSelect.renderer): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class NewHouseForm(forms.ModelForm): class Meta: model = NewHouse fields = ( 'rating',) widgets={ "rating": forms.RadioSelect(renderer=HorizontalRadioRenderer), } Which gave the following error AttributeError: type object 'RadioSelect' has no attribute 'renderer'. I tried to solve it by doing this which is not working: class HorizontalRadioSelect(forms.RadioSelect): template_name = 'new_house_edit' class NewHouseForm(forms.ModelForm): class Meta: model = NewHouse fields = ( 'rating',) widgets={ "rating": "rating": forms.ChoiceField(widget=HorizontalRadioSelect, choices=(1, 2, 3, 4, 5)), } I now get the error AttributeError: 'ChoiceField' object has no attribute 'use_required_attribute'. Can anyone help me fix this? -
Database relationships -DRF
I am trying to build relations with my database tables. Im learning at the moment with 3 tables. for instance (auth_user table, partyEvent table, friends table). Now a user should be able to create just one partyEvent. Friends can join any number of partyEvent created by the users. The owner id in the Friends model tells the partyEvent and User 'the friend' belongs to. I am able to restrict the users to create only one partyEvent. But when i try to register friends to a partyEvent, the owner's id is not sent. Instead the default value in owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1') is rather sent. Why is that happening? models class PartyEvent(models.Model): name = models.CharField(max_length=100, blank=False) location = models.CharField(max_length=100, blank=False) owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1') class Friends(models.Model): name = models.CharField(max_length=100, blank=False) owner = models.ForeignKey('auth.User',related_name = 'friends', on_delete=models.CASCADE, default='1') serializers class FriendsSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = TeamMember fields = ('id','name','owner') -
How to download all nltk data in google cloud app engine?
I have a django application which I have deployed using below link, https://cloud.google.com/python/django/flexible-environment But as I am using nltk for text processing, I am getting below error. ********************************************************************* Resource 'taggers/maxent_treebank_pos_tagger/PY3/english.pickle' not found. Please use the NLTK Downloader to obtain the resource: >>> nltk.download() Searched in: - '/root/nltk_data' - '/usr/share/nltk_data' - '/usr/local/share/nltk_data' - '/usr/lib/nltk_data' - '/usr/local/lib/nltk_data' - '' So I know that I am missing data from nltk. I have looked tons of code online but there is no way to download data in google app engine. Below is my requirement.txt for your reference. Django==1.10.6 gunicorn==19.7.0 nltk==3.0.5 Please let me know if there is a way to do it. Thanks in advance. -
How to create Models in Django that act like a CMS?
I need help developing models in Django's ORM that would give me the ability to create a user profile and then create unique pages under that user. What I am thinking so far is that I have one model called users and then another model pages. When the user is created and that user creates a page the data in both models are linked by a unique id. Is this the right direction to go or is there a more standard way of doing something like this? Essentially, what I am trying to create is a really stripped down version of Wordpress if that helps. Any advice would be greatly appreciated. Thank you -
VueJS + Django Channels
I just finished reading the introductions for VueJS and Django Channels and would like to use them together to provide real-time updates to several components on a webpage. This illustrates the basic idea: Being new to VueJS, it seems the diagram above requires some type of "middle man", between the VueJS components and the websocket, that makes sure each component gets the correct data. So, my questions are: Architecturally, is this a good design? If so, can VueJS act as that "middle man" to manage which component connects to which channel? Thanks for your help :) -
Django unittest: TypeError: 'NoneType' object is not iterable
python3 manage.py test apps.favorites Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_e utility.execute() File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_v super(Command, self).run_from_argv(argv) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in hande failures = test_runner.run_tests(test_labels) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/test/runner.py", line 548, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/home/dmitry/.pyenv/versions/p/lib/python3.5/site-packages/django/test/runner.py", line 466, in build_suite tests = self.test_loader.discover(start_dir=label, **kwargs) File "/home/dmitry/.pyenv/versions/3.5.1/lib/python3.5/unittest/loader.py", line 341, in discover tests = list(self._find_tests(start_dir, pattern)) File "/home/dmitry/.pyenv/versions/3.5.1/lib/python3.5/unittest/loader.py", line 406, in _find_tests yield from self._find_tests(full_path, pattern, namespace) File "/home/dmitry/.pyenv/versions/3.5.1/lib/python3.5/unittest/loader.py", line 398, in _find_tests full_path, pattern, namespace) TypeError: 'NoneType' object is not iterable Very cryptic message with no details. Everything was working last night. apps/favorites ├── admin.py ├── api │ ├── __init__.py │ ├── mixins.py │ ├── permissions.py │ └── __pycache__ │ ├── __init__.cpython-35.pyc │ ├── mixins.cpython-35.pyc │ └── permissions.cpython-35.pyc ├── apps.py ├── __init__.py ├── managers.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-35.pyc │ └── __init__.cpython-35.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-35.pyc │ ├── apps.cpython-35.pyc │ ├── __init__.cpython-35.pyc │ ├── managers.cpython-35.pyc │ └── models.cpython-35.pyc …