Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Forbidden access for django apache2 media files
I have trouble with access my files from django admin site. I save files without any trouble, but when I try open it, I get error: Forbidden You don't have permission to access /media/file.pdf on this server. In django project settings: STATIC_URL = '/static/' STATIC_ROOT = '/full/path/to/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In project urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my virtualhost I added this settings: Alias /static/ "/static/folder/" Alias /media/ "/meida/folder/" <Directory "/static/folder"> Require all granted </Directory> <Directory "/media/folder"> Require all granted </Directory> But still get this error. Where can be bug/mistake? -
Django define default view
I migrated my Django project to an Ubuntu distant server. I'm using mod_wsgi in order to runserver and I have some questions about default page. I'm really new in this domain and I apologize if my question is bad or useless .. When I want to connect to my Django application, I have to write something like that : http://172.XX.XX.XXX/Home/login/ If I write just : http://172.XX.XX.XXX I get : Page not found Using the URLconf defined in Etat_civil.urls, Django tried these URL patterns, in this order: ^admin/ ^BirthCertificate/ ^Identity/ ^Accueil/ ^Home/ ^captcha/ ^Mairie/ The current URL, , didn't match any of these. My question is : How I can define redirected url in order to write http://172.XX.XX.XXX in my browser and go directly to http://172.XX.XX.XXX/Home/login/ for example ? This is urls.py file from my project : from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.conf import settings from BirthCertificate import views from Identity import views from Accueil import views from log import views from Mairie import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^BirthCertificate/', include('BirthCertificate.urls')), url(r'^Identity/', include('Identity.urls')), url(r'^Accueil/', include('Accueil.urls')), url(r'^Home/', include('log.urls')), url(r'^captcha/', include('captcha.urls')), url(r'^Mairie/', include('Mairie.urls')), ] Because I just want for example, write my IP … -
Django auto generate identifier number
I want to define the unique identifier field for the Django user model. I want the numbers like 0000-0000-0001, 0000-0000-0002 when save the models. Approach: I can define field as char and post_save signal can update the identifier based on primary key. Is there any automatic way to generate number like this for the user identifier (not primary key) -
django browsable api raw data form empty for post and put requests?
How to auto-fill the form with a default JSON object for easy testing according to the related serializer to the specific view ? -
creating/ guessing the underlying models from JSON response
I am building an application and it was easier for me to think of the JSON response I will get when hitting a specific URL and then based on that now I am trying to build my models. JSON looks like following: { "idea": { "title": "", "description": "", "tags": [ "", "", "" ], "priority": "", "PD": { "question1": "", "question2": "" }, "TOC": { "question1": "", "question2": "" }, "HOW": { "question1": "", "question2": "" }, "issues": [ "issue1", "issue2" ], "tasks": [ "task1", "task2" ], "note": "", "image": [ "base64(1)", "base64(2)" ] } } I started creating models like following (this is more or less Django syntax for models, but I guess logic remains the same for any framework): class Tag(): name = string; idea = ForeignKey(Idea); class Prototype(): base64 = string; idea = ForeignKey(Idea); class Issue(): name = string; idea = ForeignKey(Idea); task = ManyToMany(Task); class Task(): name = string; idea = ForeignKey(Idea); class Idea(): title = string; description = string; priority = string; note = string; I am not sure about the PD, TOC and HOW parts. Could they be attributes of Idea or could they be separate models and in that case what could … -
setup django with domain name and static ip
I have a django app and it's time for deployment!! I know how to setup a django app on a local network but now I want to set it up using a domain name , let's say www.example.com . BUT I want to have a static ip as well. To sum up, I want the app to respond to www.example.com and the static ip. Is this possible? I am using Apache2 on Debian. my settings.conf for the apps I have installed so far are like that... <VirtualHost *:80> ServerName example.srcnet.com ServerAlias example2 ServerAdmin webmaster@localhost WSGIProcessGroup myapp WSGIScriptAlias / path/to/app/wsgi.py Alias /site_media/ /path/to/site_media/ Alias /static/ /path/to/project_static/ DocumentRoot /home/task2/task2_dev/task2/task/ <Directory /path/to/app/> Order allow,deny allow from all </Directory> ErrorLog /var/log/apache2/app-error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/app-access.log combined </VirtualHost> and in the interfaces file is: # The primary network interface allow-hotplug eth0 iface eth0 inet static address 192.168.1.117 netmask 255.255.255.0 gateway 192.168.1.1 -
How to model a Many-to-many relation when the target model is a tuple in django?
I have a model with translated text fields. Now the issue is that often i don't have translations for 'some' languages and i do like to publish the models already. An easy (default) ay out is to fallback to the default language (as per django model translations) but actually i'm thinking of explicitly enabling the instance for a language. For this i like to have a many-to-many relation with the LANGUAGES tuple from settings. So basically it's like a CharField with choices set to LANGUAGES but then in a select many fashion. One idea is to add a Language model for this and create a standard ManyToMany relation; but it doesn't feel right since i have nothing to add except for the language code itself; so why add a model.... Another alternative is to apply a PickleField and serialize a [] of language-codes. But that obviously is a quick/dirty solution as there is no validation etc... Anyone an idea on this issue? Paul -
clear items with optional delete button
I have a form with and input field for uploading files, Further I need to bind an optional delete button for my uploaded files, and make a separate event which needs to delete uploaded item and update my template, it will make a call through the api and update my template that the item was deleted. Now, my problem is that uploaded item is not removing from the array, I have tried to debug it and found some minor typos, call is going through the api and it is updating my template, but it want remove it, in first I was using remove() but I found out that for array objects it's better to use splice(), but I'm vary new to the angularjs so I'm little confused about how to deal with this, can someone help me understand it, I would like to learn as much as I can from this, so please bear with me. I will only put part of the code where I'm managing this events, because it's a big file, I can provide more info if needed. Form <form class="htmlForm"> <label for="id_payment_proof">{% trans "Payment proof:" %}</label> <div class="full-size"> <div class="input-control full-size file" data-role="input"> <input id="id_payment_proof" type="file" … -
How to call two html files same url in django
Main html file is base.html. Put register.html and login.html data in base.html. please check this url: www.payallpayments.com automatically will redirect to http://www.payallpayments.com/login/?next=/ if you are in this url: http://www.payallpayments.com/login/?next=/ login information that is showing is correct . if you click on signup button signup information is not correct. if you in this http://www.payallpayments.com/register login information that is showing is not correct . if you click on signup button signup information is correct. if you click on login button login related information will show. if you click on signup button signup related information will show. what i want: if i call http://www.payallpayments.com/ it should show login information and signup information. what are the changes i have to in urls.py and views.py files. register.html {% extends "base.html" %} {% block title %}User Registration{% endblock %} {% block head %}User Registration{% endblock %} {% block content %} <form method="post" action=".">{% csrf_token %} <table border="0"> {{ form.as_table }} </table> <button type="submit" value="Register">Register</button> <button type="button" onclick="window.location.href='/' ">Login</button> </form> {% endblock %} login.html <form method="post" action="{% url 'login' %}"> {% csrf_token %} <p class="bs-component"> <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> </p> <p class="bs-component"> <center><input … -
Error while fetching objects from Django model
I want to get all objects and count the length of the objects returned. I'm getting an error that I can't understand. This is my model class Codes(models.Model): username = models.CharField(max_length=100) code = models.CharField(max_length=10000) language = models.CharField(max_length=100) def __str__(self): return self.language I'm using the below function to get all objects from the model def get_all_codes(lang): queryset = Codes.objects.filter(language = lang) return queryset Calling the function all_codes_of_lang = get_all_codes(lang) and trying to count the length using: if len(all_codes_of_lang) > 0: print "abc" leading to this error: if len(all_codes_of_lang) > 0: File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 240, in __len__ self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__ results = compiler.execute_sql() File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) ProgrammingError: relation "submissions_codes" does not exist LINE 1: ...odes"."code", "submissions_codes"."language" FROM "submissio... ^ --> -
Scheduled, timestamped sqlite3 .backup?
Running a small db on pythonanywhere, and am trying to set up a scheduled .backup of my sqlite3 database. Is there any way in the command line to add a time/date stamp to the filename, so that it doesn't overwrite the previous days backup? Here's the code I'm using, if it matters: sqlite3 db.sqlite3 .backup dbbackup.sqlite3 .quit Running every 24 hours. The previous day's backup gets overwritten, though. I'd love to just be able to save it as dbbackup.timestamp.sqlite3 or something, so I could have multiple backups available. Thanks! -
Cannot import importlib
I am trying to use Listfield from djangotoolbox.fields but it is giving me an error saying : Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Library/Python/2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/coderahul/Desktop/Experiment Box/Innovation/Codeplay/codeplay/data_aggregator/models.py", line 9, in <module> from djangotoolbox.fields import ListField File "/Library/Python/2.7/site-packages/djangotoolbox/fields.py", line 4, in <module> from django.utils.importlib import import_module ImportError: No module named importlib What am I doing wrong? -
Django: setting template_name doesn't work in Class-based View
I have a ProductListView: class ProductListView(ListView): model = Product template_name = 'products/product_list.html' context_object_name = 'products' I tried to create another ListView listing Product: class VoteView(ListView): model = Product template_name = 'recommendation/rec_product_list.html' context_object_name = 'products' But when I tried to access VoteView in a browser, it occurs errors : it rendered product_list.html, not rec_product_list.html. So I debugged it and fount out that get_template_names() returns, ['recommendation/rec_product_list.html', 'products/product_list.html']. I could fix this by inserting this code: def get_template_names(self): return ['recommendation/rec_product_list.html'] But wonder whether there is better way than this one.. Thanks -
IndentationError: unindent does not match any outer indentation level tutorials
IS LEARNING FROM THIS LINK https://docs.djangoproject.com/en/1.10/intro/tutorial03/ MY CODE IS def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { ' latest_question_list': latest_question_list, } # output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(template.render(context, request)) AND THE ERROR IS RAISED File "C:\Users\ab\mysite\polls\views.py", line 9 context = { ^ IndentationError: unindent does not match any outer indentation level please help...........!!!!!!!!!! -
Plugin with editable link element
While implementing a Django CMS site, I’m a little stuck on link management (internal or external). In my project I have a specific box plugin the operator is to use quite often. I added screenshots of edit dialog and box rendering at the end of the question. The edit dialog is nice, but right now the button is just a char field. So the link selection, either to a page within Django CMS or to an external URL, is missing. I looked for a link field, but until now I am lost. How to add the feature to let the operator select an internal or external link ? The plugin consists of these parts: models.py from django.db import models from cms.models.pluginmodel import CMSPlugin from djangocms_text_ckeditor.fields import HTMLField class CardPlugin(CMSPlugin): title = models.CharField(max_length=256,default='') description = HTMLField(configuration='CKEDITOR_SETTINGS', default='') button = models.CharField(max_length=256,default='') def __str__(self): return str(self.title) cms_plugins.py class CardCMSPlugin(CMSPluginBase): model = CardPlugin name = 'Card' render_template = "card-default.html" card-default.html {% load cms_tags %} <section class="card card--primary-light"> <div class="card__inner"> <div class="card__content"> <div class="card__text"> <h2 class="card__title"> {{ instance.title }} </h2> <p class="card__description"> {{ instance.description }} </p> </div> {% if instance.button %} <div class="card__buttons"> <a href="#0" class="button button--primary-inverse">{{ instance.button }}</a> </div> {% endif %} </div> </div> … -
Redirect from https to https doesn't work. Can't find server, ngnix
I tried to run site on https instead of http and therefore to create a redirect. At the moment site works at https adress. If I enter http adress, redirect to https takes place but it says it can't find server. What am I doing wrong? Commented is what I have also tried. I don't really understand why server_name is _ in second configuration(which works), because it's a pre-installed image configuration on VPS upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://$host$request_uri; #listen 80; #server_name solomon; #return 301 https://closer.com$request_uri; #server_name solomon; #listen 80; #return 301 https://closer.com; } server { #listen 80 default_server; #listen [::]:80 default_server ipv6only=on; listen 443; ssl on; ssl_certificate /etc/ssl/simple_academy_cert_chain.crt; ssl_certificate_key /etc/ssl/server.key; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/django_project/django_project/media; } # your Django project's static files - amend as required location /static { alias /home/django/django_project/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; … -
How to turn on PostgreSQL VERBOSITY in django db connection?
This is a follow up question to this: Postgres: More verbose error message: I am missing the table name PostgreSQL 9.6 improved error messages with version 9.6. With psql you can enable it \set VERBOSITY verbose. How to enable this for every connection inside django ORM? Background: I want better error messages. Example: I am missing the table name in messages like this IntegrityError: null value in column "date" violates not-null constraint DETAIL: Failing row contains (10005, null, f, TEST, MAIL). I think the relevant part of the 9.6 release notes is this: Add support in libpq for regenerating an error message with a different verbosity level (Alex Shulgin) This is done with the new function PQresultVerboseErrorMessage(). This supports psql's new \errverbose feature, and may be useful for other clients as well. -
User-defined conditional standard local datetime format in Django
I have a Django project in which I have formats.py file for each of locales (English, French, Spanish, etc..). The formats.py looks like this: DATETIME_FORMAT = 'd b Y h:i' Now my goal is to define and replace 'd b Y h:i' by a user-defined format where I get 'h:i' for today, and 'd b Y h:i' for dates that differ from today. Is it possible in Django ? -
How to publish content in Django from a python script?
I have a script in python and I also have an installation of Django 1.10 and Django REST framework. With the script in Python I would like to authenticate and then send content from my content types. How is the best way to do this? My models are as follows: # Model of Reports class Report(models.Model): owner = models.ForeignKey(UserProfile) title = models.CharField(max_length=40) body = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title # Model of Invoices class Invoice(models.Model): owner = models.ForeignKey(UserProfile) report = models.ForeignKey(Report) uuid = models.CharField(max_length=36) emision_date = models.CharField(max_length=10) re = models.CharField(max_length=13) rr = models.CharField(max_length=13) type_invoice = models.CharField(max_length=2) def __str__(self): return self.uuid I think maybe send by json user and password, but how do I get a token ?, how do I send my content and the token? Those are my doubts -
Issue in user authentication
I have my header html file with option log in. I am extending this html in rest of my files. I am able to login in my home page. Home page contains a set of static data only. But from my home page, if I go to another page, then this logged in state is not maintained. What could be the issue? -
How to formulate a function for Django Celery task
I am trying to run a function in tasks.py(or celery.py) that sends email. The arguments "msg" and "email" will differ from one schedule to another. In the CrontabSchedule djcelery database table, I have several cron schedules example: CrontabSchedule: 0 4 * * * This cron is also linked to a task in PeriodicTask djcelery database tables . example: PeriodicTask: celery.send_email PeriodicTask and CrontabSchedule can be accessed by doing. from djcelery.models import PeriodicTask, CrontabSchedule The 3 models are linked through CrontabSchedule.id ---> PeriodicTask.crontab_id ---> Schedule.crontab_id myapp.models.Schedule is defined by me while theother 2 came from djcelery. Now, when celery goes into this cron schedules to run job task, how does the task SendEmail function will be able to know which "Schedule.message" and "Schedule.email" to use from the database table entry for the SendEmail function arguments "msg" and "email" respectively. This is a case of one task name many CrontabSchedule, PeriodicTask, Schedule entries. I will appreciate a skeleton(sample code) SendEmail function. Please help. I hope I explained it well cause its turning my head. tasks.py @task def SendEmail(msg, email): model.py class Schedule(models.Model): email = models.OneToOneField(MyCustomUser, unique=True) name = models.CharField(max_length=30, default='Example') message = models.CharField(max_length=918) startdatetime = models.DateTimeField(blank=False, default=datetime.now) recurrences = RecurrenceField() crontab_id = … -
django cannot import models from directory under app
I have dir structure like below picture. I would like to import models in thumbnail dir. However, I cannot get models. It just throw syntax invalid. from WebtoonServer.models I tried this as well import os import sys sys.path.append(os.path.abspath('../')) from WebtoonServer.models -
Django - How can I print a record by console?
I have 2 records in my database then I'm trying to print it like that: instance = People.objects.all() for item in instance: qs_name = item.name qs_user = item.user qs_password = item.password print qs_name,qs_user,qs_password I'm getting something like this: Kevin kjhf98 896687 Joe jwd22 336558 I want to store in a variable a single record, is that even possible? for example: Person_1 = Kevin kjhf98 896687 then if I print Person_1 I'll get only Kevin kjhf98 896687 I need this for something else that's why I'm asking for help.. any help would be apreciate!! thanks! -
ng2-bootstrap dropdown not found
I am having issue in my angular app to include ng2-boostrap. I am constently receiving this error in chrome console: GET http://127.0.0.1:8000/ng/node_modules/ng2-bootstrap/dropdown.js 404 (Not Found) Looking at how the ng2-bootstrap module is stored in my directory, it seems to me that zone.js should be trying to load this module instead: http://127.0.0.1:8000/ng/node_modules/ng2-bootstrap/dropdown/dropdown.module.js Here's my app.module.ts import: import { DropdownModule, TabsModule } from 'ng2-bootstrap'; /* Stuff */ And my systemjs.config /** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { var map = { 'app': 'app', // 'dist', '@angular': 'npm:@angular', 'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api', 'rxjs': 'npm:rxjs', // ng2-bootstrap 'moment': 'npm:moment', 'ng2-bootstrap': 'npm:ng2-bootstrap', 'ng2-charts': 'npm:ng2-charts', }; var packages = { 'app': { main: './app/main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, // ng2-bootstrap 'ng2-bootstrap': { format: 'cjs', main: 'bundles/ng2-bootstrap.umd.js', defaultExtension: 'js' }, 'moment': { main: 'moment.js', defaultExtension: 'js' }, 'ng2-charts': { main: 'bundles/ng2-charts.umd.js', defaultExtension: 'js' } }; var ngPackageNames = [ 'common', 'compiler', 'core', 'forms', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'router-deprecated', 'upgrade', ]; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Bundled (~40 requests): function packUmd(pkgName) { packages['@angular/'+pkgName] = … -
Cannot resolve keyword 'username' into field. Choices are: city, id, phone, etc
I would like to ask for help in these issue. I do know that it seems similar to other questions regarding the same issue, but I did look around and there was nothing that actually could solve my issue. Btw, it is my second asking here, so please tell me if this message is too long. Thanks! I am using AllAuth with Django 1.8 and Python 3.5 I want to implement a simple profile page based on the username provided from AllAuth. The issue is, I didn't specify the username or e-mail field in my model, I have only extended it to add some information that I would like to have, but it seems that Django only identifies the fields that I extended and I cannot find the right way to grab that information from AllAuth. Here is my code (some of the custom fields are in Portuguese, but all the core stuff is in english): profiles/models.py from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.utils.encoding import smart_text UF_CHOICES = ( ('SP', 'SP'), ('RJ', 'RJ') ) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) uf = models.CharField( max_length = 2, blank=False, default = 'SP', choices = UF_CHOICES, verbose_name …