Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with serializers creating an API with Django
I am writing an API with django and I am having this problem: When I create a serializer object, if I do it like this: document_serializer = DocumentSalesforceSerializer(data={ "AccountId": patient_id, "ContactId": patient_id, "Proveedor__c": "docline", "Servicio_asociado__c": "report", "Mapfre_Id__c": patient_id, "Status": "In Progress", "StartDate": document["createdAt"], "EndDate": "hoy", "Subject": document["category"], "Description": description, "SAV_fld_source__c": "docline", "SAV_fld_doclineExtId__c": id, "SAV_fld_doctor__c": "", }) document_serializer.is_valid(raise_exception=True) I get the following error: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. Reading on the internet some people said that I whould delete the data= part, so I left it like this: document_serializer = DocumentSalesforceSerializer({ "AccountId": patient_id, "ContactId": patient_id, "Proveedor__c": "docline", "Servicio_asociado__c": "report", "Mapfre_Id__c": patient_id, "Status": "In Progress", "StartDate": document["createdAt"], "EndDate": "hoy", "Subject": document["category"], "Description": description, "SAV_fld_source__c": "docline", "SAV_fld_doclineExtId__c": id, "SAV_fld_doctor__c": "", }) document_serializer.is_valid(raise_exception=True) But then I am getting this error: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. Does anyone have and idea of what is causing the error? Thanks in advance for reading this question. -
How to get the template after rendering (Django)
I want to have the site template that is sent to the user after rendering in middleware. -
503 Service Unavailable Error while hosting Django website on CyberPanel
I am trying to host my Django website using CyberPanel on OpenLiteSpeed. I have completed website development. The website is running properly when I run in debug mode (using runserver command). I am trying to deploy the website. I am using CyberPanel as I wish to deploy my own SMTP server. I have used the following article to install cyber-panel on my digital ocean server : https://cyberpanel.net/docs/installing-cyberpanel/ I have used the following article to install and configure Django based website on Openlitespeed server https://cyberpanel.net/blog/2019/01/10/how-to-setup-django-application-on-cyberpanel-openlitespeed/ When I try to open website unionelectronics.in I get 503 Service Unavailable (The server is temporarily busy, try again later!) error. I have updated A record in DNS Management on godaddy to point to my cloud service provider (digital ocean). Error Log : 2021-10-05 14:53:37.241089 [INFO] [817] [config:server:vhosts:vhost:Example] config context /docs/. 2021-10-05 14:53:37.241103 [INFO] [817] [config:server:vhosts:vhost:Example] config context /protected/. 2021-10-05 14:53:37.242757 [INFO] [817] [PlainConf] [virtualHostConfig:] start parsing file /usr/local/lsws/conf/vhosts/unionelectronics.in/vhost.conf 2021-10-05 14:53:37.243519 [INFO] [817] [PlainConf] [virtualHostConfig:] Finished parsing file /usr/local/lsws/conf/vhosts/unionelectronics.in/vhost.conf 2021-10-05 14:53:37.243533 [INFO] [817] [PlainConf] [virtualHostConfig:] context [/] add param [envtype 1] 2021-10-05 14:53:37.251116 [NOTICE] [817] [SSL_CTX: 0x124eb20] OCSP Stapling can't be enabled: [OCSP] /etc/letsencrypt/live/unionelectronics.in/fullchain.pem: X509_STORE_CTX_get1_issuer failed!. 2021-10-05 14:53:37.251224 [INFO] [817] [config:server:vhosts:vhost:unionelectronics.in] config context /. 2021-10-05 14:53:37.257606 … -
Cant write correct queryset in Django
i have three models:subplan,subplanfeature and price.I wanna show gym price table,but it shows wrong result class SubPlan(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class SubPlanFeature(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Price(models.Model): gym=models.ForeignKey(Gym,on_delete=CASCADE) subplan=models.ForeignKey(SubPlan,on_delete=CASCADE,related_name='subplans') feature=models.ForeignKey('SubPlanFeature',on_delete=CASCADE,related_name='features') price = models.IntegerField() highlight_status = models.BooleanField(default=False,null=True) here is my view def pricing(request,slug): gym=models.Gym.objects.get(slug=slug) price=models.Price.objects.all() banners=models.Banners.objects.filter(gym=gym) plans1= models.Price.objects.filter(gender='man',gym=gym) dfeatures1=models.Price.objects.filter(gender='man',gym=gym) return render(request, 'pricing.html',{'plans1':plans1,'dfeatures1':dfeatures1,'gym':gym}) and template here <thead> <tr> <th style="width: 34%;"></th> {% for plan in plans1 %} <th style="width: 22%;">{{plan.subplan}}</th> {% endfor %} </tr> </thead> <tbody> {% for feature in dfeatures1 %} <tr> <th scope="row" class="text-start">{{feature.feature}}</th> {% for plan in plans1 %} <td> {{plan.price}} Azn. </td> {% endfor %} </tr> {% endfor %} </tbody> it should display as this enter image description here but shows this enter image description here what should i change? -
Send a zip file as a response using python
This is probably a question already asked but posting it again since I didn't find a way to resolve my issue. I am given a zip file that I need to send to UI from where it should be downloaded for the user. While testing on POSTMAN, using Send & Download button associated with POST, I am able to download the file. But when opening it, it says: Windows cannot open the folder. The Compressed(zipped) folder <zip path> is invalid Here's the code I am trying: from django.response import Response from rest_framework.views import APIView def get_response(): with open(zip_file_path.zip, 'r', encoding='ISO-8859-1') as f: file_data = f.read() response = Response(file_data, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="ReportTest.zip"' return response class GenerateZIP(APIView): def post(self, request): zip_file_response = get_response() return zip_file_response The zip file read is valid as it's already on the local. Any ideas? -
form-data(POSTMAN) only showing "This field is required" in django
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. In post request, raw-data input works, but not form-data. It only shows 'rooms' field is required. module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms, blank=True) room_list = models.CharField(max_length = 100, blank=True) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializerWrite(many=True) class Meta: model = Module fields = '__all__' def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room = Rooms.objects.get(**data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance rooms/serialier.py - class RoomSerialize(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): # Adding the rooms to module from room_list new_request = request.data.copy() room_list=[] if … -
djangochannelsrestframework websocket connection failed with error 500
I am building a simple chat application using djangochannelsrestframework but it gives me error while compiling WebSocket connection to 'ws://localhost:8000/ws/' failed: Error during WebSocket handshake: Unexpected response code: 500 trackback of error at django Internal Server Error: /ws/ Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Python39\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Python39\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "C:\Python39\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "C:\Python39\lib\site-packages\django\template\loader.py", line 47, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html [05/Oct/2021 19:21:55] "GET /ws/ HTTP/1.1" 500 83990 My Code(chat app) consumers.py from .models import Messages from .serializers import MessagesSerializer from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework import permissions from djangochannelsrestframework.mixins import ( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, ) class UserConsumer( ListModelMixin, RetrieveModelMixin, PatchModelMixin, UpdateModelMixin, CreateModelMixin, DeleteModelMixin, GenericAsyncAPIConsumer, ): queryset = Messages.objects.all() serializer_class = MessagesSerializer permission_classes = (permissions.AllowAny,) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"^ws/$", consumers.UserConsumer.as_asgi()), ] serializers.py #from django.db import models #from django.db.models import fields #from djoser.serializers import UserCreateSerializer from rest_framework import serializers from … -
How to display a value in another table by using a function in django
I have been trying to make search_fields able to search for fields in another table on the django admin page. I discovered that I could use a function to achieve my goal, but when I went to the admin page, in place of the data I wanted it to display, it would display <django.db.models.query_utils.DeferredAttribute object at 0x00000208375C9280> Here is my admin.py file: from django.contrib import admin from .models import RiskRegister, Category, Severity, RSev from account.models import Account class RiskRegisterAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity', 'action_taken_explanation', 'created_at'] list_filter = ['id', 'user', 'date', 'category', 'roles', 'responderID', 'severity', 'action_taken_explanation'] search_fields = ['id', 'user', 'user_dept', 'date', 'category', 'roles', 'responderID', 'severity', 'created_at'] def user_dept(self, obj): return Account.department And my models.py file containing the Account model: class Account(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True) email = models.EmailField(verbose_name='email', max_length=254, unique=True) department = models.CharField(verbose_name='department', max_length=100, editable=True) first_name = models.CharField(verbose_name='first name', max_length=254, blank=True) last_name = models.CharField(verbose_name='last name', max_length=254, blank=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) How can I make it display what is in the department? -
I am getting 500 Internal Server Error in django app during deloying on production server ModuleNotFoundError: No module named 'main' (wsgi:error)
I want to serve my project using mod_wsgi. When i run development server, It's started but it gives error on production server.My os is RedHat and using httpd(apache) virtual host configured with python3-mod_wsgi. This is my error [Tue Oct 05 14:01:48.998236 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] mod_wsgi (pid=423542): Failed to exec Python script file '/var/www/public_html/main/main/wsgi.py'. [Tue Oct 05 14:01:48.998291 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] mod_wsgi (pid=423542): Exception occurred processing WSGI script '/var/www/public_html/main/main/wsgi.py'. [Tue Oct 05 14:01:48.998461 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] Traceback (most recent call last): [Tue Oct 05 14:01:48.998506 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/var/www/public_html/main/main/wsgi.py", line 17, in <module> [Tue Oct 05 14:01:48.998523 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] application = get_wsgi_application() [Tue Oct 05 14:01:48.998530 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/usr/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Tue Oct 05 14:01:48.998534 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] django.setup(set_prefix=False) [Tue Oct 05 14:01:48.998540 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup [Tue Oct 05 14:01:48.998543 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Oct 05 14:01:48.998548 2021] [wsgi:error] [pid 423542:tid 140143400638208] [remote 209.141.62.185:36776] File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ [Tue … -
Django + NGINX 404 Not Found
Whenever I run server using gunicorn --bind command, all static files load without any error. but when I try to access my domain It gives 404 error. I am mentioning all my settings related to the static file: STATIC_ROOT (Django): '/var/www/html/static' STATIC_URL = '/static/' /etc/nginx/sites-available/default: (Nginx) server{ root /var/www/html; index index.php index.html index.htm index.nginx-debian.html; server_name 65.1.254.234; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; include proxy_params; proxy_pass http://unix:/home/ubuntu/Application_Code/app.sock; } location /static { autoindex on; alias /var/www/html; } } Is there any problem happening due to .env file? -
How can I transfer this SQL query to Django orm code
The model(the pk/id is auto generated) class Comments(models.Model): parent = models.ForeignKey(to="self", null=True) And the SQL query SELECT * FROM comments WHERE ( parent_id IN ( 1, 2, 3, 4 ) AND ( SELECT COUNT(*) FROM comments AS f WHERE ( f.parent_id = comments.parent_id AND f.id <= comments.id ) )<= 2 ) -
Key 'fieldname' not found in 'ModelForm'. Django 3.2
I am trying to override the get_form function in admin class in Django 3.2. I defined a custom permission for a specific user that can only view some defined fields of a model. It worked fine but when I tried to navigate to the change form of an object with the non-permitted users, I cannot be able to view the change form as superuser until other user closes the change form. So basically, override get_form method is not working at the same time for different kind of users. By the way I did not have any defined view because I am only using admin template as view, I am just only overriding admin template. I am new in django so I don't know that I am doing this correctly... Here is the admin class that I created and override get_form method(for instance I do not want to display surname if the user does not have the custom permission): class HumanAdmin(admin.ModelAdmin): fieldsets = ( ('Fields 1', {'fields': ('id','name', 'surname'),}), ) def get_form(self, request, obj=None, **kwargs): if request.user.has_perm('app_name.custom_permission'): self.fieldsets[0][1]["fields"] = ('id','name', 'surname') form = super(InventoryAdmin,self).get_form(request, obj, **kwargs) else: self.fieldsets[0][1]["fields"] = ('id','name') #I do not want to see if user does not have … -
DRF Pagination custom response without model APIView
Hello I have a project in Django, which performs several queries to different databases returning them in several endpoints, for this I use Pandas and DRF (APIViews). The problem arises when the response is very long and logically the server runs out of memory, I understand that I need to paginate the result but I have not found the way to do it because I do not use models or serializers, I do raw queries with pandas to make the queries. Is there any way to paginate the results the way I'm doing it? I leave some snippets of my code. class AffiliateAPIView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): insurance = self.request.query_params.get('insurance', None) emergensys_df = pd.read_sql_query(general_attention(insurance), engine()) return Response(emergensys_df.to_dict(orient='records')) -
Dynamic ModelChoiceField on template
I would like to have a ModelChoiceField that is dynamically changed by the user directly on the form. Basically I'm building a CMS and User has several templates at its disposal, however I'd like to display in my dropdown only the relevant templates to the kind of content it's producing. For example, we would have a first dropdown to select the content_type. We assume we pick article. Selecting this would update in a second dropdown list both including side_image_article.html and default_article.html. Here is a MRE : models.py class MyTemplate(models.Model): template_name = models.Charfield(max_length=80) content_choices = [("article", "article"), ("project", "project"), ("press_release", "press_release"), ("newsletter", "newsletter"), ("newsletter_web", "newsletter_web"), ("petition", "petition"), ("mailing_list_signup", "mailing_list_signup"), ] content_type = models.CharField(max_length=100, choices=content_choices, default="article") Each template is assigned a content type that is appropriate to the sort of content it's designed for. still models.py class MyBlogitem(models.Model) template = models.ForeignKey(MyTemplate, on_delete=models.PROTECT) body_text = models.TextField() content_choices = [("article", "article"), ("project", "project"), ("press_release", "press_release"), ("newsletter", "newsletter"), ("newsletter_web", "newsletter_web"), ("petition", "petition"), ("mailing_list_signup", "mailing_list_signup"), ] item_type = models.CharField(max_length=100, choices=content_choices, default="article") And the forms.py class MyBlogItemForm(ModelForm): template = ModelChoiceField( queryset=TopicBlogTemplate.objects.filter( content_type=???), empty_label=None) So here the goal would be to filter the template field using the content_type field, both being in dropdown lists. There are being loaded … -
Django FileNotFound image url
The idea is I want my form to upload an image with ImageField and then save a base64 of that image with post_save. Model : class Feed(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length = 200) content = models.TextField() thumbnail = models.ImageField(upload_to='feeds/', blank=True) img_b64 = models.BinaryField(blank=True, null=True) author = models.ForeignKey(Account, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) view = models.IntegerField(default=0) kategori = models.CharField(max_length=100, default="None") post_save : @receiver(post_save, sender=Feed) def save_base64(sender, instance, **kwargs): if instance.thumbnail: img_file = open(instance.thumbnail.url, "rb") instance.image_b64 = base64.b64encode(img_file.read()) instance.save() but I get a FileNotFound error: Traceback (most recent call last): File "D:\Project\Lapor Hoax\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Project\Lapor Hoax\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\Lapor Hoax\env\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Project\Lapor Hoax\laporhoax\account\views.py", line 123, in isi_berita_view form.save() File "D:\Project\Lapor Hoax\env\lib\site-packages\django\forms\models.py", line 468, in save self.instance.save() File "D:\Project\Lapor Hoax\env\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "D:\Project\Lapor Hoax\env\lib\site-packages\django\db\models\base.py", line 774, in save_base post_save.send( File "D:\Project\Lapor Hoax\env\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "D:\Project\Lapor Hoax\env\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "D:\Project\Lapor Hoax\laporhoax\feed\models.py", line 43, in save_base64 img_file = open(instance.thumbnail.url, "rb") Exception Type: FileNotFoundError at /berita/add/ Exception Value: [Errno 2] No such file or directory: … -
Sentry SDK Django set tag for event and raise
This is the current implementation I have: from sentry_sdk import push_scope def run(): with push_scope() as scope: message = "Failed" scope.set_tag("custom", "tag") raise Exception(message) But according to the docs the with-scope context manager will swallow the exception raised inside. The problem is I need this method run to actually raise an Exception so is doesn't send a response to the user. If I handle the flow and capture the sentry event in the with-scope context manager and raise later outside of the context manager, I will end up with duplicate events in Sentry ? from sentry_sdk import push_scope, capture_exception def run(): with push_scope() as scope: message = "Failed" scope.set_tag("custom", "tag") capture_exception(message) raise Exception(message) Is this really sending two events to Sentry and/or is there a better way to deal with this issue, maybe forcing sentry to ignore the raise at this point ? -
CreateView redirect with parameter created from the same view
I have this CreateView that creates an object for me and after creating it I would like it to render me inside that object through its 'nome_scheda' which is a text field. views.py class SchedaCreateView(CreateView): model = Schede fields = ['nome_scheda','data_inizio','data_fine'] template_name = 'crea/passo1.html' def form_valid(self, form): form.instance.utente = self.request.user return super().form_valid(form) urls.py path('crea/<nome>/', creazione, name="creazione_passo1"), -
Publish and "Save Drafts" feature in Django
I am working on a Django Rest Framework B2B application with a React Frontend. The data is fed from a csv and then Analytics dashboards are rendered in React. Each Account ("User") is a company - and within a company, the app is used by the entire marketing team (say). Each company account has data unique to that co. and dashboard preferences unique to that company. An administrator is a human user who is some Manager / employee of a company (let's say, for example, Boeing, Nike etc) who has edit / administrator rights on behalf of the company. That "admin" makes some changes to the dashboard preferences and wants to "Publish" the changes so that rest of the employees (the rest of the Marketing team) of the company Account can view the updated dashboard. But maybe not yet, hence a "Save Drafts" feature. I'm not sure how to get these two features in the most industry-standard way in Django (DRF) - When I hit "Publish", the entire marketing team should be able to see the changes. (It's a B2B app). But when I save drafts, I should be able to view the changes (as admin) but not the rest … -
Django 3.2.3 - 3.2.6 broken pipe error on dev server
I tried beget and digital ocean, different Django-projects (my own and examples) and every time i am getting [05/Oct/2021 12:26:24,844] - Broken pipe from ('94.72.62.225', 53959) I do same things every time: python3 -m venv env . env/bin/activate pip install -r requirements.txt python3 manage.py makemigrations python3 manage.py migrate set ALLOWED_HOSTS=['*'] python3 manage.py rusnerver 0.0.0.0:8000 -
how to use model attribute in views for another model
so basically i have a Product model which has a price attribute as below. class Product(models.Model): name = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() image = models.ImageField(upload_to = 'photos/products') stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name then i have this Main model which i make for payments, as you can see there is an amount attribute also there: class Main(models.Model): user = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) order_id = models.TextField() payment_id = models.TextField() amount = models.IntegerField() date = models.TextField(default='-') card_number = models.TextField(default="****") idpay_track_id = models.IntegerField(default=0000) bank_track_id = models.TextField(default=0000) status = models.IntegerField(default=0) def __str__(self): return str(self.name) now i want to know how to set amount = price ? currently user enter the amount manually from a form. but i want to pass the price to this function and then set it to amount and then delete the amount input from the html def payment_start(request): if request.method == 'POST': order_id = uuid.uuid1() amount = request.POST.get('amount') name = request.POST.get('name') email = request.POST.get('mail') phone = request.POST.get('phone') payer = { 'name': request.POST.get('name'), 'phone': request.POST.get('phone'), 'mail': request.POST.get('mail'), 'desc': request.POST.get('desc'), } record = Main(order_id=order_id, amount=int(amount), … -
Is it possible to return a GET request after saving the post request to the database?
I have been trying to return the GET response after the post request has been made and the data has been saved to the DB. Instead of the serialized validated data being returned to the api caller. It would save another GET request handling on the frontend Here are the serializers: class PollVoteSerializer(serializers.ModelSerializer): class Meta: model = PollVote fields = '__all__' class PollAnswerSerializer(serializers.ModelSerializer): is_correct_answer = serializers.SerializerMethodField() answer_votes = serializers.SerializerMethodField(read_only=True) class Meta: model = PollAnswer fields = ('id', 'answer', 'is_correct_answer', 'answer_votes', ) def get_is_correct_answer(self, object): if object.question.is_finished: return object.is_correct return False def get_answer_votes(self, object): return object.answer_vote.count() class PollQuestionSerializer(serializers.ModelSerializer): choices = PollAnswerSerializer(many=True, read_only=True) total_votes = serializers.SerializerMethodField(read_only=True) user_voted = serializers.SerializerMethodField(read_only = True) class Meta: model = PollQuestion fields = ['id', 'question_name', 'created_by', 'is_finished', 'total_votes','user_voted', 'choices', ] def get_total_votes(self, question_vote): c = PollVote.objects.filter(question=question_vote).count() return question_vote.question_vote.all().count() def get_user_voted(self, object): user_id = self.context['request'].user.id return PollVote.objects.filter(question__id = object.id, voted_by = user_id).exists() Here is the view. class GetPoll(viewsets.ModelViewSet): def get_serializer_class(self): if self.action == 'create': return PollVoteSerializer else: return PollQuestionSerializer queryset = PollQuestion.objects.all().order_by('-id') authentication_classes = (authentication.TokenAuthentication,) permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination Apologies for the massively unneat formatting. I am fairly new to Stack Overflow. -
TypeError at/xx 'method' object is not subscriptable Django
when i try to update i get TypeError,I'm having trouble updating even though I have successfully added and deleted. I'm getting an error even though it just worked, where could I have made a stupid mistake models.py; class problemduyuru(models.Model): olusturulmatarihi = models.DateTimeField(auto_now_add=True, null=True) duyurutipi = models.TextField(max_length=100, null=True) incidentno = models.TextField(max_length=100, null=True) baslangiczamani = models.TextField(max_length=100, null=True) aciklama = models.TextField(max_length=100, null=True) views.py; def problemduyurusuupdate(request, id): problemmember = problemduyuru.objects.get(id=id) problemmember.duyurutipi = request.POST.get['duyurutipi'] problemmember.incidentno = request.POST['incidentno'] problemmember.baslangiczamani = request.POST['baslangiczamani'] problemmember.aciklama = request.POST['aciklama'] problemmember.olusturulmatarihi = request.POST['olusturulmatarihi'] problemmember.save() messages.success(request, 'Alarmlar was updated successfully!') return redirect('/problemduyurusu') HTML; <form class="form-horizontal" action="problemduyurusuupdate/{{ problemmembers.id }}" method="POST"> {% csrf_token %} <div class="bd-callout bd-callout-danger"> <div class="bd-calloutic bd-callout-dangeric "> <div class="dangericon"></div> <h4 id="asynchronous-methods-and-transitions" style="color: #e70800;"><b>Technology Announcements</b></h4> <h7 id="asynchronous-methods-and-transitions" style="color:red; font-weight: 400; ">Problem Duyurusu</h7></div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Duyuru Tipi:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.duyurutipi }}" name="duyurutipi" id="duyurutipi" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Incident No:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.incidentno }}" name="incidentno" id="incidentno" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Başlangıç Zamanı:</span> </div> <input type="text" class="form-control" value="{{ problemmembers.baslangiczamani }}" name="baslangiczamani" id="baslangiczamani" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group mb-3" > <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;" … -
Making Django Function Work On HTML On Button Click
I'm trying to call a view so that it displays within a div on the page I already have existing rather than linking to a new page to post a comment. So far I've been able to bring up the div which shows after a button click and hides when pressed again. Ideally, when it shows the form for a comment should show yet at the moment it is only the submit button. I'm wondering how I could get this form to show up in this div as it does on the other HTML page. If there is any more required info let me know, just didn't want to give too much to look at. Views.py: class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'storysharing/comment.html' def form_valid(self, form): form.instance.story_id = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return reverse('storysharing:story_details', kwargs={'story_id':self.kwargs['pk']}) urls.py: app_name = 'storysharing' urlpatterns = [ path('', views.index, name = 'index'), path('<int:story_id>/', views.story_details, name = 'story_details'), path('add_story/', views.add_story, name = 'add_story'), path('thanks/', views.story_added, name = 'story_added'), path('final_post/<int:pk>', UpdateStoryView.as_view(), name = 'final_post'), path('review/', views.review, name = 'review'), path('get_location/', views.get_location, name = 'get_location'), path('<int:pk>/comment', AddCommentView.as_view(), name = 'comment'), ] page.html, the tag is where the link usually links to the other … -
Django. Как в шаблоне узнать наличие значения в QuerySet
Всем привет! Есть две связанные модели, вопрос и ответ от пользователя: models.py class TasksModel(models.Model): title = models.CharField('Заголовок задания', max_length=100) description = models.TextField('Описание') class UserAnswerTasks(models.Model): task_id = models.ForeignKey(TasksModel, verbose_name='id задания', on_delete=models.CASCADE) user_id = models.ForeignKey(ProjectUsers, verbose_name='id пользователя', on_delete=models.CASCADE) answer = models.TextField('Ответ на задание') Представление: views.py def index(request): user = request.user # берём пользователя tasks = TasksModel.objects.all() # Берём все вопросы all_answers = UserAnswerTasks.objects.filter(user_id=user) # Берём все ответы от этого пользователя content = { "tasks": tasks, "all_answers": all_answers } return render(request, 'tasksapp/index.html', content) Далее мне нужно в index.html вывести все вопросы из "tasks", и к ним же создать кнопку что если вопрос уже решён пользователем то "Кнопка 1" если пользователь ещё не решил этот вопрос то "Кнопка 2" index.html {% for i in tasks %} <h2"> <a href="{% url 'tasks:task' i.pk %}">{{ i.title }}</a> </h2> ???И ВОТ ТУТ КАК СДЕЛАТЬ ВЫДАЧУ??? {% if i.id in all_answer %} <a href="" class="btn">Посмотреть свой ответ</a> {% else %} <a href="" class="btn">Приступить к заданию</a> {% endif %} {% endfor %} Проходить снова циклом не хочется по all_answer, знаю что тип данных разный для оператора in, я знаю как решить задачу ещё одним циклом по all_answer. Но может есть способ сделать это при помощи if in, или какого … -
Django custom decorator for redirections
I'm deploying a multi-domain platform in Django, with some model logic for performing redirections between websites. As the redirection mapping is going to get slightly bulky I'd rather decorate each view as opposed to replicate the code for redirections in every view (I'm sticking to function-based views for this project). As the logic could possibly be changed too, I need to have it all in one place and I'd really like to use a custom decorator for that. I've been trying different syntaxes in order to define a decorator and I'm getting all sorts of problems. https://pythonbasics.org/decorators/ I'm using the syntax I see here but I couldn't apply it to Django views at first. I'm using Django 3.2. This is the thread that most resambles my situation and which helped me get closer to the result I want Django custom decorator redirect problem however my decorator view still returns None instead of an HttpResponse object and I don't understand. Decorator 1 def inner(request, *args, **kwargs): print("DEBUGGING") if settings.DEBUG == False or request.user.is_superuser == False: return render(request, 'myapp/manutenzione.html') func(request, *args, **kwargs) return inner Decorator 2 for my redirection def reindirizzamenti_necessari(func): def inner(request, *args, **kwargs): print("REINDIRIZZAMENTI") sito = get_current_site(request) dominio = sito.domain …