Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What would the best way in Django to create, compile, format and generate a file?
I am looking for to produce a file using labels on the left of the page, by clicking on the label, I would get Title dropping down. When clicking on the title, a form could be displayed with prepopulate form field or not and textbox. I would like to have the choice between different prepopulated form field if possible. At the end, I could create a file with all the labels displayed as the title and compiling all the forms into one document. It would respect a pre-formating to make it easier. At any time, the final document could be viewed in HTML format. And we could generate it and save it in a folder, with Revision n°. -
Django serializer is not returning JSON data
I have a model Domain: class Domain(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name And a corresponding serializer: class DomainSerializer(serializers.ModelSerializer): class Meta: model = Domain fields = ('name',) I'm trying to serialize a queryset in a view like this: def getDomains(request): domains = Domain.objects.filter(name__startswith=request.GET['name_startsWith']) data = DomainSerializer(domains, many=True) print(data.data) return HttpResponse(data.data) This is not working correctly, and data.data is : [OrderedDict([('name', 'Math')])] I would like to have a JSON object, something like: {'name': 'Math'}. -
How to sort a ChoiceField in a ModelForm?
I have a model that contains a user field. usr = models.ForeignKey(User, related_name='+', limit_choices_to={'is_active': True}) I have a ModelForm (shown below) that allows the usr to be set: this all works fine. However, the list of users is presented in a random order. class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['usr', ] How can I sort the list of active users in the drop down? -
Django connection to postgres by docker-compose
My django project cannot connect to postgres database container. What I should to do? It crashes on commands python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate. I know docker run command creates a new container but I have more commands as one by bash in docker-compose.yml. It should works, shouldn't it? my Dockerfile: FROM python:3.6-alpine MAINTAINER Name <name@domain> ENV PYTHONUNBUFFERED 1 ENV INSTALL_PATH /heckblog RUN mkdir -p $INSTALL_PATH WORKDIR $INSTALL_PATH COPY requirements.txt requirements.txt # make available run pip install psycopg2 RUN apk update && \ apk add --virtual build-deps gcc python3-dev musl-dev && \ apk add postgresql-dev RUN pip3 install -r requirements.txt # add bash into alpine linux RUN apk add --update bash && rm -rf /var/cache/apk/* COPY ./heckblog . #RUN pip install . CMD gunicorn -b 0.0.0.0:8000 --access-logfile - "config.wsgi:application" my docker-compose.yml: version: '2' services: db: image: postgres:alpine environment: POSTGRES_USER: blogdmin POSTGRES_PASSWORD: password POSTGRES_DB: heckblog PGDATA: /tmp/pgdata volumes: - postgres_data:/tmp/pgdata web: build: . command: > bash -c "sleep 10 && python manage.py collectstatic --noinput && python manage.py makemigrations blog && python manage.py migrate && echo \"from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'pass')\" | python manage.py shell && gunicorn -b 0.0.0.0:8000 --access-logfile - --reload \"config.wsgi:application\"" … -
How to send the user to a section of the template if it meets condition
very good, I have a template which lists items in a table and make a condition that if the statistical field is 0 then do not show that table and take it to the textinput of the model form to enter the statistic Here the template, html: {% if estadis.estadistica == 0 %} <section id="contenido"> <div class="container" style="margin:50px auto width="100%""> <form id="myform" method="post"> {% csrf_token %} {{form.as_p}} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <a href="{% url "usuario:lita_todo" especialidad.id %}" method='GET' type="submit" class="btn btn-primary pull-right" value="editar" onclick="document.location.reload();"/>Ingresar</a> {% else %} <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> <td>Ingresar</td> </tr> </thead> <tfoot> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> <td></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ ped.especialidad.nombre }}</td> <td>{{ ped.articulo.cod_experto }}</td> <td>{{ ped.articulo.nombre }}</td> <td>{{ ped.cantidad }}</td> <td><a href="{% url "usuario:cant_ingresar" ped.id especialidad.id %}" method='GET' type="submit" class="btn btn-primary pull-right" value="editar" onclick="document.location.reload();"/>Ingresar</a></td> </tr> {% endfor %} {% endif %} </tbody> </table> </form> </div> </section> </div> {% endif %} Here the views.py where I show the data of the table and call the Form models: def ListAll(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': user = request.user … -
How do you change the href attr in Jquery if the html has static tag?
I have 2 stylesheet versions one is tile view and the other is list view. How do I change hrefs if the html code is in a static tag? My code doesn't seem to work HTML <link rel="stylesheet" type="text/css" href="{% static "Stylesheets/tileVersion.css" %}"> JQUERY $('#listicon').click(function () { $('link[href="static/Stylesheets/tileVersion.css"]').attr('href', 'static/Stylesheets/listVersion.css'); }); -
invitation being called twice when sending
I have used django-invitations for invitation feature. I have used a form in homepage which asks for email address of the user. When user fills the email and hit the submit button. It is redirected to invitations/send-invite/ and again shows the form as in the screenshot This is the homepage. I have filled the email address which has been never invited and whilst submitting the form, the page was redirected which is shown in second screenshot. The email has never been invited before but it still says it has already been invited Here is the configuration with the code urls.py url(r'^invitations/', include('invitations.urls', namespace='invitations')), url(r'^accounts/', include(allauth_urls)), home.html <form action="{% url 'invitations:send-invite' %}" method="POST" id="invite-form" class="form-horizontal"> {% csrf_token %} <div class="input-group"> <input type="text" name="email" id="id_email" value="" class="form-control validate-email" placeholder="Enter your email address to request invitation" > <span class='input-group-btn'> <input type="submit" value="REQUEST INVITATION" class="btn btn-primary generic-ajax-submit"> </span> </div> </form> settings.py ACCOUNT_ACTIVATION_DAYS = 7 ACCOUNT_INVITATION_DAYS = 7 INVITE_MODE = True ACCOUNT_ADAPTER = 'pages.login_redirect.AccountAdapter' I have already ACCOUNT_ADAPTER for allauth and i am confused on what to do with django-invitation's ACCOUNT_ADAPTER. Where have i done mistake? Did i miss anything? -
How to run django project without virtual environment
I'v downloaded django project which I need to modify. But there is no such thing as virtualenv, and I have always launched by python manage.py runserver which is only possible after source virtualenvname/bin/acivate the structure is the following: project project.sql manage.py requirments.txt How do I run it with this structure ? I just need to modify it as it is -
Django admin date picker for search
I would like to use the Django date picker widget for searching in the admin. Lets suppose I have a model with field date_created. In the admin, I would like to have a date picker for date_created with start and end ranges using which I can filter the results. -
Django admin: view hangs on field_sets block
I have encountered a weird behaviour where one of the admin views which is quite simple and straight forward takes a while to load up until an nginx timeout in prod. Through Django debug toolbar and new relic I have found that the guilty code is the field_sets block in Django templates, which makes it way harder to debug. On production, when the view does load, it is empty. This is the first time I encounter something like that, and thus I decided to reach out to the community for help. The model: from datetime import timedelta from decimal import Decimal from django.conf import settings from django.contrib.auth.models import User from django.db import models from django.utils import timezone from django.utils.crypto import get_random_string from django.utils.translation import ugettext as _ from core.common.models import (SoftDeletableModel, TimeStampedModel, UniqueFieldMixin, FlagableMixin) from core.models import Pair from payments.utils import money_format from ticker.models import Price from django.core.exceptions import ValidationError class Order(TimeStampedModel, SoftDeletableModel, UniqueFieldMixin, FlagableMixin): USD = "USD" RUB = "RUB" EUR = "EUR" BTC = "BTC" EXCHANGE = 2 BUY = 1 SELL = 0 TYPES = ( (SELL, 'SELL'), (BUY, 'BUY'), (EXCHANGE, 'EXCHANGE'), ) _order_type_help = '{} - {}<br/>{} - {}<br/>{} - {}<br/>'.format( 'BUY', 'Customer is giving fiat, … -
ContentType doesn't declare an explicit app_label
I am deploying a Django 1.10 project onto an Ubuntu server with Apache and mod_wsgi. I am getting the following 500 error which I can't solve: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. installed_apps in settings.py: INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', ] wsgi.py: sys.path.append('/home/x_dashboard/x_dashboard/') activate_this = os.path.expanduser("/home/x_dashboard/.venv/bin/activate_this.py") execfile(activate_this, dict(__file__=activate_this)) os.environ['PYTHON_EGG_CACHE'] = '/home/x_dashboard/x_dashboard/.python-egg' os.environ['DJANGO_SETTINGS_MODULE'] = 'x_dashboard.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() Apache config: <VirtualHost *:80> #ServerName example.com #ServerAlias www.example.com #ServerAdmin username@example.com DocumentRoot /home/x_dashboard/x_dashboard/ #ErrorLog /var/www/html/example.com/logs/error.log #CustomLog /var/www/html/example.com/logs/access.log combined WSGIScriptAlias / /home/x_dashboard/x_dashboard/x_dashboard/wsgi_local.py #Alias /robots.txt /var/www/html/example.com/public_html/robots.txt #Alias /favicon.ico /var/www/html/example.com/public_html/favicon.ico #Alias /images /var/www/html/example.com/public_html/images Alias /static /var/www/x_dashboard/static <Directory /home/x_dashboard/x_dashboard/x_dashboard/> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> </VirtualHost> The Django documentation says that an app_label is required for models which do not belong to an app defined in installed_apps. However, 'django.contrib.contenttypes' is defined in installed_apps, so I don't understand the problem. Any help appreciated. -
How can I make tests that combine Selenium and Django when the development server can't run recent browsers?
I am working with a Django application running on the host foo-dev:8000, which runs Red Hat Enterprise Linux Server 6.8. I have python-based Selenium tests that run on my Windows 10 workstation as foo-dev is unable to use recent Selenium-supported versions of Chrome or Firefox. I would like to use Django in my Selenium tests to verify the database impact of the Selenium interactions. As an example, there is a page in the application that displays a form for registering a device. I want to write a test that uses Selenium to fill this form and register the device on the Django test database. Once added, I want to use Django to assert that the device was added. I would then like the device entry to be cleared from the test database. The browser that performs these interactions has to run on the Windows 10 workstation, not foo-dev. What do I need to do to accomplish this? Is it possible to use django unit tests on a separate machine from the server that runs the app? -
Django Rest Auth Query Based Authentication token restart
I am building a django application and I am stuck with the following issue. The token has an expiry time and I want to create an api endpoint which if visited refreshes the user token availability. Due to the nature how I handle the rest of the app, I need to use query based authentication. I implemented this as following: In my authentication.py: from rest_framework.authentication import TokenAuthentication class QueryStringBasedTokenAuthentication(TokenAuthentication): def authenticate(self, request): key = request.query_params.get('auth_token').strip() if key: return self.authenticate_credentials(key) else: return super(QueryStringBasedTokenAuthentication, self).authenticate(request) And I have updated the settings accordingly: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'authsys.auth.QueryStringBasedTokenAuthentication', ) } Now I saw some question on how to achieve what I desire using the standard header tokens. How would I do that with query based authentication? Thanks in advance! Lukas -
Iterate a queryset
When I type in python console something like: for n in users: sum_up.filter(order__user_id=n.get('order__user_id')).aggregate(a=Sum('user_cost')) It gives me: {'a': Decimal('5.500')} {'a': Decimal('14.500')} Is there a way to render those results in a template? -
Able to access only last element of list in Python unicode dictionary
My Python unicode dictionary looks like this: `<QueryDict: {u'csrfmiddlewaretoken':[u'oacUfIz5q2tPtmSoqCQi7tBDn2ejpt4x9ZiFeLKeIOyB2CHvAoJqbe1cHNZJSObP'], u'Date and Events[]': [u'2000-09-09', u'bday', u'second']}>` When I try to access the element with key 'Date and Events[]', I get only the last element of the list. Any idea why this occurs? -
Django render on the same template
I try to create a pagination, so i use a some lines of JS to send data, i catch it correctly (and can print it in the console) and i see they are different but my render never change. Template.html: <p> THIS IS THE PAGE {{ page }} </p> <div class="col-xs-12 center"> <ul class="pagination" > <li><a href="#" value={{ page|add:"-1" }}>&laquo;</a></li> <li><a href="#" value=0>1</a></li> <li><a href="#" value=1>2</a></li> <li><a href="#" value=2>3</a></li> <li><a href="#" value=3>4</a></li> <li><a href="#" value=4>5</a></li> <li><a href="#" value={{ page|add:"1" }}>&raquo;</a></li> </ul> </div> <script language="javascript"> $('ul.pagination li a').on('click', function(e){ e.preventDefault(); var page = new XMLHttpRequest(); xhr.open('POST', '/index/', true); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); xhr.send($(this).attr('value')); }) </script> Views.py: def index(request, page=0): print('DATA SEND:', request.body) if request.method == 'POST' and request.body: page = int(request.body.decode('utf-8')) return render(request, "site/index.html", {'page': page}) So I think if i'm on /index/ i can't do a new render of index with new variable (and new render with this variable as well) ? Do you have an idea when i can do that ? -
Bulk adding multiple "events" in the django admin interface
What I have I have a model of events. Each event can have many occurrences. models.py: ... class Occurrence(models.Model): start_date = models.DateField(null=True, blank=True) event = models.ForeignKey('Event') ... class Event(TranslatableModel): ... What I want I want a nice way to add multiple similar events with a single date (occurrence). Some thoughts I thought of adding a single event with many occurrences and then turn them into a single events (with a Button "Turn Occurrences into Events"). So I need to iterate over the occurences and save an event for each. But how do I loop over the occurences from the Admin interface, save them and delete the original event? Alternative I thought of creating a bulk adding Interface like this: admin.py: ... class BulkAddEvent(Event): class Meta: proxy = True class BulkAddEventAdmin(EventAdmin): def save_model(self, request, obj, form, change): pass # I don't know what to do here. ... In any case I need to override the save_model function. But the question of iterating over the occurences remains. Can someone help? Versions Python Version 2.7.12 Django Version 1.8.16 -
Image is not uploading after submiting form
When I'm trying to upload a user profile picture using form, which allowing users to edit their account information - nothing is happening. I'm not sure what should I do, to get this upload working. models.py: class UserProfile(models.Model): objects = models.Manager() user = models.OneToOneField(User) image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username forms.py: class EditProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ( 'image', ) views.py: def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect(reverse('accounts:view_profile')) else: form = EditProfileForm(instance=request.user.userprofile) args = {'form': form} return render(request, 'accounts/edit_profile.html', args) settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mainapp/media') edit-profile.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> -
Ident authentication failed for user "graphite"
I'm in the process of installing Graphite. I'm using postgresql under Centos 7.3. When I go to import the django schema into postgres, I get the following TB: [root@hera graphite]# PYTHONPATH=$GRAPHITE_ROOT/webapp django-admin.py migrate --settings=graphite.settings --run-syncdb Traceback (most recent call last): File "/usr/bin/django-admin.py", line 5, in <module> management.execute_from_command_line() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 89, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/lib/python2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/lib/python2.7/site-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/lib/python2.7/site-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/lib/python2.7/site-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/usr/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/lib/python2.7/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/usr/lib/python2.7/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/usr/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/usr/lib64/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: … -
django.db.utils.OperationalError: cannot ALTER TABLE "forum_thread" because it has pending trigger events
models.py class Thread(models.Model): title = models.CharField(max_length=300) answer_count = models.PositiveIntegerField(default=0) added_at = models.DateTimeField(auto_now_add=True) accepted_answer = models.ForeignKey('forum.Post', null=True, blank=True, related_name='+') I am trying to change accepted_answer ForeignKey to BooleanField ex: accepted_answer = models.BooleanField() and getting migration error "pending trigger events error". please take a look. -
How to integrate django-viewflow without the front end?
There is the library Viewflow that I would like to use. I don't need the front end because I already got mine. I've been following the quickstart but I don't see how I can integrate viewflow, without using the front end because there are a lot of relations to the material app. Any ideas? -
I was looking for a real time notification system for HTML Django web app
After researching I came across pusher and also reading some of the previous answers about web sockets. Since on pusher there is tutorial but they have implemented it on flask( https://pusher.com/tutorials/realtime-notifications ) also I am not too sure about how to approach push notification for Django(1.8.4) web app so can anyone through some light on the push notification part in Django. -
Jquery send empty data to Django
Info: i'm using python 3.6 and Django 1.10.6. I try to send a simple dict to change my number of page, but i don't use a form. So i read many tutorials when they use XMLHttpRequest and it's work. But in my situation, i just receive an empty query. Template.html: <html> <p> You select the page {{ page }} </p> <ul class="pagination" > <li><a href="#" value={{ page|add:"-1" }}>&laquo;</a></li> <li><a href="#" value=0>1</a></li> <li><a href="#" value=1>2</a></li> <li><a href="#" value=2>3</a></li> <li><a href="#" value=3>4</a></li> <li><a href="#" value=4>5</a></li> <li><a href="#" value={{ page|add:"1" }}>&raquo;</a></li> </ul> <script language="javascript"> $('ul.pagination li a').on('click', function(e){ e.preventDefault(); var val = { 'page': $(this).attr('value'), } var page = new XMLHttpRequest(); xhr.open('POST', '/index/', true); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); xhr.send(val); }) </script> </html> Views.py: def index(request): page = request.POST.get('page', 0) #POST ARE YOU HERE ? print('[TEST]', request.POST, page) return render(request, "site/index.html", {'page': page}) When i show my console i always have empty query, so it's normal page=0. Console log: [TEST] <QueryDict: {}> 0 I when to receive a dict like {'page':'1'} sending by a click on the a -
Filter records before Django admin renders a model data
So, I have a model named foo. My requirement is to show a filtered list of records on the admin dashboard for foo. Basically, I want to filter the QuerySet even before admin renders the view for foo. Is there a way to do this? Django == 1.7, Python == 2.7 I use Grappelli to render my admin site. -
pace.js monitor xhr request and options set it as false
I'm using pace.js to add progress bar to our application, but I want pace.js just to monitor 2 divs with ids Code <head> {% compress js %} <script src="{% static 'js/pace.min.js' %}"></script> <script> window.paceOptions = { "ajax": false, "eventLag": false, "document": false, "restartOnPushState": false, "restartOnRequestAfter": false, "elements": { "selectors": ['#home', '#videos'] } } </script> {% endcompress %} ... </head> But pace.js is still refreshing with each AJAX/xhr request. Note: I'm using django-compressor to minify the js.