Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I automatically delete images in Django media file when I delete the objects in Admin?
please help! I am using Django 3 and have a basic blog with a title, description and image for each entry. In Django admin I can delete each blog post however, when I look in my media file in Atom all the images are still there and I have to manually delete them... how do I get them to auto delete when I delete them in Admin? Model.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='images/', default='images/road.jpg') last_modified = models.DateField(auto_now=True) Views.py from django.shortcuts import render from .models import Blog def home (request): blogs = Blog.objects.all() return render (request,'blog/home.html', {'blogs':blogs}) -
Run Django manage.py shell commands on elastic beanstalk
I have my Django service up and running on AWS elasticbeanstalk. eb deploy works perfectly. But I would like to run some functions from shell of Django on by eb or maybe perform migrations on my DB. I am unable to find my package after I eb ssh so cant find the manage.py file. Related question - Run manage.py from AWS EB Linux instance I believe it might be outdated ? -
How to implement foreign key relationships with django-import-export
I've made a django app in which I want to import data from .xlsx files to models with django-import-export module. My models.py is: class File(models.Model): name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Data(models.Model): file = models.ForeignKey(File, on_delete=models.CASCADE, null=False) url = models.URLField() I want that when I import .xlsx file its contents go into Data model and its File name into File model with foreign key relationship between them. My admin.py file is: from import_export.admin import ImportExportModelAdmin from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from django.contrib import admin from .models import File, Data admin.site.register(File) class DataResource(resources.ModelResource): file = fields.Field( widget=ForeignKeyWidget(File, 'name')) class Meta: model = Data exclude = ('file',) @admin.register(Data) class DataAdmin(ImportExportModelAdmin): pass I tried everything in the module's documentation. But I can't solve the issue I'm facing -
Dealing with unique constraints in nested serializers
In my Django project, I made a custom Auth model with unique email and username, I made a different model where I defined the user field and connect it with ForignField, and also made serializer for this model, but whenever I adding 2nd object in the model it shows me validation error like { "error": { "user": { "username": [ "user with this username already exists." ], "email": [ "user with this email already exists." ] } } } I got one article on how to dealing with unique constraints in nested serializers link of that article but this article only shows me how to tackle username which is working fine but I also want to validate email Id. How can I write a custom validator in serializer which will deal with both fields? -
In Django class based views how I do I use multiple slugs with slug_url_kwarg
According to the documentation, The name of the URLConf keyword argument that contains the slug. By default, slug_url_kwarg is 'slug'. How do I use this for an UpdateView where I have two slugs book_slug and chapter_slug? According to this answer, I can override get_queryset method. But is there a way to use multiple slugs with slug_url_kwarg? I tried slug_url_kwarg = ['book_slug', 'chapter_slug'] but it doesn't work. -
Why are integration tests failing on updates to model objects when the function is run on Django q-cluster?
I am running some django integration tests of code that passes some functions to Django-Q for processing. This code essentially updates some fields on a model object. The app uses signals.py to listen for a post_save change of the status field of the Foo object. Assuming it's not a newly created object and it has the correct status, the Foo.prepare_foo() function is called. This is handled by services.py which hands it off to q-cluster. Assuming this executes without error hooks.py changes the status field of Foo to prepared, or keeps it at draft if it fails. If it passes then it also sets prepared to True. (I know this sounds convoluted and with overlapping variables - part of the desire to get tests running is to be able to refactor). The code runs correctly in all environments, but when I try to run tests to assert that the fields have been updated, they fail. (If I tweak the code to bypass the cluster and have the functions run in-memory then the tests pass.) Given this, I'm assuming the issue lies in how I've written the tests, but I cannot diagnose the issue. tests_prepare_foo.py import time from django.test import TestCase, override_settings, … -
Django reproduce concurrency example with select_for_update()
I'm reading over this article on handling concurrency in django The post talk about the following example: User A fetches the account — balance is 100$. User B fetches the account — balance is 100$. User B withdraws 30$ — balance is updated to 100$ — 30$ = 70$. User A deposits 50$ — balance is updated to 100$ + 50$ = 150$. I tried to reproduce with a UserBalance model with balance column that use IntegerField() def test_con(id): with transaction.atomic(): user_balance = UserBalance.objects.select_for_update().get(pk=int(id)) sleep(60) user_balance.balance -= 30 user_balance.save() So this transaction is lock for 60 seconds In the first shell i go into manage.py shell to call it In another shell after i execute test_con(5) i ran the following : >>> from backend.models import UserBalance >>> user_balance = UserBalance.objects.get(pk=5) >>> user_balance.balance += 50 >>> user_balance.save() >>> print(str(user_balance.balance)) the second shell wait till the first shell test_con(5) transaction is completed(as expected) and return the balance but it return 150 ? shouldn't it be 120 ? I'm confused about why this locking mechanic doesn't work -
How to retrieve post data from view of django app
Hi All I am new to jquery and django. I used the following code to post when the button with id 'submit_data' is clicked. Is it possible to retrieve the dictionary { data_key: 'myString'} from the views.py of django app? If yes how? $(function() { $('#submit_data').on('click',function() { $.post('/url/', { data_key: 'myString'}, function(result) { alert('successfully posted'); }); }); }); -
Django 3.0+ : django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
so i have been googling for a solution in the past 5 hours, maybe more? I did all the solutions that are listed like checking each installed_app and adding django_setup() then knowing that django_setup() should NOT be used. Ill edit what you need to see, because im not sure where exactly my error is. ive trued python manage.py runserver/check and thats what i get: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_li ne utility.execute() File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\saraa\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\contrib\auth\apps.py", line 8, in <module> from .checks import check_models_permissions, check_user_model File "C:\Users\saraa\PycharmProjects\okobackend\okobackend\lib\site-packages\django\contrib\auth\checks.py", line 8, in <module> from myapi.models import is_anonymous File "C:\Users\saraa\PycharmProjects\okobackend\myapi\models.py", line 3, … -
How to rename is_active in user table in django?
This is my user model: class User(AbstractUser): id = models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True ) email = models.EmailField(_("email address"), max_length=255, unique=True) avatar = models.CharField(_("avatar"), max_length=128, default="") username = None EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email Now, I need to rename is_active to active. I originally wanted to cancel is_active like username, and then create a new active field is_active = None active = models.BooleanField(_("active"), default=False) This does not seem to work, and I received an error message (admin.E116) The value of 'list_filter[2]' refers to 'is_active', which does not refer to a Field. -
Why request.body is empty on call custom API using tastypie?
Facing issue with POST API call. I am using tastypie prepend_urls wrap_view for login custom api. I am using below versions: Tastypie 0.14.3 Tastypie_swagger 0.1.4 Django 2.2.12 Python 3.5.2 I am using below deserialize method to abstract data from payload. I don't know why I'm getting empty request.body. request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json') ) If I'm trying to convert request data into json, Then it is raising Request is not valid JSON. As per my debugging it is using package method named deserialize and into serialize.py of tastypie. It is using from_json method. Also request.body returning blank query dict. I am receiving data which is passing into POST call with request.GET. Is it happening due to upgraded version of python and tastypie? Is there something am I doing wrong? Here is some output of my request. It would be helpful to understand the scenario. I am getting this params into GET instead of request.body. request.GET <QueryDict: {'username': ['abc@gmail.com'], 'password': ['123456']}> Empty POST QueryDict request.POST <QueryDict: {}> Request call: request <WSGIRequest: POST '/api/v1/user/login/?username=abc%40gmail.com&password=123456'> self.method_check(request, allowed=['post']) 'post' request.body b'' It should have JSON payload like {"username":"password"}. Please suggest me what should I do for resolved below error. { "status": "0", "message": "Request is … -
How do I create Groups for custom users in Django?
I created a Custom User Model by basically copying and pasting the full example given in the Django Docs. But in the docs, they unregistered groups. But in my project I will need groups because I'll have different uper types. So how can I still have groups and add my custom users to them? -
Set environment variables uwsgi
I'm working with a Django project and want to deploy it using nginx with uwsgi. I have to set these environment variables for my app to work (I'm using Gurobi if people are interested). export GUROBI_HOME="/opt/gurobi902/linux64" export PATH="${PATH}:${GUROBI_HOME}/bin" export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" My app works fine in my development environment, but when I try deploying it to my server, I get a Gurobi import error, which means these environment variables are not properly set up in my uwsgi environment. I've tried setting up these environment variables in 2 ways in my uwsgi configuration file, but none works. [uwsgi] ... env = GUROBI_HOME="/opt/gurobi902/linux64" env = PATH="${PATH}:${GUROBI_HOME}/bin" env = LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" The other way I tried was taken from this answer. [uwsgi] ... route-run = addvar:GUROBI_HOME="/opt/gurobi902/linux64" route-run = addvar:PATH="${PATH}:${GUROBI_HOME}/bin" route-run = addvar:LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${GUROBI_HOME}/lib" Does anyone know how to properly pass environment variables to uwsgi? Thanks all. -
How to Count distinct rows over two ManyToMany Fields
from django.db import models class Group(models.Model): users = models.ManyToMany(User, blank=True, related_name="groups" class Task(models.Model): users = models.ManyToManyField(User, blank=True, related_name="personal_tasks") groups = models.ManyToManyField(Group, blank=True, related_name="group_tasks") Note: Code above is to demonstrate the concept, it is not code that is being used. So using the models above as an example, would it be possible (with a single query preferably) to get a total count of unique users? I initially thought of just adding the counts of the users field and the groups__users field, however, I would like to account for the possibility that someone was both assigned the task personally, and through their group. -
Why Django does not generate app name into href paths?
I hope someone could maybe help me, please : I am quite new to Django and currently trying to implement a simple login/logout for a test page. However, for some reasons, the Django does not generate the name of application in the href (so where it should be xxxx/main/register, it is only xxx/register). But when I put the app name manually in the href in Pycharm, it generates it two times (so it becomes xxx/main/main/register). So for this: <a href="/logout/">Logout</a> I got this url: http://127.0.0.1:8000/logout/ If I write this: <a href="main/logout/">Logout</a> I got this url: http://127.0.0.1:8000/main/main/logout/ But I need to get this: http://127.0.0.1:8000/main/logout/ It worked before, but from one minute to another, it suddenly stopped directing to the good path. And django does the same thing with every links in my site. main/urls.py: from django.urls import path from . import views app_name = 'main' # here for namespacing of urls. urlpatterns = [ path("", views.homepage, name="homepage"), path("register/", views.register, name="register" ), path("logout/", views.logout_request, name="logout"), ] main/views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tutorial from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import logout, authenticate, login from django.contrib import messages def homepage(request): return render(request = request, template_name='main/home.html', … -
How to get and show many images in the Django application from Flask programs that live on other servers through a GET request for them
I have the Django application (D) as a dashboard site on some instance of AWS and several Flask working applications (F) on others. I need to show many images (such as .png scenes) in the D web interface. To do this, I need to get files from F, where they are stored using a GET query with a path file to the current instance. The model cannot be used via AWS S3 to perform this specific task. I'm thinking about the built-in Python socket, but I don't see a solution ... Maybe someone has faced the same problem and can say a solution, which way can I use? Thanks. -
Django urls behaviour with coplex path
In my django project, in urls.py file i have a link like thisone: ... url(r'^poliamb/(?P<m_path>\w+)/$', pol_data), ... ok all work done when i have an url like: http://127.0.0.1:8000/poliamb/test1 but i got error when i have for example http://127.0.0.1:8000/poliamb/test1-other if there is the - sign in the url path django get url not defined error Someone can hel me to manage also urls with - sign? so many thanks in advance -
Detect all types of compress files in Django and best practice
I want to restrict uploaded files to compress files. I wrote a restricted file field for this, but the problem I have is that some people can't upload their compressed files. I added all kinds of compress file applications to my validator, but the problem was not solved. This is my codes: # models.py class Answer(models.Model): answer_file = BaseFChecker.ContentTypeRestrictedFileField(null=True, blank=True, upload_to='answer-file/', content_types=['application/zip', 'application/x-zip-compressed', 'application/x-rar-compressed', 'application/pdf','application/vnd.rar' ], max_upload_size=BaseGlobs.SIZE_20MB, ) # validators.py from django.db.models import FileField, class ContentTypeRestrictedFileField(FileField): def __init__(self, *args, **kwargs): self.content_types = kwargs.pop("content_types", []) self.max_upload_size = kwargs.pop("max_upload_size", []) super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs) try: file = data.file try: if file.content_type in self.content_types: if int(file.size) > int(self.max_upload_size): error_text = "Maximun size is {}".format(filesizeformat(self.max_upload_size)) raise forms.ValidationError(error_text) else: error_text = 'Format of uploading file is not correct.' raise forms.ValidationError(error_text) except AttributeError: pass except FileNotFoundError: error_text = 'Check existing of uploading file!' raise forms.ValidationError(error_text) return data What is wrong with my codes? How can I create restricted method for uploaded file that support all types of compress files? # Related side question I was looking for a solution and came to the conclusion that there are three possible solutions to this problem. To find out type of … -
Django admin_order_field on custom field that is formatted/decrypted
I have a database with some field that are encrypted. In the admin page i created a custom function to decrypt that text(full_name column) and show on the listing page: #admin.py list_display = ('get_full_name',) def get_full_name(self, obj): if obj.full_name is not None: return decrypt_string(obj.full_name) else: return None get_full_name.short_description = 'User full name' get_full_name.admin_order_field = 'full_name' I though it would ordering over the decrypted text but instead it order by the actual encrypted values instead. How can i have an order by decrypted value on the admin listing page ? -
Django taggit issue in mobile browser
I have used Django-taggit in my website and they are working all awesome in website. But a weird thing has been noticed that when I open that website in my mobile and put tags [first add tag, then remove it and then put again] it gets save in backend like: , star, green Due to which I get this error while displaying that product: Yes I understand this error is coming case of first empty ',' . But question is why is it happening? I have tested from website in all resolution/even in mobile view and everything is expecting fine. But from mobile browser this issue is coming. Any insights how can I catter this situation? -
Bast way to implement DRF with JSON Api where no model is involved?
I've been at this for a while now. Any guidance is appreciated. I have to implement a django rest_framework with JSON API output with pagination. Seems simple enough. I've done it many times before. But this time I don't have an underlying model wo work from. My data comes from a third-party SDK which just returns a list of dictionaries. It's complex data with nested lists and such, but in the end it's just a list of dicts. I got to the point where I'm able to display my data and even paginate it (sort of). But there are no "links" nor are there any "next", "prev", or "count" fields in my output. I'm posting my snippets here changing the name to not expose the 3rd party provider. Here is the serializer I have so far: from rest_framework import serializers class MySerializer(serializers.Serializer): def to_representation(self, instance): return instance This is my view: class MyViewSet(ViewSet): serializer_class = serializers.MySerializer queryset = sdk.get_all_the_things() def list(self, request): page = self.paginate_queryset(self.queryset) return Response(page) sdk.get_all_the_things() returns a list of dicts, similar to: [{ "foo": "something", "bar": "more stuff", ... }, { ... }, and so on.... ] I have no control over this input directly and the … -
Docker compose up works very slow
I have a web app with Django (and angular as compiled app) and I'm trying to run it using docker containers. Here is my docker-compose.yml file: version: '3' services: web: build: ./ command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn decoderservice.wsgi:application --bind 0.0.0.0:8000" ports: - "8000:8000" env_file: - ./.env.dev Dockerfile: FROM python:3.7 WORKDIR /orionprotocolservice/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt ./requirements.txt RUN pip install -r requirements.txt COPY . /orionprotocolservice/ Program works, but performance is extremely slow (about 17s for loading the main page). Routing between pages are also slow. Interestingly, if I click to some button twice, it immediately loads. What is happening, who could help? -
Missing heart rate data in Garmin .fit file
I am working with Garmin Fitfile. When I am parsing a fitfile which contains only power data I am getting data record of every second. But when the file contains only heart rate data most of the timestamp records are not found. I am using this library https://github.com/dtcooper/python-fitparse. My sample code is given below: parsed_file = FitFile("test.fit") records = parsed_file.get_messages('record') total_record = 0 for record in records: total_time += 1 print(total_record) When I am running this code the output is: 1050, which means I am getting records of 1050 seconds. But the file should contain more than 4200 seconds data which I can check by running this code: parsed_file = FitFile("test.fit") activity_record = parsed_file.get_messages('activity') total_time = activity_record.get_values()['total_timer_time'] Here in 'total_timer_time' Garmin saves the total time a user spent while completing the activity. When I check the fit file in my Garmin website account I can see all 4200 seconds data. Is there anything I am missing to retrieve the heart rate data? -
Edit behavior of a table in Django 2.2 admin
I am currently implementing an application in which the model has the following tables defined: # Modelo cactaceas class Taxonomia(models.Model): id_cactacea = models.AutoField(primary_key=True) subfamilia = models.CharField(max_length=200) genero = models.CharField(max_length=200) especie = models.CharField(max_length=200) subespecie = models.CharField(max_length=200, null=True, blank=True) autor = models.CharField(max_length=200) descripcion = models.TextField(null=True, blank=True) ESTADO_CONSERVACION = [ ('NE', 'no evaluada'), ('DD', 'informacion insuficiente'), ('LC', 'menor preocupacion'), ('NT', 'casi amenazado'), ('VU', 'vulnerable'), ('EN', 'en peligro de extension'), ('CR', 'en peligro critico'), ('EW', 'extinto en la naturaleza'), ('EX', 'extinto'), ] estado_conservacion = models.CharField(max_length=2, choices=ESTADO_CONSERVACION, default='NE') distribuciones = models.ManyToManyField(Distribucion) fenologias = models.ManyToManyField(Fenologia) imagenes = models.ForeignKey(Imagen, on_delete=models.CASCADE, default=1) class Meta: ordering = ["-subfamilia"] def get_absolute_url(self): from django.urls import reverse return reverse("detail-cactacea", args=[int(self.id_cactacea)]) def __str__(self): subespecie = "" if self.subespecie != None: subespecie = self.subespecie cactacea = self.subfamilia + " " + self.genero + " " + self.especie + " " + subespecie + " " + self.autor return cactacea # Modelo distribucion class Distribucion(models.Model): id_distribucion = models.AutoField(primary_key=True) localidad = models.TextField(null=True, blank=True) def __str__(self): return self.localidad I am using the "admin.ModelAdmin" subclass for rendering the models in the django admin area getting the following rendering for each record in the "taxonomia" table As you can see in the image above this shows a box with … -
How to create virtual environment in pythonware?
8:59 ~ $ mkvirtualenv --python=3.7 myproj The path 3.7 (from --python=3.7) does not exist also tried with 3.5 and the path of python.exe its not working Thank you in advance