Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
operational error with Digital ocean and django
Getting this error after using DO's one-click install for Django and uploading all my stuff. I set up my settings and urls files. Not really sure what the issue is, I've never seen it before. The error: OperationalError at /accounts/login/ SSL error: unknown protocol expected authentication request from server, but received S Traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapper return bound_func(*args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in dispatch return super(LoginView, self).dispatch(request, *args, **kwargs) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in dispatch **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in get request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in get return self.render_to_response(self.get_context_data()) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in get_context_data site = get_current_site(self.request) … -
django apache ImportError: No module named
So this is driving me crazy I have python3 and modwsgi and apache and a virtual host, that work great, as I have several other wsgi scripts that work fine on the server. I also have a django app that works great when I run the dev server. I have checked that "ldd mod_wsgi.so" is linked correctly against python3.5 Whenever I try to access my site, I get an error and the apache log states: ImportError: No module named 'protectionprofiles' protection profiles is mysite name the following is my virtual host config <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName <my ip> WSGIScriptAlias /certs /var/www/scripts/CavsCertSearch/CavsCertSearch/certstrip.wsgi WSGIScriptAlias /testcerts /var/www/scripts/CavsCertSearchTest/CavsCertSearch/certstriptest.wsgi WSGIScriptAlias /protectionprofiles /var/www/protectionprofiles/protectionprofiles/wsgi.py <Directory /var/www/protectionprofiles/protectionprofiles> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> my site app is the protection profiles alias. I have no idea what the issue is I have tried following dozens of different apache tutorials and none of them seem to work. Any help is greatly appreciated. -
Django form field validation and auth password validation
I'm using Django 1.10.6 and working on a registration form. On a forms.py I want to use the min_length argument for the password form field to help prevent unnecessary server requests, because Django adds that attribute to the CSS and most browsers will check that before allowing a form to be submitted. However, Django doesn't seem to like when I use form field validation along with AUTH_PASSWORD_VALIDATORS in certain cases. When I open up inspector on the registration page and delete the CSS for the min_length attribute of the password input (thus preventing being prompted by my browser to enter more characters) and submit the request with less than 8 characters, the form field validation fails and Django deletes/empties (sorry, not sure of the correct term) the cleaned data so the password is None, which then causes the rest of the AUTH_PASSWORD_VALIDATORS to throw errors. This is the error which results object of type 'NoneType' has no len() Here's my registration class on forms.py class RegisterForm(forms.Form): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) email = forms.CharField(label="Email", max_length=254, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'email'})) #when I remove the min_length here it works, however I would like to have the benefit of the … -
Django | update requirements.txt automatically afrer installing new package
I am new to Django. Every time I install new library using pip, I have to run pip freeze -l > requirements.txt and sometimes I forget this ( and error happens at my production environment). What's the best way to run this command automatically when I install new packages...? I am using: Django==1.11.5 Python 3.6.1 -
Django Template: key, value not possible in for loop
Error I get: Need 2 values to unpack in for loop; got 1. Here is my view: class Index(View): def get(self, request, slug): test = { 1: { 'id': 1, 'slug': 'test-slug-1', 'name': 'Test Name 1' }, 2: { 'id': 2, 'slug': 'test-slug-2', 'name': 'Test Name 2' } } context = { 'test': test } return render(request, 'wiki/category/index.html', context) Here is my template: {% block content %} <div> {{ test }} <ul> {% for key, value in test %} <li> <a href="#">{{ key }}: {{ value }}</a> </li> {% endfor %} </ul> </div> {% endblock %} I also tried the template like: {% block content %} <div> {{ test }} <ul> {% for value in test %} <li> <a href="#">{{ value }}: {{ value.name }}</a> </li> {% endfor %} </ul> </div> {% endblock %} No error then, but {{ value }} shows key (what is fine), but {{ value.name }} shows nothing. Whilte {{ test }} shows my dict. -
Social authentification django
I am building a website using django, and I did a social auto using 'allauth', but the thing is, I can only login from my own facebook account where I have added the app in developers.facebook.com, well I want other users , to be able to login with their own facebook accounts. Is there's another way than 'allauth', or should I make changes to it ? I am a beginner in django. -
How to select results from django model group by an attribute
I need some help with a problem that i can't figure out with Django (unless by doing crappy nested for). I have these three models : class Article(models.Model): label = models.CharField(max_length=100) unity = models.ForeignKey('Unity') category = models.ForeignKey('Category') user = models.ForeignKey(User) class Store(models.Model): label = models.CharField(max_length=100) address = models.TextField() products = models.ManyToManyField(Article, through='Offer') user = models.ForeignKey(User) class Offer(models.Model): quantity = models.FloatField() price = models.FloatField() infos = models.TextField(blank=True) article = models.ForeignKey('Article') store = models.ForeignKey('Store') user = models.ForeignKey(User) I'd like to print a table in my template that would looks like : Article | Quantity | Infos | Store_1 | Store_2 | Store_n ------- | -------- | ----- | ------- | ------- | ------- Ham | 4 | Bla | 4.2 $ | 5.0 $ | Ham | 6 | Bla | 6.0 $ | 7.5 $ | Instead, i only managed to have print this : Article | Quantity | Infos | Store_1 | Store_2 | Store_n ------- | -------- | ----- | ------- | ------- | ------- Ham | 4 | Bla | 4.2 $ | | Ham | 6 | Bla | 6.0 $ | | Ham | 4 | Bla | | 5.0 $ | Ham | 6 | … -
How to deploy a Django website that developed on Pycharm IDE (windows 10) to AWS EC2 or Elastic Bean?
I recently build a Django website in local with Pycharm IDE. I am using window 10. The website is almost done. Now I need to research how to deploy it on the AWS EC2 or Elastic Bean. The reason of choosing AWS is I want to learn how to use AWS. Any clues, tips or document will be appreciated. -
django-graphene mutation runs multiple queries
I'm using these versions. django==1.11.5 graphene-django==1.2.1 Amazon Redshift I have a simple Django model that looks like this. Base class BaseModel(models.Model): created_dt = models.DateTimeField(auto_now_add=True) created_user = models.CharField(max_length=25, default='myuser') updated_dt = models.DateTimeField(auto_now=True) updated_user = models.CharField(max_length=25, default='myuser') class Meta: abstract = True Model class MappingsMaster(BaseModel): """Master mappings model.""" master_id = models.CharField( max_length=36, help_text='''The UUID of the record.''', primary_key=True, default=uuid.uuid4) account_nm = models.CharField( max_length=255, null=True, blank=True, help_text='''The account's name.''') class Meta: managed = False db_table = 'mappings_dev' app_label = 'mappings' GraphQL model class MappingsGraphQL(ObjectType): master_id = String() account_nm = String() My schema looks like this. I've taken most of this from the Graphene tutorial. class MappingsNode(DjangoObjectType): """ Search account. accounts (or groups) of a search advertisement source system. """ class Meta: model = MappingsMaster interfaces = (relay.Node,) class CreateMapping(ClientIDMutation): class Input: account_nm = String() ok = Boolean() mapping = Field(MappingsNode) @classmethod def mutate_and_get_payload(cls, args, instance, info): ok = True mapping = MappingsMaster(account_nm=args.get('account_nm')) mapping.save() return CreateMapping(mapping=mapping, ok=ok) class Mutations(AbstractType): """Mutations for the mappings class.""" create_mapping = CreateMapping.Field() class Query(AbstractType): """The account query class for GraphQL.""" mapping = Field(MappingsGraphQL) Query mutation createMapping { createMapping(input: {accountNm: "testing account derp"}) { mapping { masterId accountNm } ok } __debug { sql { rawSql } } } Output … -
How do you add a Django form to a wagtail block
I want to add a form to a wagtail block. The form is a simple drop down selection with a submit button. class ExampleForm(forms.Form): example = forms.ModelChoiceField(queryset=Example.objects.all()) Then the wagtail block is a simple table that is generated with get_context() # this is basically the view rendering def get_context(self, request, **kwargs): context = super().get_context(request, **kwargs) # do some queries and populate tables in template. context['example_data'] = SomeObject.objects.all() # here is where I want to add the form. this_form = SomeForm() context['this_form'] = this_form return context But how do you habdle form submissions and everything? It seems that wagtail takes away the idea of a view so I don't know if its possible to do this. Any help would be greatly appreciated. -
Does Django execute all the python files in its project directory?
I'm not sure what the best way of phrasing this question, but I am noticing that if I have say this file in the project directory: a.py class A: pass print("hello") The print statement gets called. What is happening and what is triggering it? Is this part of the class indexing that needs to be done or how is this working? -
Which type of field should I take for likes model in django, Foreign key or ManyToManyField
class Like(models.Model): user = models.ForeignKey(User) picture = models.ForeignKey(Picture) created = models.DateTimeField(auto_now_add=True) Or class Like(models.Model): user = models.ManyToManyField(User) picture = models.ManyToManyField(Picture) created = models.DateTimeField(auto_now_add=True) And please explain why in either case -
Using Google BigQuery as a backend for Django
I am considering using Google BigQuery as a back-end for Django but cannot be certain if this is possible, and if it is, what settings would apply. Currently, my Django application uses Postgresql, and the code in settings.py is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } Ideally, I'd like to setup a database connection to Google BigQuery through settings.py and then use views and models as usual. -
Sphinx: runtime error django 1.9
Currently I'm using Django 1.9 and Django Rest Framework. I'm attempting to use Sphinx and it's autodoc functions, but I'm hitting an error on make html. The models.py does not import. myapp/ manage.py index.rst myapp/ __init__.py settings.py users/ models.py source/ modules.rst users.rst settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'myapp', 'users', ) and the error I get is: WARNING: /home/sestrella/Devel/leroi-angular/source/customers.rst:10: (WARNING/2) autodoc: failed to import module u'users.models'; the following exception was raised: Traceback (most recent call last): File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 657, in import_object __import__(self.modname) File "/home/me/Devel/myapp/users/models.py", line 3, in <module> from django.contrib.auth.models import User, Group File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 6, in <module> from django.contrib.contenttypes.models import ContentType File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 161, in <module> class ContentType(models.Model): File "/home/me/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 112, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. /home/me/Devel/myapp/source/modules.rst:4: WARNING: toctree contains reference to nonexisting document u'source/ users' modules.rst myapp ============= .. toctree:: :maxdepth: 4 users and users.rst users ================ Modules ---------- users.models ---------------------- .. automodule:: users.models :members: :undoc-members: :show-inheritance: Why does the users.models fail to import? I do use the ContentType model in my users.models as a generic relation. -
django form wizard with file upload multiple not working
I am currently digging into django form wizards and I am trying to upload multiple images. Unfortunately, the BaseStorage provided by django form wizard does not handle multiple files. It always assumes a dictionary to be passed. There is a fix posted here: https://github.com/django/django-formtools/issues/98?_pjax=%23js-repo-pjax-container The problem is now, that the posted code breaks in the render_done step of the form wizard when the form_obj is reevaluated. FileFields do not validate when the file is turned from dict to a list. Can anybody point me in the correct direction on how to fix this? How do generic views deal with this issue? Or don't they have this issue at all? -
Django blocktrans with variable
I have a template, in which I want to translate a string. {% blocktrans with "www.mywebsite.com" as website_name %}footer-slogan{{ website_name }}{% endblocktrans %} I've generated my po file, in which I've translated the string as follow : msgid "footer-slogan %(website_name)s" msgstr "This is a test %(website_name)s" On my generated html file, I get this untranslated element : footer-slogan www.mywebsite.com If I remove the variable from the translated string, it works : msgid "footer-slogan %(website_name)s" msgstr "This is a test" I've even tried to remove the variable from the source translation but keeping the variable in the translated string, the issue is the same : template.html {% blocktrans with "www.mywebsite.com" as website_name %}footer-slogan{% endblocktrans %} django.po msgid "footer-slogan" msgstr "This is a test %(website_name)s" I'd prefer to be able to set the variable only on the translated string. What I'm doing wrong on the translated string? -
Django load static in development directly from static folder (Not from apps)
I use django for the backend, in the frontend I use vue.js, so 99% of my CSS it's handled by vue.js, however I need a simple base.css for some customization in the landingpage and few things like this. Normally in django I would put the file inside app/static/app/base.css then do collectstatic and get it under static/app/ for production. I would like to avoid to keep it under an app as it's just a file. I'm trying adding a folder under my main "static" folder. But it seems in development django in not fetching it at all, it fetches directly and only static files from apps. How can I tell django to fetch it directly from the static main folder as it would do in production? i.e. I want to add a folder called main in my root (where manage.py is) and use only that to store my static files for both production and development, without passing through the single apps. -
Javascipt Library to use drag and drop functionalities
I am new to learning HTML, CSS and Javascript. I really need help with the following more from how to approach the problem. I am looking out for a library that can help me with the drop and drag functionality to create the flow into my system like something similar to http://interactjs.io/ . Are there any better libraries as well that help me define the connections? Once I have designed a process for the connections, I want to create the execute routine to process the calculations in the sequential order using python. What would be the best way to store the order of the calculations that I should store in the system? Should I store in the database or create a linked list for every object? -
nginx won't response to some ports
my problem is that I can not add another port to my existing nginx config! I have disabled the firewall on the ubuntu server with this command: sudo service ufw stop in sites-available I have this file named file.conf: server { listen 80; server_name example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/project; } location /files/ { root /home/user/download/; } } server{ listen 8080; server_name example.com www.example.com; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/project.sock; } } server{ listen 8001; server_name example.com www.example.com; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/project.sock; } } I had the 8080 part earlier and this worked in past and now! but 8001 is not working! I disabled the firewall so it shouldn't be it! I also ran this command: sudo netstat -napl | grep 8001 which returned this: tcp 0 0 0.0.0.0:8001 0.0.0.0:* LISTEN 3475/nginx -g daemo thanks for your help and support -
How to create a django project in ubuntu
I'm following a tutorial on Django and I'm suppose to create a folder in Ubuntu in terminal $ django-admin startproject mysite This above line shows "Cannot find installed version of python-django or python3-django." After installing all the required stuffs. -
Rendering django tag in HTML not working
Hi guys I am trying to make my HTML work but it seems that I do not get something. My HTML is the following: {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Welcome to your Project {{ project.name }} Detail page</h2> </div> {% if not project.team_id and project.team_id.members.count() == 0 %} <div class="invite-teammembers"> <div class="jumbotron"> <div class="jumbo-text"> <h3>The team {{ project.team_id }} has beed created, we now need to add TeamMembers</h3> </div> <div class="jumbo-button"> <a href="{% url 'registration:team_register3' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Add Team Members</a> </div> </div> </div> {% elif project.team_id == None %} <div class="invite-team"> <div class="jumbotron"> <div class="jumbo-text"> <h3>Your project has been created, It is time to link a team or create a new for your project</h3> </div> <div class="jumbo-button"> <a href="{% url 'website:link_team'%}" class="btn btn-default" role="button"><span class="glyphicon glyphicon-link"></span> Link an existing team</a> <a href="{% url 'website:add_team' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Create a new team</a> </div> </div> {% else project.team_id.members.count() > 0 %} <h1>Youhouu</h1> {% endif %} </div> </div> {% endblock%} my HTML is not rendering like it is supposed to be I get : Could not parse the remainder: '()' from 'project.team_id.members .count()' the thing is using the shell … -
How to add click event on django-chatit chart
I have created a chart using django-chartit library. Once the chart it shown, I want a click action on my chart, upon which chart get enlarge. How can I do this. Moreover: it there any tutorial available to customize django-chartit charts? -
Celery can't autodiscover tasks
I can't figure out why Celery doesn't autodiscover tasks in Django apps (app called engine). The only discovered task is debug_task inside celery.py Celery v: v4.1.0 stilio/settings.py: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'stilio_auth', 'engine', 'django_extensions' ] ... stilio/__init__.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] stilio/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stilio.settings') app = Celery('stilio') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) engine/tasks.py: from datetime import timedelta from celery.app import shared_task from celery.task import periodic_task, task from utils import SpiderSupervisor @shared_task def tasks(): return @periodic_task(run_every=timedelta(minutes=1)) def ping_spider(): SpiderSupervisor().check() Do you have any ideas where is the problem? -
Django ERROR (EXTERNAL IP): Internal Server Error: /u/1/
I'm having the following issue, but I suspect that it is a configuration issue. The DJANGO app I'm using is open source (from GitHub). The serving components are DJANGO, NGINX and GUNICORN. Clicking on a user-profile page of the site produces the following web page error (all other site links appear fine -- no issues): Internal Error! Sorry about that. A detailed error report has been generated and has been sent to the managers. If the problem persists please contact the site owners. Underneath the covers, it looks like an error email is also constructed with the following subject: [Django] ERROR (EXTERNAL IP): Internal Server Error: /u/1/ Again, I haven't run into any other site link that produce this issue (but I am just starting with this). Looking at the logs, here is more information (where I substituted in example.com and 93.184.216.34 for the actual host/domain name and IP address), Both the host/domain name and it's IP address are specified in NGINX as well as in ALLOWED_HOSTS (live.deploy settings file). gunicorn uses a UNIX DOMAIN SOCKET to communicate with NGINX. MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: [Django] ERROR (EXTERNAL IP): Internal Server Error: /u/1/ From: noreply@lvh.me To: admin@lvh.me … -
Django squash or eliminate migrations on production
I have an app on production. It has 251 migrations that take too much time when I run the tests, it is making development really slow. I need to do something about this and I'd like an advice. Is it recommendable to squash the 251 migrations? what if I erase then and then just fake initial? of course, I can't lose or change the database, it is on production. Thanks a lot for your help.