Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve "IndexError at / list index out of range" when there is an empty list
I was wondering what the simplest way is to return null in Django when there is an empty list coming from an API "leverage_buy": [],: my views.py from django.shortcuts import render from meal_app.models import Kraken import requests def get_krakens(request): all_krakens = {} url ='https://api.kraken.com/0/public/AssetPairs' response = requests.get(url) data = response.json() for i in data['result'].values(): kraken_data = Kraken( altname = i['altname'], leverage_buy = i['leverage_buy'][0], ) kraken_data.save() my models.py from django.db import models class Kraken(models.Model): altname = models.CharField(max_length=50, blank = True, null = True) leverage_buy = models.IntegerField(blank=True, null=True) Postman response { "error": [], "result": { "1INCHEUR": { "altname": "1INCHEUR", "leverage_buy": [], I researched and tried thoroughly many similar cases here, but none had the example of an API empty list. -
Django querySet order by date closest to today
I have a simple view that returns event dates and then is presented within a table on my page. I need to order the data by the date closest to the current date only for dates in the future, not for dates that have passed. This is my view def dashboard_view(request): now = datetime.datetime.now().date game_list=Game.objects.all() event_list = Event.objects.all().order_by('event_date') return render(request,"dashboard.html",{"game_list":game_list, "event_list": event_list}) I was thinking of using datetime.datetime.now() but I can't figure out the logic/syntax to do this. Thanks -
Search filter using Vuejs and Django
I am doing my website search-filter part using Django rest-framework and VueJs. I used django-filter. My problem is that I don't know how to set url or change on Vue when data is changed for example if I input max-price, url be like that http:/.../api/v1/search/?max_price=150 and when I check is-online status to true url should be changed to http:/.../api/v1/search/?max_price=150&is_online=true. Is there any approach for this? Thanks in advance filters.py from django_filters import rest_framework as filters from .models import Announcement class AnnouncementFilter(filters.FilterSet): min_price = filters.NumberFilter(field_name="price", lookup_expr="gte") max_price = filters.NumberFilter(field_name="price", lookup_expr="lte") class Meta: model = Announcement fields = ['subcategory', "is_online", "owner"] views.py from django_filters import rest_framework as filters from .filters import AnnouncementFilter class AnnouncementFilterList(generics.ListAPIView): queryset = Announcement.objects.all() serializer_class = AnnouncementSerializer filter_backends = [filters.DjangoFilterBackend] filterset_class = AnnouncementFilter Search.vue export default { name: "Search", data() { return { announcements: [], is_online: false, min_price: "", max_price: "", ... } }, methods: { async search() { await axios .get(`api/v1/announcements/search/?max_price=${this.max_price}`) .then(response => { this.announcements = response.data console.log(response.data) }) .catch(error => { console.log(error) }) } That's what I did so far.. -
How send value from django html to django views
I want to make a section with goods in which you can "+" and "-" increase or decrease the quantity of goods And then, depending on the amount, "sell" it. Now we need to pass the value {{ el.id }} to django views My code: html: <form method="POST"> {% csrf_token %} {% for el in form3 %} {% if el.count > 0 %} [ {{ el.count }}шт. ] <br> [ {{ el.title }} ]<br> <a id="minus{{ el.id }}" href="#"><b>[ - ]</b></a> <span id="value{{ el.id }}">0</span> <a id="plus{{ el.id }}" href="#"><b>[ + ]</b></a> <br> Function where i + or - from count <script> $(function(){ var valueElement = $('#value{{ el.id }}'); function incrementValue(e){ valueElement.text(Math.max(parseInt(valueElement.text()) + e.data.increment, 0)); return false; } $('#plus{{ el.id }}').bind('click', {increment: 1}, incrementValue); $('#minus{{ el.id }}').bind('click', {increment: -1}, incrementValue); }); </script> {% endif %} {% endfor %} </form> how can i get the values with "span id=value{{ el.id }}" -
How to return a separate, related value from a Django form?
I am working on a simple appointment scheduling system where customers can bring their vehicle in for service. Customers can have multiple vehicles and have a login with all of their vehicle information saved. Most of the customers track their vehicle by a 'unit' number. When they fill out the form, they select the branch (service center) where they want the work performed, the date, the timeslot, and they select their vehicle based on the unit number. On the backend, the unit and VIN are tied together. However, currently when they submit a service request, only their unit number comes through. I need the associated VIN to come through automatically. I have tried to return separate values from the vehicle model (I can't figure that out), I've tried to return them with f' but that returns it as one string with the unit and VIN together. I've spent probably 3-4 hours trying to get this figured out. Any help is appreciated!! Models.py class Vehicle(models.Model): unit = models.CharField(max_length=10, help_text="Unit number for the vehicle") vin = models.CharField(max_length=17, unique=True, validators=[MinLengthValidator(17)], help_text="VIN of the vehicle") engine = models.ForeignKey(Engine, on_delete=models.SET_NULL, null=True) engineMfg = models.ForeignKey(engineMfg, on_delete=models.SET_NULL, null=True) sold_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) mileage = models.IntegerField(default=0, … -
How to change the name of a field generated with a function in list_display in admin.py
i have a modelAdmin in admin.py. i want to display a value which i generated from a function in the model. here is the code: admin.register(Salary) class Salary(admin.ModelAdmin): list_display=('Category','BasicPA','BasicBM','Grade','Step','total') def BasicBM(self,instance): return instance.get_BasicBM() def total(self,instance): return instance.total() fieldsets =( ('Grade Salary Information',{ 'fields':('Category','BasicPA','RentP','TransportP','MealG','UtilityP','WeighInP','CSAP','TSAP','CallG','HazardG','RuralAllG','ShiftG','DomesticLawG','StateCounselG','Grade','Step') }), ) This works but it shows 'BasicBM' on the list_display title and i want to change it to 'Basic B/M'. i can't change it because i think the name of the string in list_display list has to match the name of the function in the class Salary in admin.py for this to work and the name of a function can't contain '/' or spaces. please, how do i achieve this? Thanks in Advance! -
display background color based on the conditions in the Django template
Let us consider the color codes red - #FFDADA amber - #FFC200 green - #90EE90 gold - #FFFF00 here is my index.html <td style="background-color:{% if qualification.is_past_due %}#FFDADA{% elif qualification.is_past_month %}#FFC200{% elif not qualification.validated %} #FFFF00 {% else %}#90EE90{% endif %};" Here if qualification is is_past_due = red if qualification is is_past_month (near to expire 30 days) = amber if qualification date is in future and qualification.validate = Green if qualification.expiry date is in future and not qualification.validate = Gold if no expiry_date the white let us consider my models.py class Qualification(models.Model): expiry_date = models.DateField(null=True,verbose_name="Expiry Date", blank=True) validated = models.BooleanField(default=False) def is_past_due(self): try: date1 = datetime.combine(self.expiry_date, datetime.min.time()) date2 = pytz.utc.localize(date1) return date2 and timezone.now().date() > localtime(date2, timezone=self.user.get_user_timezone()).date() except: return '' def is_past_month(self): try: expiry_date = self.expiry_date+relativedelta(months=-1) date1 = datetime.combine(expiry_date, datetime.min.time()) date2 = pytz.utc.localize(date1) return date2 and timezone.now().date() > localtime(date2, timezone=self.user.get_user_timezone()).date() except: return '' def today_date(self): try: today = timezone.now().date() return today except: return '' class Meta: ordering = ['expiry_date'] Let us consider my database records as id expiry_date validated 1 08-11-2019 1 (# alredy expired so red) 2 24-11-2021 0 (# near to expiry so amber ) 3 22-12-2021 1 (# future date and validated(1) so green ) 4 28-12-2021 0 … -
Why does my Django object being deleted with no reason?
Okay, so I know this question may not be in appropriate shape, but I have no other way to describe it. I have a Django project, deployed with Heroku. I'm using Postgres add-on. The problem is, few of the objects that my users created is being deleted for some reason. I tried to see if there's a pattern with this issue, but I haven't found one. It happens randomly. So I started wondering if there could be something wrong with Heroku or the Postgres add-on I'm using. This is a quite serious issue, but I can't figure out what the problem is. Has anyone experienced similar issue or knows the answer to this? Thank you very much. -
Django message history
I wonder if you have any ideas on this I present messages as below - it works great, when there is an error it shows the error. But, how do I retain these messages - so the user can see all of the errors they had since their session started? I.e. if I working for a while, I might want to review all my form validation failures at the end. Thanks messages.error(request, ('ERROR: Your milestone was not created. Milestone points must be numeric. Please try again.')) -
django form dynamic drop-down list
I am a newbie in Django. I want to create a dropdown list which can be created from django-admin dynamically without editing coding multiple times. I don't know how to do it. Thanks in advance. -
cannot install msqlclient on win 10. fatal error C1083: Cannot open include file: 'mysql.h' No such file or directory
To install mysqlclient using pip I download visual c++ and install it. but when i run this code: pip install mysqlclient I get this error: fatal error C1083: Cannot open include file: 'mysql.h' No such file or directory. I have win10 and python version 3.10.0 on my system. Please help me with this error. -
How to speed up stacked queries in Django using caching
Current in my project, I have a layer of models as such: Sensor class: which stores different sensors Entry class: which stores whenever a new data entry happens Data class: which stores data pairs for each entry. Generally, that additional class was used since I have different fields for different sensors and I wanted to store them in one database, so how I was doing that was through two methods, one for entry to get the data for it, and one in the sensor as follows: class Data(models.Model): key = models.CharField(max_length=50) value = models.CharField(max_length=50) entry = models.ForeignKey(Entry, on_delete=CASCADE, related_name="dataFields") def __str__(self): return str(self.id) + "-" + self.key + ":" + self.value class Entry(models.Model): time = models.DateTimeField() sensor = models.ForeignKey(Sensor, on_delete=CASCADE, related_name="entriesList") def generateFields(self, field=None): """ Generate the fields by merging the Entry and data fields. Outputs a dictionary which contains all fields. """ output = {"timestamp": self.time.timestamp()} for entry in self.dataFields.all(): if field is not None: if entry.key != field: continue try: value = float(entry.value) if math.isnan(value) == True: return None else: output[entry.key] = float(entry.value) except: pass return output class Sensor(models.Model): . . . def generateData(self, fromTime, toTime, field=None): fromTime = datetime.fromtimestamp(fromTime) toTime = datetime.fromtimestamp(toTime) entries = self.entriesList.filter(time__range=(toTime, fromTime)).order_by( "time" … -
Django limit choice of user field foreign key based on the user that logged in
I have a model called Client with user field as a foreign key: class Client(models.Model): name = models.CharField(_('Client Name'), max_length=100) address = models.CharField(_('Client Address'), max_length=100, blank=True) demand = models.PositiveIntegerField(_('Client Demand')) location = models.PointField(_('Client Location')) created_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) class Meta: default_permissions = ('add', 'change', 'delete', 'view') def __str__(self): return self.name I want to limit the choice of the user field in the admin form based on who logged in for example, here I logged in as agung, so I want the select box choice of user field limit only to agung, but here I can access other username like admin and rizky. I tried this class ClientAdminForm(forms.ModelForm): class Meta: model = Client fields = "__all__" def __init__(self, request, *args, **kwargs): super(ClientAdminForm, self).__init__(request, *args, **kwargs) if self.instance: self.fields['user'].queryset = request.user but it seems that it can't take request as an argument (I guess because this is not an Http request) -
Losing image files saved by users after deployment updates to AWS
My Django App have a CRUD where users can save news with an image. All my static files like banners and css files are working good. When the app is running and users create News, everything works fine too. My problem starts when I need deploy updates to production. After deployment, the app is losing all image files uploaded by users. When users upload images, it are saved inside project folder and I think deployments are overwriting all project folder. What can I do to solve this? Some configs in my Settings.py which I think are important: MEDIA_ROOT = os.path.join(BASE_DIR, 'Setup/media') MEDIA_URL = '/media/' DEBUG = False I Already tried change the image path to outside project folder. But this don't work in production, because I don't have access to folders outside project in AWS. -
Checking the payment status from an payment APi
Am trying to verify user transaction on paystack. After a user makes payment, I want what to append the reference to the Api URL to check if the payment was succcessful. If the payment is successful then save the model. import requests from django.conf import settings class Paystack: PAYSTACK_SECRET_KEY = "sk_test_3cd83d64a1de3a7334bdad47e3fdfa01bf16a059" base_url = "https://api.paystack.co" def verify_payment(self, reference, *args, **kwargs): path = f'/transaction/verify/{reference}' headers ={ "Authorization": f"Bearer {self.PAYSTACK_SECRET_KEY}", "Content-Type":'application/json' } url = self.base_url + path response = requests.get(url, headers=headers) if response.status_code == 200: response_data = response.json() return response_data['status'], response_data['data'] response_data = response.json() return response_data["status"], response_data["message"] def process_payment(request, slug, amount, award, votes): reason = request.GET.get('reason') transaction_id = request.GET.get('reference') amount = (str(int(amount) / 100)) paystack = Paystack() status = paystack.process_payment(self.reference) if status == "success": transaction = SuccessfulTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount, award=award ) transaction.save() Nomination.objects.filter(slug=slug).update(votes=F('votes') + votes) Award.objects.filter(slug=award).update(amount=F('amount') + amount) return redirect('vote:paymentsuccess', slug=slug) else: context = { 'error': reason } transaction = FailedTransactionHistory( nominee_name=slug, transaction_id=transaction_id, amount=amount, award=award ) transaction.save() return render(request, 'payment_error.html', context=context) This is the eeror i get AttributeError at /payment/Paul/000000000020/halotech-award-8/1/ 'Paystack' object has no attribute 'process_payment' -
Django (Gunicorn) doesn't see ENV VARS in production but Django-shell does
I'm pretty desperate here. I can't figure out why Django doesn't see environment variables even if shell can. in settings.py BASE_URL = os.getenv('VUE_APP_WEB_URL','http://127.0.0.1:8080/') in admin.py class _UserAdmin... ... list_display = ('username', 'email', 'is_staff', '_set_pwd_url','base_url') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') def base_url(self, obj: User): return settings.BASE_URL in /etc/environment VUE_APP_WEB_URL=http://my.url.xyz/ Server has been rebooted multiple times, also Gunicorn has been restarted by sudo service gunicorn restart It's still showing the default value, not the ENV VAR. Now, when I test it in django shell: Python 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> settings.BASE_URL 'http://my.url.xyz/' >>> What is going on? PS: Browser cache is not the problem. -
how to delete a previous message if we get new message in django channels
I want to broadcast the only latest message of Django-channel layer in a specific room. Right now I have created specific room names for specific users. Now I just want to send them only latest message or note, I don't want to show all the previous messages. Right now all the previous message are showing to user side. # chat/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ProjectConsumer(AsyncWebsocketConsumer): async def connect(self): parameter = self.scope['url_route']['kwargs']["project_key"] print("url_parameter ",parameter) self.room_name = parameter # Join room group await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) instance_user = text_data_json['instance_user'] sender = text_data_json['sender'] receiver = text_data_json['receiver'] message = text_data_json['message'] object = { 'sender':sender, 'receiver':receiver, 'message':message, } # Send message to room group await self.channel_layer.group_send( self.room_name, { 'type': 'sent', #function name as an event type 'object': object #function parameters as an event object } ) # Receive message from room group async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) -
How to give validations for a PrimaryKeyRelatedField serializer
How can I add validations like required=true to the primarykeyrelated serializer? models.py class WorkLocation(models.Model): city = models.CharField(max_length=255) latitude = models.FloatField() longtitude = models.FloatField() serializers.py class WorkLocationField(serializers.PrimaryKeyRelatedField): queryset = WorkLocation.objects.all() def to_internal_value(self, data): if type(data) == dict: location, created = WorkLocation.objects.get_or_create(**data) data = location.pk return super().to_internal_value(data) class JobPostSerializer(serializers.ModelSerializer): work_location = WorkLocationField() class Meta: model = JobPost fields = "__all__" A part of my data looks like: "hourly_pay": 10, "yearly_pay": 120, "work_location": { "city": "kottayam", "latitude": 0.00001, "longtitude": 0.0012 }, "Benefit": [ 1 ], I need validations for the nested JSON data. -
HTML image not found django
I know that there are a lot of questions with this error but I am trying all of the tips and I am not having success yet. I installed django and I want to introduce two images in my web map. I try everything and the images are not found yet. I have a folder static inside my project and inside static I have a folder images with the images. I also tested with the folder images outside the static folder. In my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'gic\static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'images') MEDIA_URL = '/images/' and in index.html file {% load static %} <img src="{% static "coalmine_logo.png" %}" alt="Cinque Terre" width=350 height=120/> and an error appears: GET http://localhost:8000/static/coalmine_logo.png 404 (Not Found) -
unable to install pyodbc using python 3.10 in windows 10
I get this Error when I try to install Pyodbc , I have already install visual studio and I have Microsoft Visual C++ 12 , 15-19 in my machine but still its giving this error. Running setup.py clean for pyodbc Failed to build pyodbc Installing collected packages: sqlparse, pytz, asgiref, pyodbc, Django, Pillow, mssql-django, django-crispy-forms Running setup.py install for pyodbc ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\Athar\Desktop\New folder\Project\HeatlhCare\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Athar\\AppData\\Local\\Temp\\pip-install-w0wwm18g\\pyodbc_61963e883a8543fea24a63b1c522bbea\\setup.py'"'"'; __file__='"'"'C:\\Users\\Athar\\AppData\\Local\\Temp\\pip-install-w0wwm18g\\pyodbc_61963e883a8543fea24a63b1c522bbea\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Athar\AppData\Local\Temp\pip-record-t1td50y6\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Athar\Desktop\New folder\Project\HeatlhCare\venv\include\site\python3.10\pyodbc' cwd: C:\Users\Athar\AppData\Local\Temp\pip-install-w0wwm18g\pyodbc_61963e883a8543fea24a63b1c522bbea\ Complete output (7 lines): running install C:\Users\Athar\Desktop\New folder\Project\HeatlhCare\venv\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. warnings.warn( running build running build_ext building 'pyodbc' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\Athar\Desktop\New folder\Project\HeatlhCare\venv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Athar\\AppData\\Local\\Temp\\pip-install-w0wwm18g\\pyodbc_61963e883a8543fea24a63b1c522bbea\\setup.py'"'"'; __file__='"'"'C:\\Users\\Athar\\AppData\\Local\\Temp\\pip-install-w0wwm18g\\pyodbc_61963e883a8543fea24a63b1c522bbea\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record … -
django form request post not loading data
I have am trying to load submitted data into a Form instance, request.POST has valid value but form does not. class ArticleCreateForm(forms.Form): title = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'autocomplete': 'off'}), label='') tagging = forms.CharField(max_length=255, required=False, widget=forms.TextInput(attrs={'autocomplete': 'off'}), label='') towhere = forms.CharField(max_length=20, required=False) # default to unchecked, save class Meta: fields = ['title', 'tagging', 'towhere'] def clean_title(self): data = self.cleaned_data['title'] if len(data) < 3: raise ValidationError('Title is too short') def clean_tagging(self): data = self.cleaned_data['tagging'] if len(data) == 0 or data is None: raise ValidationError('Please add at least one tag') @login_required def articleChangeView(request, pk): try: article = Article.objects.get(pk=pk) if article.author != request.user: raise PermissionDenied() elif request.method == 'POST': form = forms.ArticleCreateForm(request.POST) print('--------') print(request.POST) print(form.cleaned_data) <QueryDict: {'csrfmiddlewaretoken': ['gm0ODMFud35nhHlPdBr3IHVZXgtiDQV8zGPsscGWzcpylNVd0fnray7iodJvBWyb'], 'title': ['Title'], 'tagging': ['jquery']}> {'title': None, 'tagging': None, 'towhere': ''} I wonder why this happens, I will be so glad if you can give me a hand -
Updating fields via subquery in Django
I have an app with models and db schema that looks as shown below. I am trying to add field r to L2 in order to be able to access the related objects from model R. The new field is not shown in the schema figure. Retrieving the desired value of field r using a subquery and an annotation works as expected. However, populating/updating the field with an update() call does not work. Do I have to modify my subquery? Or is this not possible at all in Django without resorting to raw SQL? Models and schema from django.db import models class L1(models.Model): desc = models.CharField(max_length=16) m1 = models.ForeignKey('M1', on_delete=models.CASCADE) class L2(models.Model): desc = models.CharField(max_length=16) l1 = models.ForeignKey('L1', on_delete=models.CASCADE) m2 = models.ForeignKey('M2', on_delete=models.CASCADE) # r is the field added r = models.ForeignKey('R', null=True, default=None, on_delete=models.SET_NULL) class M1(models.Model): desc = models.CharField(max_length=16) class M2(models.Model): desc = models.CharField(max_length=16) class R(models.Model): desc = models.CharField(max_length=16) m1 = models.ForeignKey('M1', on_delete=models.CASCADE) m2 = models.ForeignKey('M2', on_delete=models.CASCADE) Sample code from random import randint from django.db import connection, reset_queries from django.db.models import F, OuterRef, Subquery from myapp.models import L1, L2, M1, M2, R # create random data for m in range(10): M1.objects.create(desc=f'M1_{m:02d}') M2.objects.create(desc=f'M2_{m:02d}') for r in range(40): R.objects.create(desc=f'R_{r:02d}', m1_id=randint(1,10), m2_id=randint(1,10)) … -
django: smart-select ChainedForeignKey / chained dropdown in admin
Hej! :) I have 5 models which are connected hierarchical with each other. Section -> division -> group -> class -> wz one section can have multiple divisions, but one division can only have one section (and so on). Therefor I have ForeignKeys set: # models.py class NaceSection(models.Model): code = models.CharField(max_length=1, unique=True) description_english = models.CharField(max_length=500) class NaceDivision(models.Model): code = models.CharField(max_length=2, unique=True) nace_section = models.ForeignKey(NaceSection, on_delete=models.CASCADE, related_name="nace_section") description_english = models.CharField(max_length=500) class NaceGroup(models.Model): nace_division = models.ForeignKey(NaceDivision, on_delete=models.CASCADE, related_name="nace_division") code = models.CharField(max_length=4, unique=True) description_english = models.CharField(max_length=500) I than have a model where all those are integrated as M2M fields with a dropdown option. My goal is to only get the divisions which are in the already selected section in the admin area. (and so on) I tried smart-select ChainedForeignKey: # models.py class Institution(models.Model): nace_sections = models.ManyToManyField( NaceSection, related_name="nace_sections" ) nace_divisions = ChainedForeignKey( NaceDivision, chained_field="nace_sections", chained_model_field='nace_sections', blank=True, ) nace_group = ChainedForeignKey( NaceGroup, chained_field="nace_divisions", chained_model_field='nace_divisions', blank=True, ) The organisation and dropdown in the admin area do not change at all and my view with a table of all my results tells me ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'nace_divisions_id'. (207) (SQLExecDirectW)") With the ChainedManyToManyField nothing at all happens. Does anybody … -
How to serialize data from celery to django rest framework
I am using Celery - Redis - Django rest framework (DRF). What I am trying to do: DRF Passes URL to the celery task/function Celery then fetches that image and applies the logic Celery Sends id of new object created DRF retrieves the instance from the object saved and serializes and sends it to react (the problem is in this step) I am not able to unpack and serialize the message from celery so I am able to send it as a response. Here is my code: Here is the viewset class TestSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = WebsiteURLSerializer def create(self, request, *args, **kwargs): serializer = WebsiteURLSerializer(data=request.data) if serializer.is_valid(): url_site= serializer.validated_data['url'] result = test_call.delay(url_site) result_unpacked = WebsiteURLSerializer(ModelName.objects.filter(pk=result.get())) #the below line seems return an empty response return Response(result_unpacked.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @shared_task(name="values") def test_call(url_image): model_instance = ModelName.objects.create() ..some logic model_instance.save() return model_instance.id -
Validate one field in form which allows multiple photos upload
I have the custom form that allows to upload multiple photos which I'm using in UserAdmin model. Also I have my own validator for a field in User model. I was trying to make a validator for the field of my form by overriding clean method, but clean method made my custom validator in User model unworkable, so it means my validator for a field in User model became useless because clean method in forms.py works for everything. I've tried to go through this answer but it didn't help me. How can I make each validator work for the field that they are intended for? forms.py from django import forms from django.utils.safestring import mark_safe from .models import UserImage class PhotoUploadForm(forms.ModelForm): photo = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False, help_text='Необходимо количество фото - 10', label=mark_safe("<strong style='color:black'>Фото</strong>") ) def clean_photos(self): photos = self.files.getlist('photo') if len(photos) != 10: raise forms.ValidationError( {'photo': f'Вы попытались загрузить {len(photos)} фотографий'}) return photos class Meta: model = UserImage fields = '__all__' admin.py @admin.register(User) class UserAdmin(admin.ModelAdmin): form = PhotoUploadForm models.py class User(models.Model): first_name = models.CharField( verbose_name='Имя', max_length=40, ) last_name = models.CharField( verbose_name='Фамилия', max_length=40 ) rfid_mark = models.CharField( verbose_name='RFID', max_length=10, unique=True, help_text='RFID должен состоять из 10 символов', error_messages={ 'unique': 'Такой RFID уже …