Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 уже … -
Parse python multiline traceback to one line with fluentbit
My python application writing logs to STDOUT and I am collecting the logs with fluentbit agent. My logs sample Checking for future activity Activity Time: 1636487814 Current Time: 1636490831 Not the future activity request for athlete: 505 [2021-11-09 20:47:11,781] ERROR in app: Exception on /api/v1/lala/activity-request [POST] Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/usr/local/lib/python3.7/site-packages/newrelic/hooks/framework_flask.py", line 64, in _nr_wrapper_handler_ return wrapped(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 467, in wrapper resp = resource(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/flask/views.py", line 89, in view return self.dispatch_request(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 582, in dispatch_request resp = meth(*args, **kwargs) File "./test-app/api/resources/lala/v1/resources.py", line 111, in post lalaService.send_activity_request_to_broker(athlete, activity_request) File "./test-app/api/resources/lala/services.py", line 94, in send_activity_request_to_broker ThirdPartyService.produce_activity(activity_data) File "./test-app/api/resources/common/services.py", line 91, in produce_activity get_or_create_eventloop().run_until_complete(produce_activity(activity_data)) File "/usr/local/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete return future.result() File "./test-app/producer.py", line 12, in produce_activity await result RuntimeError: Task <Task pending coro=<produce_activity() running at ./test-app/producer.py:12> cb=[remove_from_cache() at /usr/local/lib/python3.7/site-packages/newrelic/hooks/coroutines_asyncio.py:20, _run_until_complete_cb() at /usr/local/lib/python3.7/asyncio/base_events.py:157]> got Future <Future pending cb=[Topic._on_published(message=<FutureMessage pending>, state={}, producer=<Producer: running >)()]> attached to a different loop [pid: 10|app: 0|req: 15952/63804] 10.0.225.22 () {60 vars in 2181 bytes} [Tue Nov 9 20:47:11 2021] POST /api/v1/lala/activity-request => generated 37 bytes in 506 msecs (HTTP/1.1 500) … -
Implement Odoo Connector for external application?
The exact question is about roadmap of implementation. It is Django application that I'm mentioning as external application. Actually I want to speak (sending changed data to Django) with Django when data created, deleted or updated on Odoo. Also how can I get the mutated data from Django app? In other word I want to learn how can I build synchronization structure (bidirectional synchronization) between Odoo and Django app? is there any information can help? -
How to improve multiple query for multiple chart in 1 page
I would like to increase speed for loading page for my website I have to write code with difference group by eg. data that group by period type data that group by country data that group by daterange Question:how can i improve my coding for increse speed on query?. View.py def get_queryset(self): dateRange = self.request.query_params.get('dateRange') if dateRange is not None: datestart = datetime.datetime.strptime(dateRange.split('-')[0], "%Y%m%d").strftime("%Y-%m-%d") dateend = datetime.datetime.strptime(dateRange.split('-')[1], "%Y%m%d").strftime("%Y-%m-%d") else: year_today = str((datetime.datetime.now().date() - datetime.timedelta(days=1)).year) week_today = str((datetime.datetime.now().date() - datetime.timedelta(days=1)).isocalendar()[1] - 1) datestart = datetime.datetime.strptime(year_today + '-W' + week_today + '-1', "%Y-W%W-%w") dateend = datetime.datetime.strptime(year_today + '-W' + week_today + '-0', "%Y-W%W-%w") queryset = ranking_page_data.objects.filter(Date_start__range=(datestart, dateend), Period_Type="daily", Order_Type="Gross Order").values('Country').annotate( Sales_Euro=Sum('Sales_Euro'), Orders=Sum('Orders'), Unit=Sum('Unit'), buyers=Sum('buyers'), Visitors=Sum('Visitors'), Pageview=Sum('Pageview'), Conversion_Rate=Avg('Conversion_Rate')).order_by('-Sales_Euro') queryset1 = ranking_page_data.objects.filter(Date_start__range=(datestart, dateend), Period_Type="daily", Order_Type="Gross Order").values('Platform').annotate( Sales_Euro=Sum('Sales_Euro'), Orders=Sum('Orders'), Unit=Sum('Unit'), buyers=Sum('buyers'), Visitors=Sum('Visitors'), Pageview=Sum('Pageview'), Conversion_Rate=Avg('Conversion_Rate')).order_by('-Sales_Euro') queryset2 = ranking_page_data.objects.filter(Date_start__range=(datestart, dateend), Period_Type="daily", Order_Type="Gross Order").values('Country','Platform').annotate( Sales_Euro=Sum('Sales_Euro'), Orders=Sum('Orders'), Unit=Sum('Unit'), buyers=Sum('buyers'), Visitors=Sum('Visitors'), Pageview=Sum('Pageview'), Conversion_Rate=Avg('Conversion_Rate')).order_by('-Sales_Euro') return queryset,queryset1,queryset2 and model.py class ranking_page_data(models.Model): ID = models.IntegerField() Specific_Identity = models.TextField() Country = models.TextField() Platform = models.TextField() Brand = models.TextField() Period_Type = models.TextField() Date_start = models.DateField() Date_end = models.DateField() Order_Type = models.TextField() Date = models.TextField() Time = models.TextField() Conversion_Rate = models.FloatField() Orders = models.IntegerField() buyers = models.IntegerField() Pageview = models.IntegerField() Unit = models.IntegerField() Visitors = models.IntegerField() … -
Audio recording in modal Bootstrap and Django
I need to insert in a boostrap modal the possibility to record a microphone audio and pass the file to the django view. For the text I did it like this but I don't know how to do it for the audio, ideas? HTML: <div class="modal fade" id="textModal"> <div class="modal-dialog"> <div class="modal-content"> <form action="results_text_analysis" method="POST"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Input text</h4> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <!-- Modal body --> <div class="modal-body"> {% csrf_token %} <textarea type="text" class="form-control input-lg" name="text"></textarea> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Calculate</button> </div> </form> </div> </div> VIEW: @api_view(['POST']) def results_text_analysis(request): input_text = request.POST['text'] ..... -
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance
I am using Django Rest and my request parameter contains: [ { "job_role": 2, "technology": 1 }, { "job_role": 1, "technology": 1 }, { "job_role": 2, "technology": 1 } ] My models are: class Technology(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class JobRole(models.Model): role_name = models.CharField(max_length=100) def __str__(self): return self.role_name class ExpertPricing(models.Model): role_name = models.OneToOneField(JobRole, related_name="role", on_delete=models.SET_NULL, null=True) experience_in_years = models.PositiveBigIntegerField() technology = models.OneToOneField(Technology, related_name="technology", on_delete=models.SET_NULL, null=True) salary_per_month = models.PositiveBigIntegerField() My view looks like this: class PricingView(APIView): def post(self, request): datas = request.data data_list = [] for data in datas: job_role_id = data["job_role"] technology_id = data["technology"] job_role = JobRole.objects.get(pk=job_role_id) technology = Technology.objects.get(pk=technology_id) expert_pricing = ExpertPricing.objects.filter(role_name=job_role, technology=technology) if expert_pricing: data_list.append(expert_pricing) serializer = ExpertPricingSerializer(data_list, many=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class TechnologySerializer(serializers.ModelSerializer): class Meta: model = Technology fields = ("id", "name") class JobRoleSerializer(serializers.ModelSerializer): class Meta: model = JobRole fields = ("id","role_name") class ExpertPricingSerializer(serializers.ModelSerializer): role = JobRoleSerializer(many=False, read_only=True) technology = TechnologySerializer(many=False, read_only=True) class Meta: model = ExpertPricing fields = "__all__" I am unable to understand why data_list is not being serialized. the error says: AttributeError: Got AttributeError when attempting to get a value for field `experience_in_years` on serializer `ExpertPricingSerializer`. The serializer field might be named incorrectly and not match any attribute or key … -
AttributeError: 'QuerySet' object has no attribute 'save'
This is the page that I'm trying to work out. If the update is clicked, the filled-in details should be updated in a MySql database called TL. But while clicking update, it's throwing the following error: AttributeError at /add/ 'QuerySet' object has no attribute 'save' The following is Views.py file in Django where I had put code for add: def add(request): ad = TL.objects.all() if request.method == 'POST': TL_Name = request.POST.get('TL_Name') Proj_name = request.POST.get('Proj_name') Deadline = request.POST.get('Deadline') ad.TL_Name = TL_Name ad.Proj_name = Proj_name ad.Deadline = Deadline ad.save() return redirect("/operations") return render(request, 'operations.html', {"name": ad, 'b': ad}) The following is the urls.py file: from . import views urlpatterns = [ path('', views.home), path('adminlogin/', views.adminlogin), path('operations/', views.operations), path('approve/<int:pk>', views.approval), path('decline/<int:pk>/', views.delete), path('edit/<int:pk>/', views.edit), path('add/', views.add), path('tlist/', views.approved_tlist) ] The following is the operations.html file: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Team Leaders</title> </head> <body> <h1>List of Team Leaders</h1> <table id="table"> <tr> <th>TL_Name</th> <th>Proj_name</th> <th>Proj_Status</th> <th>Deadline</th> <th>Action</th> </tr> {% for i in name %} <tr> <td>{{i.TL_Name}}</td> <td>{{i.Proj_name}}</td> <td>{{i.Proj_Status}}</td> <td>{{i.Deadline}}</td> <td> <a href="/approve/{{i.id}}">Approve</a> <a href="/decline/{{i.pk}}">Decline</a> <a href="/edit/{{i.pk}}">Edit</a> </td> </tr> {% endfor %} </table> <br> <br> {% if a %} <form method="post"> {% csrf_token %} <table> <tr> <td> <label>TL_Name</label> </td> <td> <input type="text" name="TL_Name" … -
Unable to display the firebase push notification/message on background mode
Im working on firebase messaging service to send push notification via django web application to Andriod,IOS and website as well, i refer to this link, i managed to get token but not able to display the message on background mode, please find the js code in html index page and firebase-messaging-sw for your reference (Note: i don't get any error, but at the same time I don't receive any notification nor message!!) html: <!-- Getting the tocken --> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js'; // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "xxxxxxxxxxxxxx", authDomain: "xxxxxxxxxxxxxx", projectId: "xxxxxxxxxxxx", storageBucket: "xxxxxxxxxxxxxxxx", messagingSenderId: "xxxxxxxxxxxxxxxxx", appId: "xxxxxxxxxxxxxxxxxxxxx", measurementId: "xxxxxxxxxxxxxxxxxxx" }; // Initialize Firebase const app = initializeApp(firebaseConfig); import { getMessaging, getToken } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js'; // Get registration token. Initially this makes a network call, once retrieved // subsequent calls to getToken will return from cache. const messaging = getMessaging(); getToken(messaging, { vapidKey: 'BJRrwDBTJkgQ0j0buwcfLsSxfr5tOxPrOzI5XM7J38n-k9Tzeq8qrY8SPeHyb3LRF49eFEj7lv6BiDFhEVJZn0A' }).then((currentToken) => { if (currentToken) { console.log(currentToken); // Send the token to your server and update the UI if necessary // ... } else … -
infinite scroll working but not populating all data because of javascript call
in my web site i want to show the user ratings for that i used the infinite scroll but i am facing one problem. when it first loads the data before calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is showing the star with the count of vote,but when after calling the <a class="infinite-more-link" href="?page={{ ratings.next_page_number }}"></a> it is not showing the star. my views.py @login_required def ratings_user(request,pk): ratings = VoteUser.objects.filter(the_user_id=pk).order_by('-pk') paginator = Paginator(ratings, 1) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,request.session['is_mobile']+'profile/ratings.html',{'ratings':posts}) html {% extends 'mobile/profile/base.html' %} {% block title %} Ratings {% endblock %} {% block leftcontent %} <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"> {% endblock %} {% block middlecontent %} <div class="infinite-container"> {% for i in ratings %} <div class="infinite-item"> <div class="w3-container w3-card w3-white w3-round w3-margin"> <img src="{{ i.the_user.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:40px;height:40px;border-radius:50%;"> <a href ="{% url 'profile' i.the_user_id %}" style="color:black;">{% with user=i.the_user.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}</a> <br> <span class="stars" data-rating="{{ i.vote.vote }}" data-num-stars="5" ></span> <hr class="w3-clear"> <p> {{ i.commentaire|linebreaksbr }} </p> <span class="glyphicon glyphicon-user"></span> <a href ="{% url 'profile' i.the_sender_id %}">{% with user=i.the_sender.profile %}{{ user.prenom|title|truncatewords:2 }} {{ user.nom|title|truncatewords:1 }}{% endwith %}</a> </div> … -
How to retrieve Django list as array in Javascript
I'm sending django list from view.py to my javascript. But when I receive the list in javscript, it only return me as string. I tried to print the type of the variable but it show me false which mean its not array list. So how can I retrieve the list as array in Javascript? View.py mergedCompare = [item_listAssigned[f'subject{i}'] + ': ' + item_listAssigned[f'serial{i}'] for i in range(1, len(item_listAssigned) // 2 + 1)] global context context = { 'mergedCompare': mergedCompare } mergedCompare = ['EMP004: BPCE-RNHC-25G8', 'EMP003: 8FIW-9JRB-NY4J', 'EMP005: 7QF2-6HI9-XKZZ', 'EMP002: SG8P-YQKG-ZV3C', 'EMP001: PBF7-WZHT-WPZR'] JavaScript: var assignedDevices = "{{mergedCompare|safe}}" const list = assignedDevices; console.log(Array.isArray(list)) //false , not array -
Is there a way to add more than one field on a dropdown?
So I am calling fields from a persons class to a shareholders class so I us a Many2One field to call the field to call the firstnames as drop form the persons class. I now want to show the firstname, lastname and email on the dropdown. class shareholder(models.Model): person_id = fields.Many2one('person', string='First Name', required=True) last_name = fields.Char(string='Last Name', related= 'person_id.last_name') email = fields.Char(string='Email Address', related= 'person_id.email') -
Django models datetime with timezone UTC+1 saved as UTC+0
In my django project i have a model where i store data (in my read_date field) with a DateTime field for storing date (with timezone): class Results(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) i setted in settings.py file using timezone: TIME_ZONE = 'UTC+1' USE_TZ = True So, the problem is, when i pass a corrected formatted ditetime with UTC+1 timezone as: 2021-11-12 10:39:59.495396+01:00 in my db i get: 2021-11-12 9:39:59.495396+00 Why my stored value is UTC+0 instead using timezone passed? So many thanks in advance -
I am having some trouble designing API endpoint for my Django App (DRF)
I am designing an API for an E-learning project. The platform enables students to take online tests. The tests contain questions and questions can have multiple options. Below is the schema for my app: Test: id: Primary Key duration: Integer created: Timestamp Question: id: Primary Key serial: Integer test: Foreign Key (Test) body: Char Field Option: id: Primary Key question: Foreign Key (Question) body: Char Field correct: Boolean Field StudentSelectedOption: id: Primary Key question: Foreign Key (Question) student: Foreign Key (User) option: Foreign Key (Option) Now, the problem is that I want to create an endpoint for returning student selected options based on the requesting user /test/<int:test_id>/student-answers/ But I am not able to filter selected options related to the test id and user. Can someone help me out?