Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin - Detect changes in inline fields
I am pretty new to python. I have Models named Project and ProjectTopic. class Project(models.Model): name = models.CharField(max_length=250) description = models.TextField() class ProjectTopic(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=250) In the admin.py, I have added the ProjectTopic as an inline field. Now the requirement is I need to send a notification if there is any change in the project that includes the ProjectTopic section. I have added def save_model(self, request, obj, form, change): if 'description' in form.changed_data: send_notification() super().save_model(request, obj, form, change) But don't know how to track the changes in the inline ProjectTopic section. -
Django render template on AJAX success
I am trying to make a web application based on Django that takes user input and performs Heavy background task that completes in almost five to ten minutes. When the background task is completed, few parameters are supplied to the template to render. Everything works fine and the page loads after that. But when I am trying to use AJAX for this as it does'nt seems good that the page is loading for so long due to background heavy processing, I am not able to figure out how to reload the page (Though I am able to show an alert on completion but instead of this I want to re-render the page) Here is my views.py code: def index(request): #All Background process code goes here return render(request, 'form.html', {'scanResults' : scanResults, 'context_list' : context_list, 'scanSummary' : scanSummary}) Here is my AJAX call <script type="text/javascript"> $(document).on('submit','#scanForm', function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/scanner/', data: { email: $('#email').val(), context: $('#context').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(response){ alert('Scan Completed'); location.reload(); } }); }); I am not able to figure out, what should I write in success function to reload the page that index function has returned to template. My main motive is to show a progress β¦ -
Why My Conversion LatLongs are slightly difference in GeoDjango?
There are two models in my Projects, One having the Parcel data and another having the Building Data. My Aim is to Locate the building coordinates on Parcel. My parcel coordinates are in california_zone 2(ESPG=3492), and my Building coordinates are ESPG=4326. That's why I am converting both into ESPG=4326. And both coordinates are relating to Sacramento City 16Th street 2712 zipcode:95818. and then I define the GEOSGeometry set and filter the object in Building Data with the poly coordinates(geom) and finally get one Object and took the coordinates of that object and then try to locate them in Google maps. But those are not locating at same location. I don't know what I am doing wrong in this. Can you please suggest me What is the right way to locate the coordinates at same location. parcel = Parcel.objects.filter(objectid="22520").values() geojson = parcel[0]['geom'].geojson ast_format = ast.literal_eval(geojson) data = ast_format['coordinates'][0][0] poly_california = Polygon(data, srid=3492) poly_gps = poly_california.transform(4326, clone=True) pnt = GEOSGeometry(poly_gps) building = Primary.objects.filter(geom__contained=pnt).values() build_geo = building[0]['geom'].geojson build_format = ast.literal_eval(build_geo) build_coords = build_format['coordinates'][0] These are the Parcel Coordinates (((-121.49440799279022, 38.55725848782723), (-121.49438844924772, 38.557303481514126), (-121.4943760310021, 38.5573320694682), (-121.49436263531841, 38.557362909896675), (-121.49402385986245, 38.557269114460084), (-121.49406987333441, 38.55716268909225), (-121.49440799279022, 38.55725848782723)),) These are the Building coordinates [[[-121.494079, 38.557279], [-121.49411, 38.557199], [-121.494246, 38.557232], β¦ -
Django 2.0 admin save functionality breaks when defining a custom manager
I am just starting to learn the Django framework, and I started with Django 2.0. I am creating just a simple site to mess around with, and I created a custom manager to get all objects that are in a "published" state. However, when I added this manager, it broke the admin's site Save/Edit/Delete functionality, and provides me with the error: Manager isn't accessible via Post instances Where the Post is the object that I have defined a custom manager for. (Forgive me if I am butchering the terminology). The traceback for this error isn't particularly easy to follow either. Some code that will hopefully help. Custom manager in my models.py file class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') Registering the managers in my Post class: class Post(models.Model): ... objects = models.Manager() published = PublishedManager() tags = TaggableManager() When I comment out the published = PublishedManager() line, all functionality is restored to the admin site. What is going wrong with the custom manager? Do I need to tell Django somewhere to use this in addition to the default manager? I definitely need to do some more learning, but this ones driving me crazy. Thanks all! -
How to Do a Multi-step form in Django Class-based CreateView
I have multiple class-based createviews. My goal is to link all createviews such that when I post the first createview, it will redirect me to the second createview where it will retrieve the data entered from first createview. Does anyone know the solution to this? The first createview (Step01) contains django-inline-formset-factory code which is similar to this code, while the rest (Step02 and Step03) contain basic code. I have referred to this link, but the solution is based on using function-based view. Have also made attempt using Django's Form-Wizard, but handling django-inline-formset with it is still too complicated for me. This is my current code: models.py class Model_Step01_Cart(models.Model): cart_name = models.CharField(max_length=100) class Model_Step01_CartItem(models.Model): cart = models.ForeignKey(Profile) item_name = models.CharField(max_length = 100) item_quantity = models.FloatField(null = True, blank = True) class Model_Step02_Staffnote(models.Model): note_staff = models.TextField(max_length = 500, null = True, blank = True) class Model_Step03_Managernote(models.Model): note_manager = models.TextField(max_length = 500, null = True, blank = True) forms.py class Form_Step01_Cart(forms.ModelForm): class Meta: model = Model_Step01_Cart fields = ["cart_name"] class Form_Step01_CartItem(forms.ModelForm): class Meta: model = Model_Step01_CartItem fields = ["cart", "item_name", "item_quantity"] Formset_CartItem = forms.inlineformset_factory( Model_Step01_Cart, Model_Step01_CartItem, form = Form_Step01_CartItem, extra = 3 ) class Form_Step02(forms.ModelForm): class Meta: model = Model_Step02_Staffnote fields = ["note_staff"] β¦ -
Searchable drop down for choice field in django admin
I have a choice field with with lot's of data, I have created dropdown at admin panel but I want to have a searchable dropdown. class ItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PublicUserForm, self).__init__(*args, **kwargs) self.fields['city'] = forms.ChoiceField( choices = CHOOSE_CITY) class ItemAdmin(admin.ModelAdmin): form = ItemForm admin.site.register(Item, ItemAdmin) I have reffered django-autocomplete-light. Help me, please! Thanks in advance! -
Valid values of Speed and Pitch for Google Text-to-Speech API in Python
I'm trying to implement Google's Text-to-Speech api in python/Django, but I'm not able to set the correct values for Seed and Pict: According to my understanding of API's documentation, we have values for Speed between the range 0.25 -to- 4.0 AND Pitch between -20 -to- 20. But when I passed values between these ranges it returns an error, which says: <ul class="errorlist"><li>pitch<ul class="errorlist"><li>Select a valid choice. -1.0 is not one of the available choices.</li></ul></li><li>speed<ul class="errorlist"><li>Select a valid choice. 0.5 is not one of the available choices.</li></ul></li></ul> Here's my model code: from django.db import models from app.storage import OverwriteStorage genders = ( ('UNSPECIFIED', 'SSML_VOICE_GENDER_UNSPECIFIED'), ('MALE', 'MALE'), ('FEMALE', 'FEMALE'), ('NEUTRAL', 'NEUTRAL'), ) voice_types = ( ('nl-NL-Standard-A', 'nl-NL-Standard-A'), ('en-AU-Standard-A', 'en-AU-Standard-A'), ('en-AU-Standard-B', 'en-AU-Standard-B'), ('en-AU-Standard-C', 'en-AU-Standard-C'), ('en-AU-Standard-D', 'en-AU-Standard-D'), ('en-GB-Standard-A', 'en-GB-Standard-A'), ('en-GB-Standard-B', 'en-GB-Standard-B'), ('en-GB-Standard-C', 'en-GB-Standard-C'), ('en-GB-Standard-D', 'en-GB-Standard-D'), ('en-US-Wavenet-A', 'en-US-Wavenet-A'), ('en-US-Wavenet-B', 'en-US-Wavenet-B'), ('en-US-Wavenet-C', 'en-US-Wavenet-C'), ('en-US-Wavenet-D', 'en-US-Wavenet-D'), ('en-US-Wavenet-E', 'en-US-Wavenet-E'), ('en-US-Wavenet-F', 'en-US-Wavenet-F'), ('en-US-Standard-B', 'en-US-Standard-B'), ('en-US-Standard-C', 'en-US-Standard-C'), ('en-US-Standard-D', 'en-US-Standard-D'), ('en-US-Standard-E', 'en-US-Standard-E'), ('fr-FR-Standard-C', 'fr-FR-Standard-C'), ('fr-FR-Standard-D', 'fr-FR-Standard-D'), ('fr-CA-Standard-A', 'fr-CA-Standard-A'), ('fr-CA-Standard-B', 'fr-CA-Standard-B'), ('fr-CA-Standard-C', 'fr-CA-Standard-C'), ('fr-CA-Standard-D', 'fr-CA-Standard-D'), ('de-DE-Standard-A', 'de-DE-Standard-A'), ('de-DE-Standard-B', 'de-DE-Standard-B'), ('it-IT-Standard-A', 'it-IT-Standard-A'), ('ja-JP-Standard-A', 'ja-JP-Standard-A'), ('ko-KR-Standard-A', 'ko-KR-Standard-A'), ('pt-BR-Standard-A', 'pt-BR-Standard-A'), ('es-ES-Standard-A', 'es-ES-Standard-A'), ('sv-SE-Standard-A', 'sv-SE-Standard-A'), ('tr-TR-Standard-A', 'tr-TR-Standard-A'), ) speed = ( ('0.25', '0.25'), ('0.50', '0.50'), ('0.75', '0.75'), ('1', '1'), ('1.25', '1.25'), ('1.50', '1.50'), ('1.75', '1.55'), ('2', β¦ -
Convert Django ORM query with large IN clause to table value constructor
I have a bit of Django code that builds a relatively complicated query in a programmatic fashion, with various filters getting applied to an initial dataset through a series of filter and exclude calls: for filter in filters: if filter['name'] == 'revenue': accounts = accounts.filter(account_revenue__in: filter['values']) if filter['name'] == 'some_other_type': if filter['type'] == 'inclusion': accounts = accounts.filter(account__some_relation__in: filter['values']) if filter['type'] == 'exclusion': accounts = accounts.exclude(account__some_relation__in: filter['values']) ...etc return accounts For most of these conditions, the possible values of the filters are relatively small and contained, so the IN clauses that Django's ORM generates are performant enough. However there are a few cases where the IN clauses can be much larger (10K - 100K items). In plain postgres I can make this query much more optimal by using a table value constructor, e.g.: SELECT domain FROM accounts INNER JOIN ( VALUES ('somedomain.com'), ('anotherdomain.com'), ...etc 10K more times ) VALS(v) ON accounts.domain=v With a 30K+ IN clause in the original query it can take 60+ seconds to run, while the table value version of the query takes 1 second, a huge difference. But I cannot figure out how to get Django ORM to build the query like I want, and because of β¦ -
Serialization of child models
I have models: class CommonEditor(models.Model): def __str__(self): return 'Common Atributes Mask' class Color(models.Model): name = models.CharField(max_length=25) editor = models.ForeignKey(CommonEditor, on_delete=models.PROTECT, null=True) So I make serialization this way: class ColorSerializer(serializers.ModelSerializer): class Meta: model = Color fields = '__all__' class CommonAttributesSerializer(serializers.ModelSerializer): color = ColorSerializer(many=True, read_only=True) class Meta: model = CommonEditor fields = ('pk', 'color') And then view: class CommonAttributeAPIView(generics.ListCreateAPIView): serializer_class = CommonAttributesSerializer queryset = CommonEditor.objects.all() I get only pk of my CommonEditor Model. Why can't i get the full Atributes Mask and how can I fix it? Big thanks! -
Django sending files to an external java server
How can I send files stored in Django to an external server? I can use a python binded package for that server but the server is up and running so I want to use it. Would that be with TCP sockets? If they are, how can they process rather large files? Thanks -
Django: Use both session and jwt middlewares at a time
I have both JWT and session authentication middleware being used. What i found was that i was not able to login to admin. Later when i removed JWT middleware it worked. My site will is serving as both api login and normal browser login. How to use it for both. The only option left is the below condition for jwt. if request.content_type == 'application/json': How to resolve this -
Uploading files to Django using an input tag instead of form
I am trying to upload files to Django using an input tag, not with form. The Djang side is all checked with form (common coding for file uploading, so not included here) so it works fine but I am not sure how I can pass files to Django using ajax? In Html, <input type="file" id="files" data-url="{% url 'upload' %}" multiple data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' > In JQuery, $('#files').change(function(){ $form = $(this) var formData = new FormData(this); $.ajax({ url: window.location.pathname, type: 'POST', data: formData, success: function (response) { alert(response.filename) }, contentType: false, processData: false }); }); -
Phaser 2 not loading images to game with Django
I have been at this problem for days and cant seem to figure it out, I am using Django with Phaser2 framework and Im trying to load some images to the game, but keep getting a 404. Is there some extra settings I have to configure in Django? This is my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Phaser - Making your first game, part 1</title> <script src="//cdn.jsdelivr.net/phaser/2.2.2/phaser.min.js"></script> <style type="text/css"> body { margin: 0; } </style> </head> <body> <script type="text/javascript"> var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {preload: preload, create: create, update: update}); function preload() { {#game.load.path = '/';#} game.load.image('sky', 'assets/sky.png'); game.load.image('ground', 'assets/platform.png'); game.load.image('star', 'assets/star.png'); game.load.spritesheet('dude', 'assets/dude.png', 32, 48); } function create() { game.add.sprite(0, 0, 'star'); game.add.image(400, 300, 'sky'); } function update() { } </script> </body> </html> This is my folder structure: This are the errors I get: Any idea has to what might be causing the problem? -
Django form doesn't validate
I'm trying to upload a file to an Amazon S3 bucket using Django. I've created an html form and am passing the POST data to a function based view. I've looked around and tried numerous things but I can't seem to get it to validate. (In case it's relevant: I've already configured the S3 setup in settings and it seems to work just fine for handling static files) Errors when printing to console: ValueError: The Document could not be created because the data didn't validate. <ul class="errorlist"><li>upload<ul class="errorlist"><li>This field is required</li></ul></li></ul> Model from django.db import models from django.conf import settings from django.contrib.auth.models import User from messaging_platform.storage_backends import PrivateMediaStorage class Document(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField() class PrivateDocument(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField(storage=PrivateMediaStorage()) user = models.ForeignKey(User, related_name='documents', on_delete=models.CASCADE) ModelForm from django import forms from apps.core.models.document import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('upload',) View def edit(request, message_id=None): user_obj = get_login_user_objects(request) if request.method == 'POST': # tried all of these three variants form = DocumentForm(request.FILES['content_url_0']) form = DocumentForm(request.FILES) form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() Template {% for img_upload in img_upload_list %} <input type="file" accept="image/*" class="form-control border-input input-child" placeholder="https://example.com/original.jpg" name="content_url_{{ forloop.counter }}" value="{{ img_upload.payload }}" required> β¦ -
django didn't create unique connection when using multiprocessing
Environment: python3 django 1.10.3 MySQL 5.7.22 DB engine:PyMySQL(0.8.1) I would like to create unique connection object in each process Following this stackoverflow didn't works Here's my toy example and they all output the same object id, any idea would be appreciated. from django.db import connection, connections import multiprocessing as mp import os connections.close_all() connection.close() for c in connections.all(): c.close() def process_job(): for name, info in connections.databases.items(): # Close the DB connections connection.close() connection.close() connections.close_all() process_id = os.getpid() print(process_id, connection, id(connection)) processes = [mp.Process(target=process_job) for i in range(5)] for process in processes: process.start() for process in processes: process.join() print(connection, id(connection)) output: 9363 <django.db.DefaultConnectionProxy object at 0x7fda3286c208> 140575127290376 9364 <django.db.DefaultConnectionProxy object at 0x7fda3286c208> 140575127290376 9365 <django.db.DefaultConnectionProxy object at 0x7fda3286c208> 140575127290376 9366 <django.db.DefaultConnectionProxy object at 0x7fda3286c208> 140575127290376 -
Create a model filed which corresponds to a queryset
I am using Python Django. I want to have a dynamic homepage. To be exact, I want to show different lists of books. For example one list might be best sellers and the other might be old books. These lists could be added in the future and I need them to be dynamic. Each list has a title and a queryset corresponding to books within that list. What is the best practice to handle this? What should be the properties of my List model? -
Django Rest Framework unable to parse multipart/form data
As stated in DRF documentation http://www.django-rest-framework.org/api-guide/parsers/#multipartparser, in order to parse multipart/form-data, the MultiPart and form parser must be used. I have a supiscion this is a problem in the Django Rest Framework because I saw a solution on their github issue saying it work using APIView. from django.contrib.auth.models import User from rest_framework import viewsets from api.serializers import UserSerializer, from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() parser_classes = (MultiPartParser, FormParser) serializer_class = UserSerializer Picture of me sending request to Postman with result -
local variable 'instance' referenced before assignment error
Now I've read all the posts on SO regarding this error, and I can conclude that my error is quite a different case. The error: Local variable 'instance' referenced before assignment [21/Jun/2018 09:05:58] "POST /details/create/ HTTP/1.1" 400 54 Now here's the code where I initialize instance: def create(request): if request.method == "POST": try: params = post_data(request) try: instance = Sales_detail.objects.get(id = params.get("id",None)) params["item"] = instance.item.pk params["price"] = instance.price.pk params["sales"] = instance.sales.pk detail_form = Detail_form(params, instance = instance) except Sales_detail.DoesNotExist: params["item"] = instance.item.pk params["price"] = instance.price.pk params["sales"] = instance.sales.pk detail_form = Detail_form(params) if detail_form.is_valid(): detail_form.save() else: raise_error(detail_form.errors,True) return success("Details successfully saved.") except Exception as e: return error(e) else: return redirect("dashboard") I have no idea what I'm missing, clearly instance is initialized before doing anything with it. -
django filefield renaming issue
I am using the following code to rename the filename path for a FileField in my model uploaded via a form: class Document(models.Model): document_date = models.DateField(null=True) document_category = models.CharField(null=False,max_length=255, choices=DOCUMENT_CATEGORY_CHOICES) document = models.FileField(upload_to='documents/',max_length=100) def save(self, *args, **kwargs): ext = os.path.splitext(self.document.name)[1] date = str(self.document_date).replace('-','') category = self.document_category self.document.name = '%s_%s%s' % (date, category, ext) super().save(*args, **kwargs) This is working fine for new records created, however when I update these records using a form the record is saved with new updated details (date and/or category) and my database reflects the new filename path, however the filename of the actual file in the folder is not updated. Is anyone able to shed some light as to where I am going wrong and how I might be able to go about fixing this? Any help is much appreciated! -
Django: make a view run only once at a time (mutex/lock/semaphore)
Is there an easy way (ideally built-in or library) to allow at most 1 thread/process at time within a Django view? A kind of semaphore I guess. Ideally, I can make other threads return a response if the process is already running./ It doesn't need to handle any distributed system so locally managed is fine for my use case. Using Django 1.11 -
django collect static is not working
I wanted to upgrade to latest Django version since i was using V = 1.11, I have setup my STATIC_ROOT variable to point to my static Directory ran python manage.py collectstatic command, it collected admin page static files, but i cant get my page to use the css or images files My directory tree: . βββ inventario β βββ templates β βββ inventario βββ main βββ static βββ admin βββ css βββ img βββ js My settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') My template {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/custom.css' %}"> My admin page displays without any issues, but I can't get my CSS to be linked -
Django rest Type error
i am trying the django rest framework api and i get an issue when i try to post some to data to my django I have create my api Views with the helps of the generics views from the rest framework , and i have a basics models This is the error i get : `TypeError at /api/meals/ Got a `TypeError` when calling `Meal.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Meal.objects.create()`. You may need to make the field read-only, or override the MealSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/Users/mickael/Desktop/Dev/foody-api/lib/python3.6/site- packages/rest_framework/serializers.py", line 940, in create instance = ModelClass.objects.create(**validated_data) File "/Users/mickael/Desktop/Dev/foody-api/lib/python3.6/site- packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/mickael/Desktop/Dev/foody-api/lib/python3.6/site- packages/django/db/models/query.py", line 415, in create obj = self.model(**kwargs) File "/Users/mickael/Desktop/Dev/foody-api/lib/python3.6/site- packages/django/db/models/base.py", line 495, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'user' is an invalid keyword argument for this function` this is my models.py : def upload_status_image(instance, filename): return "status/{restaurant}/{filename}" .format(restaurant=instance.restaurant.user, filename=filename) class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') name = models.CharField(max_length=500) phone = models.CharField(max_length=500) address = models.CharField(max_length=500) logo = β¦ -
Django-Bleach or Just Bleach?
I've recently tried to implement Django-Bleach into my project, but I'm having an issue with an import library. I am currently running Python 3.6.2 and Django 1.11. When I try to define a django_bleach form in my forms.py, with the following statement: from django_bleach.forms import BleachField I am receiving the following error: ModuleNotFoundError: No module named 'django.utils.importlib' I spent the better part of this afternoon researching this error and I have come to understand that the django.utils.importlib statement was deprecated in 1.9. However, I can't seem to determine a workaround for this problem. I did try the suggestion outlined in this issue but it didn't seem to make a difference. I still receive the error. Cannot import importlib I'm also wondering if I should be using bleach instead of django-bleach as django-bleach doesn't seem to be updated since 2014. Thanks in advance for your suggestions and help. -
WARNING: Django_mysql.w001
I am developing an E-commerce website using python 3.6, I made a fresh installation of Django 2.0.6 and connected it to Mysql database (on the localhost) by defining the Database variables in settings.py as below: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'moda', 'OPTIONS' : { 'init_command' : "SET sql_mode='STRICT_TRANS_TABLES'", 'init_command' : 'SET innodb_strict_mode=1', 'charset' : 'utf8mb4', }, 'USER' : 'root', 'PASSWORD' : '', 'SERVER' : 'localhost', 'PORT' : '3306' } } and after running the - \ python manage.py check - command using cmd, I am getting the following warning: (django_mysql.W001) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://django-mysql.readthedocs.io/en/latest/checks.html#django-mysql-w001-strict-mode even I used - ' init_command': "SET sql_mode='STRICT_TRANS_TABLES'", and still getting the warning! I would be so grateful if some expert show me the right way to fix this! Thanks Guys. -
Transform POST Data Before Persisting
I am writing an API with TastyPie that a Django application will hit. One of the POST endpoints must validate data before inserting into the db. The process includes checking a record in another table with a value in the POST data. How do I apply business logic before inserting the POST data?