Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix FileNotFoundError for imagefield in Django?
I'm trying to display an image uploaded by the superuser in django admin however it can't find the file path. I've added the media root to my settings.py file- MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' I've also added the following code in url.py if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) This is my model - class Component(models.Model): course = models.ForeignKey(Course, on_delete = models.CASCADE) module = models.ForeignKey(Module, on_delete = models.CASCADE, null = True, blank = True) title = models.CharField(max_length = 100) content = models.FileField(upload_to="files") # TXT or image date_of_creation = models.DateTimeField(default = datetime.now) date_of_last_update = models.DateTimeField(default = datetime.now) def __str__(self): return f'ComponentID: {self.id}, {self.course.title}(CourseID: {self.course}): {self.title}' def filetype(self): name, extension = os.path.splitext(self.content.name) if extension == 'jpeg': return ('image') if extension == 'jpg': return 'image' if extension == 'png': return 'image' else: with open(self.content.name, 'r') as file: data = file.read().replace('\n', '') return data I'm trying to call this code in the template {% for component in components %} <div class="component"> <p>{{component.title}}</p> {% if component.filetype == 'image' %} <img src="{{ component.content.url }}"> {% else %} <p> {{component.filetype}} </p> {% endif %} </div> {% endfor %} While the text file shows up fine, my image file throws an error. I can see … -
How to get a variable value of a post in django models ForeignKey?
I've created two models one for the post and another for comments. I want to get the title of the post in str by querying forginKey variable in Comments class is it even possible? i've tried using Comment._meta.get_field('post_id') but it wont works and I gets this error Exception Value: must be str, not ForeignKey My Models : class Post(models.Model): title = models.CharField(max_length=150) ... class Comment(models.Model): post_id = models.ForeignKey("post.Post", on_delete=models.CASCADE) ... def __str__(self): return self.name + " in post: " + Comment._meta.get_field('post_id') I want to get the value of title for every comment posted on site to show in Django admin. -
How to get SECURE_REDIRECT_EXEMPT to work?
I'm trying to have a single endpoint on my site that is not HTTPS (for some other service that does not support it). I have tried adding this to my settings.py as per: https://github.com/argenisosorio/django_ssl_secure_redirect SECURE_SSL_REDIRECT = True SECURE_REDIRECT_URLS = ['^'] SECURE_REDIRECT_EXEMPT = ['the_endpoint'] But it still redirects to HTTPS. Site is hosted on Heroku. Any suggestions as to how to fix it? -
How I could get information from an API request using the Django REST Framework?
I have two Model classes in Django. The first one is Document and the second one is Match. Every Document has zero or many Match objects. Matches are objects created after parsing the "text", they aren't saved in the database. I have to design an API REST in DRF with the next behavior: 1- The client send "text" and "lang" for a specific document. E.g: http://my.api.com/doc/1?text="This is a text"&lang="en-US" 2- The API server response has a set of Match objects for the corresponding document. 3- The document is updated fixing the matches problems. So, how can I get this kind of behavior using DRF? -
Why is response considering list item as string in Django rest?
I'm working on a case where when a user sends a post request with data, the data will be stored in a table and response all the objects in that table. I'm trying to implement JsonResponse in django-rest-framework. I created two of my model fields as ListFields and serialized the query set for response. But when the server is sending response, instead of being list items, they're shown as string values. Here's my code models.py: from django.db import models from djongo.models import ListField class Post(models.Model): title = models.TextField() cast = ListField() scenes = ListField() views.py: from rest_framework.response import Response from rest_framework.views import APIView from app1.models import Post from app1.serializers import PostSerializer class CreateView(APIView): def post(self, request): data = request.POST post = Post(**data) post.save() dat = Post.objects.all() print(dat) serializer = PostSerializer(dat, many=True) return Response(serializer.data) output: [ { "id": 1, "title": "['This is title']", "cast": "['1,2,3']", "scenes": "['4,5,6']" }, { "id": 2, "title": "['This is title']", "cast": "['10,20,30']", "scenes": "['40,50,60']" }, { "id": 3, "title": "['This is title']", "cast": "['10,20,30']", "scenes": "['40,50,60']" } ] Here the cast and scenes fields are shown as strings instead of Lists. Where am I going wrong? What should I do to make the fields in response … -
Django view data flow
I have a functional django service for more than one year wich implements some ~crazy~ payment rules for a sales team. Ofthen the directors change these rules, so to save time, in a delicate part of the code, I need a quick way to analyze the information flow in a django view. BTW I have huge tests to check if some alteration blow up all system. The view of interest are show below. from datetime import date from collections import OrderedDict from sales_report.models import * from django.http import JsonResponse from django.contrib.auth.decorators import login_required from itertools import chain import pprint from django.conf import settings def report(request, month, year): month_lock_status = report_lock.get_month(month, year) if month_lock_status['cod'] != 'ok': return JsonResponse(month_lock_status) if month_lock_status['msg'].is_locked == 1: response = { 'cod': 'report month is locked', 'msg': 'Carga travada para mês: ' + str(month) + ' ano: ' + str(year) } return JsonResponse(response) if month_lock_status['msg'].is_locked == 0: seller_history.clear_data(month, year) seller_report.clear_data(month, year) # sellers = seller.get_active_sellers() list_of_sellers = {} total_sales = 0 total_payment = 0 special_super_prize = prize.get_super_prize() ret = '' # É necessário percorrer os supervisores depois para que se faça o cálculo dos ganhos da equipe non_managers_qs = role_hist.get_managers(month, year, False) managers_qs = role_hist.get_managers(month, year, True) … -
Django save subclass with primary key of parent class
I have class named event in Django. With the url /<slug:slug_event>/new/ /<slug:slug_event>/<int:pk_round>/ I can access and create new rounds. Round has a foreign key to an event in the round/models.py file. So I created a form where you can select the event you want to attach the round to. Now I dont want to actively select the event field in the form, because you can only create a new round with the route posted above and so the PK of the event is given. Is there a way that I can save the event PK directly in the round/views.py file? -
Dropdown menu with submit POST
The Goal: Select name from dropdown menu, and send a POST with id to the url. The below code does not "POST". How can I modify the below code to POST the id to the url ? <form name="searchForm" id="searchForm" method='POST' action="{% url 'views:url' post.id %}"> {% csrf_token %} <div class="input-append"> <div class="btn-group"> <button class="btn dropdown-toggle" data-toggle="dropdown"> - <span class="caret"></span> </button> <ul class="dropdown-menu"> {% for user in current_users %} <li onclick="$('#searchForm').submit()"><a href="{% url 'views:url' post.id %}">{{ user }}</a></li> {% endfor %} </ul> </div> </div> </form> -
Commenting html/django template lines in Visual Studio 2017
I write a Django website in Visual Studio - but often instead of {# comment #} style I would prefer <!-- comment -->. Problem is, Visual Studio doesn't allow me just to change commenting style. That's really frustrating for me - could I get from you any tips how to change it? For example, after commenting I have this: {#<style> body { height: 100%; } html { height: 100%; } </style>#} and I want to have this: <!-- <style> body { height: 100%; } html { height: 100%; } </style> --> -
How would you rerender part of template without using 2 templates [Django]?
I want to rerender template.html with data from a python function in my views.py file. Basically, when an onclick event occurs im using ajax to make a GET request with template data. Now I just want to display the results of the function that is being called. The solutions I've seen so far, propose to use 2 templates where you simply use the "include" tag. Are there any other django tags or ajax properties that can accomplish this using a single template? -
I would like to use data from a table to create a selectmultiple list on my form
I am pretty new to python/django, but previously programmed in C# and VB.Net. I need to create a list on my django form that contains data elements from a PGSQL table. The user should be able to select multiple rows and then I would formulate a query that I would send back to the server. I have researched, but have not found anything to point me in the right direction. I will show my code below. -
Installing a specific version of GDAL within a Docker container?
I am trying to setup a Docker container for a Django site, but it relies on a version of GDAL that does not appear to be installable from the command line (1.8.1). In order to install this locally, I have to first run Configure and Make in the source folder. But I cannot find information online on how to run multi-step processes like this (perhaps running a bash script?) How do I instruct the Dockerfile to Configure/Make/Install from source? Also, is there a way to avoid having to containerize the source for this process? Specifics: Docker running Python2.7 alpine Django site RHEL 7.6 Thanks in advance -
Pushing Django app to heroku throws error "ImportError: No module named djangocms_history"
I have a Django project that I am trying to push to heroku. My requirements.txt file is Django==1.11.18 django-cms==3.5.3 django-sekizai==0.10.0 django-treebeard==4.3 djangocms-admin-style==1.2.9 When I try to deploy to heroku I get the following error: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", line 27, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/apps/config.py", line 94, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module remote: __import__(name) remote: ImportError: No module named djangocms_history remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to udsa-content-repository. remote: To https://git.heroku.com/udsa-content-repository.git ! [remote rejected] fixing-heroku-build -> … -
TypeError: get() got multiple values for argument 'task_id'
i have an endpoint that takes an id task/:task_id/. but when i try to access the id in the endpoint i get this error. TypeError: get() got multiple values for argument 'task_id' i tried to give task_id parameter a none default value. from huey.contrib.djhuey import HUEY from rest_framework.views import APIView class TaskStatus(APIView): def get(self, task_id): return Response({ 'result': Huey.result(task_id) }) url(r'tasks/(?P<task_id>[a-f0-9\-]{36})/', TaskStatus.as_view(), name='task-status'), i expect task_id to return the id from the url parameter. -
How to exit Django without CTRL+C after it finishes testing?
I am doing integration tests using django.test.SimpleTestCase. After running python manage.py test, the tests run successfully and the terminal hangs with the message: --------------------------- Ran 5 tests in 1.365s OK The problem is that currently I go back to the terminal using CTRL+C, but I want to have automated tests in my CI/CD pipeline. Did I do something wrong in the way I executed the tests? Or is this behaviour normal? In this case, is there an way in Bash to programatically execute and then exit the tests? -
Foreignkey translate to charfield
I 'm trying user to user message app.But sender and recipient is combobox ı dont want combobox.I want to charfield (input) sender and recipient. How to do this class mesaj(models.Model): sender = models.ForeignKey(User, related_name='gonderen',blank=True, null=True, on_delete=models.CASCADE) recipient = models.ForeignKey(User, related_name='alici',on_delete=models.CASCADE,null=True,) subject = models.CharField(max_length=250, blank=True) message = models.TextField() sent = models.DateTimeField(auto_now_add=True) -
Relation does not exist after deleting few tables
I have a postgres database, which naming midgard_dev. It has a many tables. After changing in models at product app I got error 'Column product_... does not exist'. I removed few tables in database, which related with product, and got error "Relation products_product does not exist. LINE 1: SELECT COUNT() AS "__count" FROM "products_product". I watched migrations (with ./manage.py showmigrations) and saw, that all migrations successful. makemigrations app and migrate --fake don't help respectively. Delete the entire database don't want. Thnx for help. -
How to Validate (list_display/editable) Django form fields including non list-display fields in the validation criteria
In the Django admin, I'm trying to validate a field in a form (this field is available as a list_display and list_editable field) using information in other non list-editable fields. I've so far overridden the clean method and performed the validation. This works fine when i'm in the Form Detail view /admin/core/binddetails/48/ but in the list display field, /admin/core/binddetails/ This doesn't work because some of the fields in the validation criteria are not available as a list_editable field I've also modified the get_changelist_form() as suggested by https://stackoverflow.com/a/8964559/6638281 class BindDetails(models.Model): field1 = models.BooleanField() field2 = models.CharField(max_length=255) field5 = models.BooleanField() class BindDetailsForm(forms.ModelForm): def clean(self): cleaned_data = super(BindDetailsForm, self).clean() field1 = cleaned_data['field1'] field5 = cleaned_data['field5'] if field1 and not field5: raise forms.ValidationError("'field1' cannot be enabled while 'field5' is turned off!") class BindDetailsAdmin(admin.ModelAdmin): model = BindDetails form = BindDetailsForm list_display = ('field1', field2') list_editable = ('field1', 'field2') def get_changelist_form(self, request, **kwargs): return BindDetailsForm I'd like a case where if field5 is disabled, but via the list_display page, I try to enable field1, A validation error is raised. -
How to get objects from two different tables that have a relationship to a third table using the related names in Django?
Let me explain. I have 2 tables which are child classes of another abstract table. The abstract table has a relationship to a model called Foo. The related_name is set dynamically. The code looks like this: class Foo(models.Model): ... class Parent(models.Model): foo = models.ForeignKey( Foo, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_related' ) ... def bar(self): print('bar') class Meta: abstract = True class ChildOne(Parent): ... class ChildTwo(Parent): ... Therefore, the related names become 'myapp_childone_related', and 'myapp_childtwo_related'. Now, lets say I want to call the bar() method of all the objects from the ChildOne and ChildTwo model that is related a Foo object called foo. Of course, I can do it like so: foo = Foo.objects.get(pk=1) references = ('childone', 'childtwo') for ref in references: children = getattr(foo, f'myapp_{ref}_related').all() for child in children: child.bar() This works fine, but honestly feels a bit hack-y, especially when dealing with more than two children classes. Is there a nicer, more Pythonic solution to this problem? -
Add extra field registration form
I created a user form in Django everything is working fine but I want to add another field of organization where user can put their organization but some how I am getting error unknown field. I try but still no luck. Always give me an unknown field error. Need little help with that from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import validate_email class SignUPForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'organization', ) def clean_username(self): user = self.cleaned_data['username'] try: match = User.objects.get(username = user) except: return self.cleaned_data['username'] raise forms.ValidationError("Username already exist, try different username") def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email = email).exists(): raise forms.ValidationError("Email already exist, try another email") return email def clean_password2(self): password1 = self.cleaned_data['password1'] password2 = self.cleaned_data['password2'] if password1 and password2: if password1 != password2: raise forms.ValidationError("password not match") def save(self, commit=True): user = super(SignUPForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.organization = self.cleaned_data['organization'] if commit: user.save() return user -
How to connect my root domain with deployed app
I currently have an app deployed on Heroku. Now I want to point my custom root_domain to it. Heroku provides no static Ips but only dns-targets. Unfortunately my provider only allows subdomains to be pointed dynamically via dns to the Heroku DNS target. But I want my root_domain to point there... I would like also to avoid changing the hosting, even though I have a feeling that won't be possible. I would go with digital ocean, since they offer a static Ip, but I have problems deploying my app there. I guess Python Anywhere does also not provide static Ips. Also I tried fixie, the Heroku add-on, but it is no compatible in my zone. So I am running out of options.... Is there any other way of pointing my root_domain to an heroku app that you could recommend? -
Django querying and listing all objects in a related many to many field
Trying to return in the admin page the manytomanyfield's table name in a list function with comma separation. class Machine(models.Model): class Meta: verbose_name = 'Machine' verbose_name_plural = '02 Machines' machine_type_choices = (...) valuestream = models.ForeignKey(Valuestream, on_delete=models.CASCADE) machine_number = models.CharField( max_length=6, help_text="Please exclude the 'm' in the machine number", unique=True, validators=[ MinLengthValidator(4, message="Machine numbers have to be greater than 3 digits long"), ] ) machine_type = models.CharField(max_length=50, choices=machine_type_choices) machine_brand = models.CharField(max_length=30, blank=True) pub_date = models.DateTimeField(auto_now=True) pass def __str__(self): return str(self.machine_number) class SWS_Document(models.Model): class Meta: verbose_name = 'SWS Document' verbose_name_plural = '03 SWS Documents' machines = models.ManyToManyField(Machine, related_name='SWS_documents') document_description = models.CharField(max_length=150, default="") pub_date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.machines.machine) The last bit of code is what I can't figure out. I'm trying to return all related machines in a list that is associated to SWS_Document. -
Running an external Python script on a Django site
I have a Python script which communicates with a Financial site through an API. I also have a Django site, i would like to create a basic form on my site where i input something and, according to that input, my Python script should perform some operations. How can i do this? I'm not asking for any code, i just would like to understand how to accomplish this. How can i "run" a python script on a Django project? Should i make my Django project communicate with the script through a post request? Or is there a simpler way? -
Too many redirects - nginx
Nginx gives too many redirects error--think it maybe has to do with the proxy_pass in location / because when I change that, I occasionally get server error 400 or 500 but no fix :( I'm using an AWS ec2 instance with nginx. I am able to access the ***.com/static/ folder with no redirect issues. I've tried many different servers for upstream and have done just about every solution suggested on stackoverflow/digitalocean. I am kind of new to nginx so it is probable that I am making a simple mistake. Here is my config: worker_processes 4; pid /run/nginx.pid; events { worker_connections 1024; } http { ## # Gzip Settings ## sendfile on; gzip on; gzip_http_version 1.0; gzip_proxied any; gzip_min_length 500; gzip_disable "MSIE [1-6]\."; gzip_types text/plain text/xml text/css text/comma-separated-values text/javascript application/x-javascript application/atom+xml; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; upstream serv { server 127.0.0.1:80; } server { listen 443 ssl http2; server_name www.***.com; access_log /var/log/nginx/***.com.access.log; error_log /var/log/nginx/***.com.error.log; ssl on; ssl_certificate /etc/letsencrypt/live/www.***.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.***.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot return 301 https://***.com$request_uri; … -
How to Make DataTables Load Data as Needed with AJAX Sourcing from Django
I am attempting to serialize a Django queryset, return the results to a URL, and point a DataTable to the resulting URL. This potential solution arose to address the issue of slow performance when loading thousands of rows from Django into a DataTable through the DOM. I have a view: from django.http import HttpResponse from django.core import serializers def json_ouput(request): objects= MyModel.objects.all() json = serializers.serialize('json', objects) return HttpResponse(json, content_type='application/json') The view connects to this URL: url(r'^home/json_ouput/$', views.json_ouput, name='json_ouput_url',), My temlate points to this URL as the AJAX source for the DataTable: <table id="example"> <thead> <tr> <th>Description</th> <th></th> </tr> </thead> <tbody></tbody> </table> <script defer type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').dataTable( { "processing": true, "ajax": { "processing": true, "url": "{% url 'json_output_url' %}", "dataSrc":'' }, "scrollY": 800, "deferRender": true, "scroller": true, "columns": [ { "data": "fields.description" }, { "data": "pk" } ] }); }); </script> Results are displayed after about 40 seconds for 9,000 rows. This is the same performance that occurs with loading the data through the DOM (not serialized into JSON) and without DataTables Scroller. My understanding, was that Scroller would not load all data, but it appears to load all data at once (i.e. all 9,000 rows are in …