Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap is not hit to HTML
Bootstrap is not hit to HTML. I use Flat UI's Bootstrap. I wrote in index.html like {% load staticfiles %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static './bootflat.github.io/bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <style> body { padding-top: 70px; } .my-form { width: 640px; margin: 0 auto; } @media screen and (max-width: 768px) { .my-form { width: 100%; } } .errorlist li { list-style-type: none; } .errorlist { color: red; margin-left: 0; padding-left: 0; } </style> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <p class="navbar-text">Hello</p> {% if user.is_authenticated %} <p class="navbar-text">{{ user.get_username }}</p> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> I designate folder path which has Flat UI like <link rel="stylesheet" href="{% static './bootflat.github.io/bootflat/css/bootflat.min.css' %}"> but the design is not changed.I accessed http://localhost:8000/static/bootflat.github.io/bootflat/css/bootflat.min.css,but Page not found (404) Request Method: GET Request URL error happens.So I think path is wrong. Directory structure is index.html is in accounts.accounts folder structure is What is wrong in my code?How should I fix this? -
OSX/Apache ModuleNotFoundError: No module named 'encodings'
I have a local Django application that I've been developing for a while. Today, after about a month off from working on it I went back to it, but it wouldn't load. Checking the apache error log, I see the following over and over: Current thread 0x00007fffc0be23c0 (most recent call first): [Tue Sep 26 19:18:09.154141 2017] [core:notice] [pid 1590] AH00052: child pid 1651 exit signal Abort trap (6) Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' The last time I was working on the project, I made some changes to my project code, but didn't touch and of my apache or mod_wsgi configuration. My PYTHONPATH is not set (nor was it set a month ago when everything was working. Here's my mod_wsgi configs (again haven't changed): WSGIDaemonProcess secureDash python-path=/Users/user/projects/secureDash_project python-home=/Users/user/.venvs/securedash_py3.6 WSGIProcessGroup secureDash WSGIScriptAlias / /Users/user/projects/secureDash_project/config/wsgi.py I've spent a lot of time googling this issue, but none of the common fixes seem to apply. Looking for some guidance on where else to look. -
why does django not combine makemigrations and migrate commands?
I can think of three reasons why: providing users with the flexibility on "when" to commit model changes debugging modularity perhaps resource consumption in larger databases However, it does seem that migrate always follows shortly after migration (tutorials/youtube videos). so is there a philosophy behind this that I'm missing? -
Failure during running rc.exe for Twisted on Windows 10
When I run pip install channels or pip install twisted Twisted fails with Failed building wheel for twisted Twisted is a required dependency for Django Channels. Here is the error: LINK : fatal error LNK1327: failure during running rc.exe error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1327 I tried various installs of Visual Studio and Build Tools, but could not make any progress. How do I get twisted to build on Windows 10? -
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 …