Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Querysets on views or on Model Managers DJANGO
thanks for your time. Some days ago a guy explained me that on ruby on rails the querys are done on models. because it gets already saved at your data before be requested on views and the query. by the way i've learned and had been working until now, i'm setting the query on views.py and passing, through a context variable. So i started to read about Model.Manager and still didn't find a answer to wich way is better: 1-querys made on views 2-querys made by simple functions on models 3-querys made on models.Manager class for each model -
Django backend Vue.js frontend fetch data with axios doesnt work
Im trying to build a simple todo app with a django rest framework as backend and a Vue.js frontend. Now i'm trying to fetch my backend data with axios but it doesnt work.Both application are on my localhost. The Django backend listens on port 8000 and the Vue.js app listens on port 8080 this is my code: Django: from django.shortcuts import render from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Task from .serializers import TaskSerializer @api_view(['GET']) def taskList(request): task = Task.objects.all() serializer = TaskSerializer(task, many=True) return Response(serializer.data) serializer.py from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' settings.py INSTALLED_APPS = [ .... 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ........ 'django.middleware.common.CommonMiddleware', CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", ] Vue.js: ....... <script> ..... created() { axios .get("http://localhost:8000/task-list") .then(res => res.json) .then(data => console.log(data)) .catch(err => console.log(err)); } .... <script> i did a lot of research and watched some youtube tutorials. I installed django-core-headers and put it in my installed apps and added the middleware and added the corse origin whitelist for the Vue.js app. if i try it with postman or with fetch everything works fine. … -
How to add image styling to CKEditor in Django?
I have created a basic django blog. I am using the RichTextUploadingField() for the body using the CK Editor. However, the problem is that the images uploaded using CK Editor are rigid and do not adjust to the screen size like other images on my blog. Please help me out. -
Django: OperationalError: no such column: User_profile.user_id
I am a beginner working on my first "independent" project without tutorial guidance. I have been working on a two password confirmation form for my registration page, without utilizing the django.contrib.auth.forms UserCreationForm. I have my Profile model with one attribute of 'user' which is a OneToOneField with the django.contrib.auth.models User model. For some reason, after I fill out my registration form from the front end and check the profiles group, the OperationalError pops up. This is not the first time I have had a 'no such column.' Can someone help? Would be greatly appreciated. My User/form.py, from django import forms from django.contrib.auth.models import User class UserRegisterForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user My User/views.py, register view, which is my registration form. def register(request): form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commmit=False) user = form.save() raw_password = form.cleaned_data.get('password1') user = authenticate(request, password=raw_password) if user is not None: login(request, user) return … -
django admin table wants another row of showing total amount of each column
I'd like to show the query results particularly total amount of each column here on my django admin page, building a postgresql as its database. I don't want an application so I'm not writing any views or htmls - using only the default htmls for admin page. And also the results better be interactive with filtering actions. I'm very new to django and I apologize if I'm out of points. Thanks. -
How to change timer for every single post in django
For every item in items I want to have a timer. I made a timer using javascript and I can show the timer for every single item. But when I want to show all the items in home page the timer is shown just for the last item. Is there any way to show the timer for all the items? <div class="row m0 p0 justify-content-center"> {% for item in items %} <div class="col-12 col-xs-6 col-md-4 card-item p0"> <div class="img-container"> <img class="rounded img-fluid img-thumbnail" src="{{MEDIA_URL}}{{ item.image }}" /> <div class="sold-img-item"></div> {% if item.sold == 1 %} <div class="sold">Sold <div class="sold-price"><span>{{item.highest_bid_offer}} €</span></div> </div> {% endif%} </div> <h5 class="no-flow capital "><b>{{item.title}}</b></h5> <div class="no-flow"><strong>Seller :</strong> {{item.seller}}</div> <div class="no-flow"> <strong>Initial Price :</strong> <span>{{item.price}} €</span> </div> <input type="hidden" id="auction_status" name="auction_status" value="{{ item.auction_status }}"/> <input type="hidden" id="end-time-fix" name="end-time-fix" value="{{item.auction_end_time}}"/> <div class="timer-small" id="timer-small"> <div class="timer-small" id="days-small"></div> <div class="timer-small" id="hours-small"></div> <div class="timer-small" id="minutes-small"></div> <div class="timer-small" id="seconds-small"></div> </div> <a class="divLinkkk" href="{% url 'item_detail' item.id %}"></a> </div> {% endfor %} </div> -
ImportError: No module named rest_framework on running collectstatic
I found many questions with the same error, but none were addressing the actual cause of my problem so I am posting this. I am facing the issue in my (digital ocean) Linux production server. I have python 3.5.2 in virtualenv, and python2.7.12 in the machine. I have installed djangorestframework in virtualenv using command pip3 install djangorestframework But did not install it in the actual machine (on 2.7) On running collectstatic command inside virtualenv I am getting the following error. It seems to be looking for the package in python2.7 and not inside virtualenv. (venv) myname@server:/www/site$ sudo python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named rest_framework python3 in the venv is working and importing rest_framework fine: (venv) myname@server:/www/site$ python Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import rest_framework … -
how to check is_staff in post_save() signals
I am working on project ,In which user can register as Doctor or Patient.when user is register as Doctor is_staff is set true ,but when i try to access it in post_Save() method it always return false even though when i take a look on Django site Doctor user are indicated as staff member ,I am not getting how to handle if any one can help me. I also tried to kwargs['is_staff'] but it say there is no attribute like that in User model def update_profile_signal(sender, instance, created, **kwargs): print(kwargs['is_staff']) if created : print(instance.user_type) PateintProfile.objects.create(user=instance) instance.pateintprofile.save() post_save.connect(update_profile_signal,sender=UserProfileInfo) -
Auth-token Getting "DoesNotExist at /api/accounts/register Token matching query does not exist." response despite account registering successfully
I'm creating a Django back-end with token authentication. I am currently running into this issue when registering a user using postman. Despite the response I receive the user-account and token still gets created successfully Response: DoesNotExist at /api/accounts/register Token matching query does not exist. API registration View @api_view(['POST']) def registration_view(request): if request.method == 'POST': serializer = AccountRegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = "successfully registered a new user." token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) Traceback: Traceback: File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in dispatch 505. response = self.handle_exception(exc) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in handle_exception 465. self.raise_uncaught_exception(exc) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception 476. raise exc File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in dispatch 502. response = handler(request, *args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\decorators.py" in handler 50. return func(*args, **kwargs) File "C:\dev\Harryandsam\harryandsam\accounts\api\views.py" in registration_view 19. token = Token.objects.get(user=account).key File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\db\models\query.py" in get 408. self.model._meta.object_name -
Cannot locate a static file. I get an error that 'STATIC_ROOT' is not set
What I want to do I'm trying to deploy my Django app using AWS (EC2), nginx, and gunicorn. The current goal is to place the static files in the directory /usr/share/nginx/html/static. Problem that is occurring I created /usr/share/nginx/html/static and then ran python manage.py collectstatic command. I had set STATIC_ROOT in settings.py to STATIC_ROOT='/usr/share/nginx/html/static' before, so I thought I could use the collectstatic command to collect static files from within the Django project and place them in /usr/share/nginx/html/static. However, that wasn't the case. Instead I got an error saying django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Could you please explain why this is so? I have tried some suggested solutions over the internet but the problem still exists. I’d be really appreciated if you could reply to me. error message 'STATIC_ROOT' -
Django - Only some static images not showing up in deployment
So I have my static url set as such under settings: settings.py STATIC_URL = '/static/' if DEBUG or not DEBUG: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'tabular', 'templates'), os.path.join(BASE_DIR, 'common'), ) Then here is my folder path with the static files I have a webpage with logo.png and step1.png-step4.png. For some odd reason when I'm running in deployment, it correct fetches logo.png, but not step1.png-step4.png. Here is the html code. <div id="wrapper"> <div id="container"> <img style="padding: 1em;" src="{% static 'images/logo.png' %}" /> <form class="form-horizontal" enctype="multipart/form-data" id="data_upload" method="POST" > {% csrf_token %} <div class="input-group mb-3"> <div class="custom-file"> <input accept=".csv" class="custom-file-input" id="file_input" name="file" type="file" /> <label aria-describedby="inputGroupFileAddon02" class="custom-file-label" for="inputGroupFile02" id="submit_label" >Upload CSV</label > </div> <div class="input-group-append"> <button class="input-group-text btn" id="upload_button" type="submit" disabled > Upload </button> </div> </div> <div id="progress_div" class="progress" style="visibility: hidden;"> <div id="progress_bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100" ></div> </div> <br /> <div id="spinner" class="d-flex justify-content-center" style="visibility: hidden;" > <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading...</span> </div> </div> </form> </div> </div> <div class="modal fade" id="my_modal" tabindex="-1" role="dialog" data-target="#my_modal" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modal_title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div id="modal_body" class="modal-body"></div> </div> </div> </div> <div class="modal fade" id="how_to_modal" … -
from: can't read /var/mail/django.utils.version when running django-admin.py
I'm trying to install Django v3.0.6 (or any other v3.x.y) in my macOS. Following are the steps that I've done: installed python3 using homebrew, then ran sudo pip3 install virtualenv, navigating into my target project folder, ran virtualenv venv -p python3. After activating it, ran pip install Django==3.0.6. This resulted in a successful installation of Django 3.0.6. However, when I run django-admin.py startproject myproject I immediately get the following error: from: can't read /var/mail/django.utils.version /usr/local/bin/django-admin.py: line 3: syntax error near unexpected token `(' /usr/local/bin/django-admin.py: line 3: `VERSION = (3, 0, 6, 'final', 0)' Trying to to run this django-admin.py command using the virtualenv is actually my second attempt. I initially started trying with installing Django directly in my machine, not using virtualenv, which also resulted in the same error. My assumption is that happened because the default python version in my machine/OS is 2.7. Any help would be greatly appreciated! -
ModelForm ''Select' object has no attribute 'fields'
I'm using the Django form.selectmultiple field for EntityForm. I'm trying to add CSS classes to form.selectmultiple. This is the code that I wrote. forms.py class Select(forms.SelectMultiple): template_name = "entity/choices/choices.html" def __init__(self, *args, **kwargs): super(Select, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs["class"] = "no-autoinit" class Media: css = {"all": ("css/base.min.css", "css/choices.min.css",)} js = ("js/choices.min.js",) class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ["main_tag", "tags"] widgets = { "tags": Select(), } I have the following error: AttributeError: 'Select' object has no attribute 'fields' How can I fix the problem? Any help would be appreciated. -
Why isn't my html style only applying to the body even though I am using block content?
So I am attempting to add a style for the body of my page but unfortunately it is applying to my navbar too which is coming from my base.html. What am I doing wrong here that it's applying to my navbar too? I only want it to apply the contents in <body> messages.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% load static %} <!DOCTYPE html> <html> <head> </head> <meta name="viewport" content="width=device-width, initial-scale=1"> {% block content %} <style> body { margin: 0 auto; max-width: 800px; padding: 0 20px; } .container { border: 2px solid #dedede; background-color: #f1f1f1; border-radius: 5px; padding: 10px; margin: 10px 0; } .darker { border-color: #ccc; background-color: #ddd; } .container::after { content: ""; clear: both; display: table; } .container img { float: left; max-width: 60px; width: 100%; margin-right: 20px; border-radius: 50%; } .container img.right { float: right; margin-left: 20px; margin-right:0; } .time-right { float: right; color: #aaa; } .time-left { float: left; color: #999; } </style> <body> <a href="{% url 'dating_app:message' other_user.id %}">Start messaging!</a> <h2>Chat Messages</h2> {% for message in messages %} {% if message.sender_id == request.user.id %} <div class="container"> <img src="{{ profile.photo.url }}" alt="Avatar" style="width:100%;"> <p>{{ message.message }}</p> <span class="time-right">{{ message.date }}</span> </div> {% elif … -
Django User Model: Raised exception on delete
Unfortunately, the stack trace given does not give any detail as to the cause of this error or any useful information. When I try to delete a user, in admin or in a method, this exception is raised and I have no idea why. [2020-06-05 03:04:20] ERROR Internal Server Error: /v1/search/events/attending-and-following/ Traceback (most recent call last): File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/fendy/Desktop/Collegeapp-Django/search_indexes/views/event_details.py", line 47, in get user.delete() File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/db/models/base.py", line 937, in delete collector.collect([self], keep_parents=keep_parents) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 245, in collect field.remote_field.on_delete(self, field, sub_objs, self.using) TypeError: SET() takes 1 positional argument but 4 were given -
Fair task processing order with Celery+Rabbitmq
I have a Django applications serving multiple users. Each user can submit resource-intensive tasks (minutes to hours) to be executed. I want to execute the tasks based on a fair distribution of the resources. The backend uses Celery and RabbitMQ for task execution. I have looked extensively and haven't been able to find any solution for my particular case (or haven't been able to piece it together.) As far as I can tell, there isn't any build-in features able to do this in Celery and RabbitMQ. Is it possible to have custom code to handle the order of execution of the tasks? This would allow to calculate priorities based on user data and chose which task should be executed next. Related: How can Celery distribute users' tasks in a fair way?