Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create an input form for two related models
I have models Movie and MovieDescription therefore I want to create an input form for these two models. I want the input to take place from one joint form, where there will be fields: title, directed_by, genre, year, rate, synopsis. class Movie(models.Model): title = models.CharField(max_length=50, verbose_name='Title') directed_by = models.CharField(max_length=50, null=True, blank=True, verbose_name='Directed by') genre = models.CharField(max_length=90, null=True, blank=True, verbose_name='Genre') year = models.IntegerField(verbose_name='Year') class MovieDescription(models.Model): movie = models.OneToOneField('Movie', on_delete=models.CASCADE, null=True) synopsis = models.TextField(null=True, blank=True, verbose_name='Synopsis') rate = models.FloatField(null=True, blank=True, verbose_name='Rate') I have a problem with finding the most suitable django2.2 tool for this. -
Django console automatically reloading, when doesn't update anything
After run py manage.py runserver then server start to run and it shows on console, and it's doesn't stop just keep running over and over again, when doesn't code or anything changes please somebody solve this problem -
Why I get 405 Error during HttpResponseRedirect to https page?
Why I get 405 Error during HttpResponseRedirect to https url? def top_up_pay(request): template = 'payments/top_up_pay.html' conf_currency = AppConfig.get_config('subscription_price_currency') if request.method == "POST": amount = Decimal(request.POST.get('amount')) if conf_currency: req_user = request.user invoice = Invoice.objects.create( invoice_type=INVOICE_TYPE.TOP_UP, user=req_user, amount=amount, currency=conf_currency ) params = { "currency": invoice.currency, "amount": int(round(float(invoice.amount) * 100)), 'order_id': invoice.payment_no, } integration = FondyIntegration(params) redirect_to = integration.checkout_url() if request.is_ajax(): response = HttpResponse(json.dumps({'success': True, 'location': redirect_to}), content_type="application/json") print(redirect_to) #https url return HttpResponseRedirect(redirect_to) #405 Error -
Django for loop in template won't loop through the elements it's like one big string
I'm trying to do a simple loop but in Django I can't get it to output properly. It's printing everything like one big string. In python it loops through fine and it is a valid list, created an inputted into the postgres database. This is my function in my views.py def pages(request, id): obj = rtves_programas.objects.get(id=id) context = {'title': obj.title, 'show_date': obj.show_date, 'script' : obj.script, 'script_eng': obj.script_eng, 'description': obj.description, 'description_eng': obj.description_eng, 'show_id':obj.show_id, 'url': obj.url, } return render(request, 'rtves/pages.html', context) this element is a list → 'script_eng': obj.script_eng, and I want to printout the elements of the list. this is my code on the template. {% if script %} {% for sentence in script %} {{ sentence }} {% endfor %} {% else %} <p>Nothing here</p> {% endif %} But it's printing out everything in the list not the elements of the list, it looks like this if I just add this to the template it {{ script }} Similar to the loop but without the space -
How to avoid using `extra` when retrieve data from postgres?
I'm retrieving data from postgres DB with following code: values = ('foo', 'bar', 'group') FooBar.objects.order_by('-id').extra(select={'group': "'stackoverflow'"}).values(*values) The code works fine but I've heard that using extra is not preferable and even django documentations says to “Use this method as a last resort.” So the question is how it's possible to avoid using extra to retrieve data? -
Detect occurence of 504 while processing django view
I have a view which sometimes, takes a long time to process resulting in a timeout. I could handle this heavy processing in the background using background tasks in as celery. This for me however is not optimal because, I need to give feedback to the user, like imediately. Whenever I get timeouts, bad things happen and I end up with a model objects in an inconsistent state, missing some vital variables. I could easily remedy this by using atomic transactions but I dont know how to see a 504 event from the view. If it helps, I running django behind nginx Any help is appreciated. -
Which view functions can handle requests to this URL pattern?
Let's say I have the following URL pattern in my urlconf. urlpatters = patterns('blog.views', ... (r'^users/(?P<user_id>\d+)/(?P<country>\w+)', 'user_profile'), ... ) Which of the following view functions are correctly defined to handle requests to this URL pattern? 1. def user_profile (request, user_id, country=None): user_id = user_id country = country 2. def user_profile (request, user_id, **kwargs): user_id = user_id country = kwargs.get('country') 3. def user_profile (request, *args, **kwargs): user_id = kwargs.get('user_id') country = kwargs.get('country') 4. def user_profile (request): user_id = request.GET.get('user_id') country = request.GET.get('country') My best guess here was 1, 2 & 3, because 4 doesn't have enough argument parameters to be able to pass in the user id and country arguments. Why am I wrong? Which of the 4 can really handle requests to the url pattern above? -
Is there a way to make year constant in date_from and date_to in Django DateField and count the number of days from those two fields
In Django model i have two fields called date_from , date_to and number of days. The date_from and date_to are supposed to only have date and month so i need to set year with a default value which is don't know how to do.The number_of_days must be the number of days calculation from date_from and date_to. I need help on this issue. I'm new to django so i don't know how to do this date_from = models.DateField() date_to = models.DateField() no_of_days = models.CharField(max_length=50) so lets say the date_from needs to take in 22-2 and date_to as 22-3 without year from calender and the no_of_days must show as 30 counting the number of days from date_from and date_to. -
Django + uWSGI + Nginx instantly results in upstream prematurely closed connection
Firstly I have read probably every stackoverflow post related to this topic this Easter weekend. E.g. upstream prematurely closed connection (uwsgi + nginx + django) does not solve my problem because it was poor code which didnt even run via manage.py runserver. Most of the posts are about timeouts. This error is thrown immediately on a file that is less than 30KB. All my timeouts on Nginx and uWSGI are set at the default of 60s. It is not a timeout issue, but maybe a cache issue. I write some info from the database into a .xlsx file using openpyxl. When I return the file, it is about 27KB and it has about a 50% chance of not throwing the error. If it is quite a bit larger it fails every time, if it is quite a bit smaller it's okay every time. All other webpages work fine for the site. This is the error message: 2019/04/21 20:14:52 [error] 19712#19712: *46 upstream prematurely closed connection while reading response header from upstream, client: ipaddress, server: request: "GET / HTTP/1.1", upstream: "uwsgi://unix:////var/run/uwsgi.sock:", host: "www.mysite.com" The file can be downloaded successfully via manage.py runserver. It also runs successfully when I start uWSGI directly. … -
Django DRF: How to join tables and call a function?
I have a basic CRUD app made using Django Rest Framework where the app takes in a Delivery number from the user and lets them enter any issue with the Delivery for which the DeliveryIssue model is used in a simple modal form. I want to add a way where once the Delivery number has been entered on the form, it can lookup the Customer Name and Delivery Date present in the DeliveryInfo model and show it on the form itself before submission. And then that information is saved alongwith the DeliveryIssue model. class DeliveryIssue(models.Model): class Meta: db_table = 'APP_Delivery_Issue' delivery = models.PositiveIntegerField(db_column = 'Delivery') issue_category = models.CharField(max_length=200, db_column = 'Issue Category') issue = models.CharField(max_length=200, db_column = 'Issue') detail = models.TextField(db_column = 'Detail') created_at = models.DateTimeField(auto_now_add=True, db_column = 'Create Datetime') updated_at = models.DateTimeField(auto_now=True, db_column = 'Update Datetime') class DeliveryInfo(models.Model): detail = models.CharField(db_column='Delivery', max_length=50, blank=True, null=False, primary_key=True) customer = models.CharField(db_column='Customer', max_length=250, blank=True, null=True) delivery_date = models.DateField(db_column='Delivery Date', blank=True, null=True) class Meta: managed = False db_table = 'INFO_DELIVERY' I have read about pre_save, but unsure how to use this in here. Here is the serializers.py file from rest_framework import serializers from .models import DeliveryIssue class DeliveryIssueSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DeliveryIssue fields … -
Have detail view for transaction, transaction has a one to many relationship with sale. I want to display all sales with transaction in detail view
Im trying to display many side of a relationship in a detail view in django. A transaction can have many sales. my view below: class TransactionDetailView(DetailView): model = Transaction URL Below: path('transaction//', TransactionDetailView.as_view(), name='transaction-detail'), HTML below: <h1> Transaction</h1> <br/> <div class = "row"> <div class = "col-md-12"> <h4>Purchased Coins</h4> <table class="table"> <thead> <tr> <th scope="col">Coin</th> <th scope="col">Amount</th> <th scope="col">per Coin</th> <th scope="col">Total</th> <th scope="col">Value Per Coin</th> <th scope="col">Total Value</th> <th scope="col">Date Added</th> <th scope="col">Profit/Loss</th> <th scope="col">%Profit/Loss</th> </tr> </thead> <tbody> <tr> <td>{{object.currency}}</td> <td>{{object.amount}}</td> <td>{{object.amount_per_coin}}</td> <td>{{object.total_price}}</td> <td><p>Get From API</p></td> <td><p>{{object.amount}} * Get From API</p></td> <td>{{object.date_purchased|date:"F d, Y"}}</td> <td><p>TBC</p></td> <td><p>TBC</p></td> </tr> </tbody> </table> trying to create list of sales associated with transaction {% for sale in object.sales %} <p>kkk</p> {% endfor %} -
How to fix `sudo systemctl status gunicorn.socket` returns `Failed to dump process ..` while setting up gunicorn
I'm trying to set up the Ubuntu 18.04 server on DigitalOcean to serve the django web application by following official tutorial Using gunicorn like this: gunicorn --bind 0.0.0.0:8000 myproject.wsgi server is running just fine. But i got next problem while creating systemd socket and service files for Gunicorn. Home directory /home/sammy contains working directory named pjshop /home/sammy/pjshop: hand_made_ishop(django project directory) pjshop_env(virtual env directory) /home/sammy/pjshop/hand_made_ishop: wsgi.py ... /etc/systemd/system/gunicorn.socket file contains: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/pjshop ExecStart=/home/sammy/pjshop_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ hand_made_ishop.wsgi:application [Install] WantedBy=multi-user.target EnvironmentFile=/home/utility so when i run sudo systemctl start gunicorn.socket and then sudo systemctl enable gunicorn.socket, if i'm not mistaken, it should create some symbol link and return output to the terminal, but i got nothing.. then checking the status of the process returns next content: Failed to dump process list, ignoring: No such file or directory ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Sat 2019-04-20 18:27:51 UTC; 1 day 19h ago Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Apr 22 12:48:56 pjshop systemd[1]: gunicorn.socket: Socket unit configuration has changed while unit has … -
How can I display the number of items per category in Django?
i have many categories listed in my homepage and want to add just next to the category title the number of items Here is my view code ! def index(request): offres = OffresEmplois.objects.filter(available=True).order_by('-created_at')[:4] catoffres = OffresCategorie.objects.all().order_by('catname')[:10] num = OffresCategorie.objects.count(offres) return render(request, 'index.html', { 'annonces':annonces, 'firstzone':firstzone, 'secondzone':secondzone, 'offres':offres, 'catoffres':catoffres, 'num':num }) -
How To Separate Objects In Django Admin?
I have an app called 'Product' with the following models.py: class Product(models.Model): product_id = models.CharField(max_length=50) pub_date = models.DateTimeField(default=datetime.now) title = models.CharField(max_length=255) price = models.DecimalField(max_digits=8, decimal_places=2) user = models.ForeignKey(User, on_delete=models.CASCADE) featured = models.BooleanField(default=False) I want to have two separate sections in Django Admin: Products and Featured Products, depending if featured = True or False. So by default all products are listed under the Products section. But if featured = True they will be moved to Featured Products section. Can you please help me how to do that? Thanks in advance. -
Need Help Troubleshooting python requests - POST works, PUT fails - "Authentication credentials were not provided."
Trying to troubleshoot python requests to see if something is wrong when sending an authorization header via a put request, but not sure how to proceed. Any help regarding what I can do next to troubleshoot this would be appreciated. I have a Django-Rest-Framework API operating, and a second Django app that is attempting to talk to the API is having trouble. The API seems to be working fine, but I'm getting a strange "Authentication credentials were not provided" error when I send a PUT request from the second app using python requests. Below is a snippet of my script that generates a POST request when creating a new record, and a PUT request when updating an existing record. The POST request works, the PUT request doesn't - returns the auth error. The side function that generates the authorization header is the same and I've manually confirmed the Authorization header and key is correct. The endpoint url is correct. The data is identical. The endpoint url hits generic model views on DRF (ListCreate for the POST and RetrieveUpdate for the PUT). They both require the same auth level. if update and headers and payload: print "put request to %s with … -
No module named base while running python manage.py --settings=[mysettings]
While running command from terminal inside virtualenv I get the error ImportError: No module named base I'm running python 2.7 and Django 1.9.0 Hierarchy todobackend settings base.py test.py manage.py test.py from base import * import os # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'todobackend'), 'USER': os.environ.get('MYSQL_USER', 'todo'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'password'), 'HOST': os.environ.get('MYSQL_HOST', 'localhost'), 'PORT': os.environ.get('MYSQL_PORT', '3306') } } base.py """ Django settings for todobackend project. Generated by 'django-admin startproject' using Django 1.11.20. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(0v^617bonn76kaj!sj-q9o08l2wka7x-17kk)-_uc^x410aok' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'todos' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'todobackend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Taking data from two different models/tables and displaying it on the same page
I have two tables one called called PlayerLkup, which contains info about the player and serves as a lookup table. I have another table (called BattingStats) which contains a player's stats (and the playerid). The BattingStats table is a one-to-many (playerid is listed multiple times, one time for each season they played). My data from PlayerLkup is displaying fine, and it is using the playerid in the URL address to retreive a specific player. My question is how to I use the data from my BattingStats model/table onto that same page? I'm assuming my views page is where the work needs to be done. Is there a way to have multiple models passed into one view? I've tried same url, different views. It didnt seem to work for me. What do I need to do? Any help here would be appreciated. models.py class BattingStats(models.Model): playerid = models.CharField(db_column='playerID', max_length=9) year = models.IntegerField(db_column='Year', blank=True, null=True) g = models.IntegerField(db_column='G', blank=True, null=True) ab = models.IntegerField(db_column='AB', blank=True, null=True) r = models.IntegerField(db_column='R', blank=True, null=True) hr = models.IntegerField(db_column='HR', blank=True, null=True) rbi = models.IntegerField(db_column='RBI', blank=True, null=True) sb = models.IntegerField(db_column='SB', blank=True, null=True) class PlayerLkup(models.Model): playerid = models.CharField(db_column='playerID', primary_key=True, max_length=255) birthyear = models.IntegerField(db_column='birthYear', blank=True, null=True) birthmonth = models.IntegerField(db_column='birthMonth', blank=True, null=True) … -
Is appropriate/safe for Django dashboard to be public facing?
I understand that Django is an ORM that you can use to build APIs and external UIs for; dashboard allows ACL access and various data-management functionality. Is generally okay or not a good idea to allow public users to use portions of the dashboards, i.e. forms? -
I can't install stellar-base in python3
i tried installing Stellar-Base as it says here https://github.com/StellarCN/py-stellar-base but it doesn't work... i'm using a virtual environment and python3. here is the error `x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/home/sam/PycharmProjects/stellamomo/venv/include -I/usr/include/python3.6m -c src/_crc16module.c -o build/temp.linux-x86_64-3.6/src/_crc16module.o src/_crc16module.c:22:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/home/sam/PycharmProjects/stellamomo/venv/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-onsbk3g_/crc16/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-r5kwjf1o/install-record.txt --single-version-externally-managed --compile --install-headers /home/sam/PycharmProjects/stellamomo/venv/include/site/python3.6/crc16" failed with error code 1 in /tmp/pip-install-onsbk3g_/crc16/ ` -
When I make a POST request I'm getting "No credentials provided response"
I have a django server running on Linode, I'm trying to make a POST request but all I get is detail:"Authentication credentials were not provided." I already made my research and whenever I have the server in production, (port 80), it doesn't work, as soon as I make ./manage.py runserver 0.0.0.0:8000 it works, when I point my fetch to that URL. fetch(URL, method ='POST', headers = { 'Authorization': `Token ${this.props.token}` , 'Accept': 'application/json', 'Content-Type': 'application/json', 'Host': 'http://72.14.177.24' }, body= JSON.stringify( { user: 10, voltage_coil_1: 1, voltage_coil_2: 1, voltage_generated_by_user: 1, activity:1, datetime:null }) ) .then(res => res.json()) .then(console.log) My expected results are a positive answer, but whenever I'm in production, I keep getting this error. Server Response -
How to extend basic manager in django?
How to add custom method to the basic django manager? ModelNmame.objects.custom_method() -
Django2.2: best way to confirm form without js
I want to implement this algorithm: user submit a modelform if clean() method raise an error, I don't want to show form again. I want user to see a confirmation page with "confirm" or "cancel" buttons. What is the best way in this case? -
How to code split with django and webpack
I managed to include bundle splitting in the webpack.config.js, so I now have a main.js, vendors~main.main.js and a npm.core-js.js. In Django I'm loading the .js files with script-tags like that: {% load static %} <script src="{% static "frontend/main.js" %}"></script> <script src="{% static "frontend/vendors~main.main.js" %}"></script> <script src="{% static "frontend/npm.core-js.js" %}"></script> and in my frontend application I'm importing the libaries with an import statement import "core-js/stable" My problem is that Django already serves all bundles, how can I prevent django from serving everything at once and instead only load for example core-js if needed (when the user visits the page with IE)? Because my goal is code splitting and not bundle splitting -
Why when I run one test it passes, but when I run all the tests, it falls
I wrote tests for the administrator interface in django project and all tests pass separately, but when I run the class with tests, it fails. Class with tests (test_admin.py): from django.forms.models import model_to_dict from django.test import TestCase from core.tests.test_data import TestDataAbs from apps.doctor.models import Doctor, DoctorSchedule, DoctorSpecialization import apps.doctor.admin as admin_models OK_STATUS_CODE = 200 class TestAdmin(TestCase, TestDataAbs): def setUp(self): self.test_root_user = self.root_user self.client.login(username=self.root_user_test_data['username'], password=self.root_user_test_data['password']) def tearDown(self): self.client.logout() def test_add_doctor(self): admin_tickets_pages = TestDataAbs.get_admin_urls('doctor', admin_models) self.client.post(admin_tickets_pages['doctor_add'], data=model_to_dict(Doctor.get_first_or_create())) response = self.client.get(admin_tickets_pages['doctor_change']) self.assertEqual(response.status_code, OK_STATUS_CODE) def test_add_doctor_specialization(self): admin_tickets_pages = TestDataAbs.get_admin_urls('doctor', admin_models) self.client.post(admin_tickets_pages['doctorspecialization_add'], data=model_to_dict(DoctorSpecialization.get_first_or_create())) response = self.client.get(admin_tickets_pages['doctorspecialization_change']) self.assertEqual(response.status_code, OK_STATUS_CODE) def test_add_doctor_schedule(self): admin_tickets_pages = TestDataAbs.get_admin_urls('doctor', admin_models) self.client.post(admin_tickets_pages['doctorschedule_add'], data=model_to_dict(DoctorSchedule.get_first_or_create())) response = self.client.get(admin_tickets_pages['doctorschedule_change']) self.assertEqual(response.status_code, OK_STATUS_CODE) Run one test: Run class with tests: -
How to specify the elements that the forms.select() must show in django
i am developing a project with django, and i have a little problem. I am trying to make a forms.py, and i have a widget form with 'forms.select()'. I just want to know what can i do if i want to specify what elements of that widget should show: This is a part from my forms.py: fields = [ ... 'id_clasificacion_fk', ... ] labels = { ... 'id_clasificacion_fk': 'Clasificación del producto', ... } widgets = { ... 'id_clasificacion_fk': forms.Select(attrs={'class':'form-control'}), ... } As you can see, i have the widget 'id_clasification_fk' but it shows me all the elements that are in 'id_clasificacion_fk'. And you just want to show the elements that have "existencia=True". This is my models.py: class Articulo(models.Model): ... existencia=models.BooleanField(default=True) ... #llaves id_clasificacion_fk=models.ForeignKey('Clasificacion', null=True, blank=True, on_delete=models.CASCADE, db_column='id_clasificacion_fk') def __str__(self): return "("+str(self.id)+") " + self.nombre_producto Again, i just want to show the elements from id_clasificacion_fk that have the "existencia" set to True, and just these. If anyone could help me with this i appreciate. Thanks a lot.