Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Did you have anyone use eZee Reservation api
Need to find out create booking and need all the information about parameters in the create a booking api [ { "Error Details": { "Error_Code": "ParametersMissing", "Error_Message": "Missing parameters." } } ] -
Django Import-Export is not processing List fields properly
I am using Django-import-export In one model I have ListTextField In exported csv file it is displayed correctly ['parameter1', 'parameter2'], however when I import it back it goes like this ''' ["['parameter1'", " 'parameter2']"] ''' I need help here ) -
How to convert raw sql to Django ORM?
I have been given sql query and I have to convert it to Django ORM and output should be the same. sql_query = "SELECT a.ID, a.post_title, a.post_name, a.post_date, d.meta_value, e.meta_value FROM wp_8_posts a, wp_8_term_relationships b, wp_8_term_relationships c, wp_8_postmeta d, wp_8_postmeta e WHERE a.post_type = :post_type AND a.post_status = 'publish' AND a.ID = b.object_id AND b.term_taxonomy_id = 1 AND a.ID = c.object_id AND c.term_taxonomy_id = :post_tag AND a.ID = d.post_id AND d.meta_key = 'upurl' AND a.ID = e.post_id AND e.meta_key = 'target' ORDER BY a.post_date DESC;" models.py class Wp_8Post(models.Model): ID = models.IntegerField(primary_key=True,null=False,default=None) post_author = models.IntegerField(null=False,default=0) post_date = models.DateTimeField(null=False) post_title = models.TextField(null=False,default=None) post_status = models.CharField(max_length=20,null=False,default='publish') post_name = models.CharField(max_length=200,null=False,blank=True) post_modified = models.DateTimeField(null=False) guid = models.CharField(max_length=255,null=False,blank=True) post_type = models.CharField(max_length=20,null=False,default='post') class Meta: app_label = 'cms' db_table = 'wp_8_posts' class Wp_8Postmeta(models.Model): meta_id = models.IntegerField(primary_key=True,null=False,default=None) post_id = models.ForeignKey(Wp_8Post,on_delete=models.CASCADE) meta_key = models.CharField(max_length=255,null=True,default=None) meta_value = models.TextField(null=True,default=None) class Meta: app_label = 'cms' db_table = 'wp_8_postmeta' class Wp_8Termrelationships(models.Model): object_id = models.ForeignKey(Wp_8Post,on_delete=models.CASCADE) term_taxonomy_id = models.IntegerField() term_order = models.IntegerField(null=False,default=0) class Meta: app_label = 'cms' db_table = 'wp_8_term_relationships' UniqueConstraint( name = 'term_relationship', fields = ['object_id','term_taxonomy_id'] ) First I thought to minimize the sql query by using INNER JOIN so I tried this but I got confused why same table is being used two times … -
Django forms how to initialze only not required field instead of passing all required fields
class Student(models.Model): name = models.CharField(null=True, blank=True) fieldA = models.TextField(null=True, blank=True) fieldB = models.TextField(null=True, blank=True) fieldC = models.TextField(null=True, blank=True) fieldD = models.TextField(null=True, blank=True) class Meta: model = Student fields = '__all__' Based on the above example all fields are taken in UpdateView or CreateView. If i need to take only required field i can change Meta to class Meta: model = Student fields = ['name','fieldA',fieldB','fieldC'] So my question is how can add only fields that should not pass in the Meta.From above example 'fieldD' is not passed. Is there is any way to say 'fieldD' is not required instead on passing all required fields in Meta.So that the code can be reduced. Above one is a small example. Consider I have 200 fields and only 1 field that I didnot want to pass so instead of passing 199 required fields in Meta is there is anyway to tell only the 1 field should not pass -
Not able view the data that I am trying to insert in CRUD
I am doing a CRUD of Products.I am struggling to view the data that I am trying to insert. below is the models,serializer(since I am suppsoed to use serializers instead of forms),functions and htmls class Products(models.Model): categories = models.CharField(max_length=15) sub_categories = models.CharField(max_length=15) color = models.CharField(max_length=15) size = models.CharField(max_length=15) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class POLLSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" def show(request): showall = Products.objects.all() print(showall) serializer = POLLSerializer(showall,many=True) print(serializer.data) return render(request,'polls/product_list.html',{"data":serializer.data}) def insert(request): if request.POST == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') form = POLLSerializer(data = insert_clothes) if form.is_valid(): form.save() # print('data',form.data) print(form.errors) messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print(form.errors) else: print('GET',id) insert_clothes = Products.objects.all() form = POLLSerializer(data = insert_clothes) if form.is_valid(): print(form.errrors) return render(request,'polls/product_insert.html') below is insert html code <form method="POST"> {% csrf_token %} <table> <thead> <tr> <td>Categories</td> <td> <select class="form-select" aria-label="Default select example" name="categories"> <option selected>Open this select menu</option> <option value="1">9-6 WEAR</option> <option value="2">DESI SWAG</option> <option value="3">FUSION WEAR</option> <option value="">BRIDAL WEAR</option> </select> </td> </tr> <tr> <td>Sub-Categories</td> <td> <input type="text" name="sub_categories" placeholder="SUB_CATEGORIES"> </td> </tr> <tr> … -
aws Beanstalk eb deploy relative path makemigrations ERROR Failed to deploy application
I keep getting an 2022-07-08 03:11:06 ERROR Instance deployment failed. For details, see 'eb-engine.log'. and ERROR: ServiceError - Failed to deploy application. when trying to run eb deploy when deploying a Django application to Elastic Beanstalk on aws. It is failing on Command 01_makemigrations it seams.. But here is the thing that is making me go crazy; the models.py works fine in http://127.0.0.1:8000/ (locally) with this one line: image = models.ImageField(upload_to=os.path.join(BASE_DIR, 'static'), null=True, blank=True). I noticed that is the line of code in the model, is causing an issue when deploying to production. I commented it out and it deployed fine but I need that method obviously.. Is this something with a Linux vs. Windows path issue?.. I am developing locally in Windows 10. 👽 django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: the_slim_fatty.wsgi:application container_commands: 01_makemigrations: command: "source /var/app/venv/*/bin/activate && python3 manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true 03_superuser: command: "source /var/app/venv/*/bin/activate && python3 manage.py createsu" leader_only: true eb-engine.log 2022/07/08 03:11:06.780830 [INFO] Error occurred during build: Command 01_makemigrations failed 2022/07/08 03:11:06.780855 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: container commands build failed. Please refer to /var/log/cfn-init.log … -
How to use Django without database
I'm creating an app with a React frontend. The purpose of the backend is to call a public API, process the data retrieved from the public API, and then with a REST API transfer the post-processed data to the view (React frontend). I would like to use python in the backend, so I started with using Django. However, it seems Django is very much focused on Models and Databases. I do not need a database for this app. Is Django the right tool to use for this? -
I am using celery and setup celery command in supervisor and facing this issues in my django project
supervisor: couldn't exec /home/tspl/python_project/venv/bin/celery: ENOENT supervisor: child process was not spawned -
Django user with main password and multiple passwords
I have one different type login idea, One single User have multiple Accounts (ManyToMany or Foreign Key). Now my logic is, if User login with main user password. access the all Accounts related details. But if User login with Accounts based password, access that one Account related details only. -
Django: Nested Sum() annotations across three Model Relations
I am using Django to sort out a storefront environment to handle orders and am struggling on one of the annotations I am attempting to write. The salient data models are as such class Order(ClusterableModel): "various model fields about the status, owner, etc of the order" class OrderLine(Model): order = ParentalKey("Order") product = ForeignKey("Product") quantity = PositiveIntegerField(default=1) base_price = DecimalField(max_digits=10, decimal_places=2) class OrderLineOptionValue(Model): order_line = ForeignKey("OrderLine", related_name="option_values") option = ForeignKey("ProductOption") value = TextField(blank=True, null=True) price_adjustment = DecimalField(max_digits=10, decimal_places=2, default=0) The OrderLine represents one or more of a specific product being bought at a specific base price and quantity. This base price has been copied from the product model in order to preserve the price of the product at the time the order was created. The Order therefore is just a collection of multiple OrderLines The complexity comes in the OrderLineOptionValue model which represents a modification to the base price based on the choices made by the user, and each order line may have multiple adjustments if the product has multiple options. Color, size, weight, etc may each have variable price impacts. When querying the OrderLine model I have been able to successfully annotate each result with that line's appropriate line … -
MAC M1 Chip Python Architecture Error (have 'x86_64', need 'arm64e')
I am having trouble running django on my M1 Mac. When ever i try to run server or make migrations i get an (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e') error. My terminal is being open with Rosetta and I am using VSCode ide. -
Unable to get results when searching in django using postgresql
I am unable to retrieve any search results when searching for items. I am using Postgresql and Django. Below is my code. I have the search bar in "inventory_management.html". I am trying to get it to where the user searches for an item, and then a list of the displayed items are shown. Any help would be greatly appreciated! models.py class Inventory(models.Model): product = models.CharField(max_length=50) description = models.CharField(max_length=250) paid = models.DecimalField(null=True, max_digits=5, decimal_places=2) bin = models.CharField(max_length=4) listdate = models.DateField(null=True, blank=True) listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) solddate = models.DateField(null=True, blank=True) soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) shipdate = models.DateField(null=True, blank=True) shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.product + "\n" + self.description + "\n" + self.paid + self.bin + "\n" + self.listdate + "\n" + self.listprice + "\n" + self.solddate + "\n" + self.soldprice + "\n" + self.shipdate + "\n" + self.shipcost views.py @login_required(login_url="/login") def search(request): q = request.GET.get('q') if q: vector = SearchVector('product', 'description') query = SearchQuery(q) searchinv = Inventory.objects.annotate(search=vector).filter(search=query) else: searchinv = None return render(request, 'portal/search.html', {"searchinv": searchinv}) inventory_management.html (where the search bar is located) {% extends 'portal/base.html' %} {% block title %}{% endblock %} {% block content %} <br> … -
Django: nested forloop not rendering
I have a "Homeworks" model, and I have a "Grades" model, and I'm trying to add a grade and show it in each homework. Everything is working great but apparently I cant save or even make the grades_form show inside a loop in a loop. Models.py class Hw_upload(models.Model): title = models.CharField(blank=True, max_length=255, null=True) description = models.TextField(blank=True, max_length=255, null=True) document = models.FileField(blank=True, upload_to='documents/', null=True) creation_date = models.DateTimeField(default=timezone.now) hw_author = models.ForeignKey(User, on_delete=models.PROTECT, related_name="hw_author") activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="hw_uploads", null=True) class Grades(models.Model): grade = models.PositiveIntegerField(validators=[MaxValueValidator(100)], blank=True, null=True) hw_upload = models.ForeignKey(Hw_upload, on_delete=models.CASCADE, related_name="hw_grades", null=True) Forms.py class Hw_gradeForm(ModelForm): class Meta: model = Grades fields = ['grade'] widgets = { 'grade': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0-100'}) } Views.py def activity(request, id): if not request.user.is_authenticated: return render(request, "auctions/login.html") activity = Activity.objects.get(id=id) try: hw_upload = Hw_upload.objects.get(id=id) except Hw_upload.DoesNotExist: hw_upload = None try: grades = Grades.objects.get(id=id) except Grades.DoesNotExist: grades = None if request.method == 'POST': form = Hw_uploadForm(request.POST, request.FILES or None) if form.is_valid(): upload_hw = form.save(commit=False) upload_hw.hw_author = request.user upload_hw.activity = Activity.objects.get(id=id) upload_hw.save() if request.method == 'POST': grade_form = Hw_gradeForm(request.POST, request.FILES or None) if grade_form.is_valid(): grade_hw = grade_form.save(commit=False) grade_hw.hw_upload = Hw_upload.objects.get(id=id) grade_hw.save() url = reverse('activity', kwargs={'id': id}) return HttpResponseRedirect(url) return render(request, "auctions/activity.html", { "activity": activity, 'hw_upload': hw_upload, 'grades': grades, 'grade_form': … -
Django Form is not submitting, even though it seems to be working
My form is still not submitting. I am stressed out now, I am rebuilding my app from the ground up because a form wasn't working (in total I have three, the other two did work), and it still isn't working. I did use the same model, so maybe it has something to do with it. That or it has something to do with two fields, the ones that are foreign keys of the other two forms. Anyway here is my code if you could check it out: #models.py class Contratos(models.Model): name=models.CharField(max_length=30) contractor=models.ForeignKey(Vendors, on_delete=models.CASCADE) contractee=models.CharField(max_length=30) start=models.DateField() end=models.DateField() cost=models.DecimalField(max_digits=9, decimal_places=2) blank='' Pesos= 'PE' Dolares='DL' CURR_CHOICES= [ (blank, '----'), (Pesos, 'MXN'), (Dolares, 'DLLS'), ] currency=models.CharField( max_length=2, choices=CURR_CHOICES, default=None, ) def is_upperclass(self): return self.currency in {self.Pesos, self.Dolares} Producto12='PR' Servicio= 'SE' Poliza='PO' Lic='LC' Otro='OT' TIPO_CHOICES= [ (blank, '----'), (Producto12, 'Product'), (Servicio, 'Service'), (Poliza, 'Policy'), (Lic, 'Licensing'), (Otro, 'Other'), ] type=models.CharField( max_length=2, choices=TIPO_CHOICES, default=None, ) def is_upperclass(self): return self.type in {self.Servicio, self.Otro} IT='IT' Fin='FN' Rec='RH' Man='MT' Cua='CR' depc_CHOICES= [ (IT, 'IT'), (blank, '----'), (Fin, 'Finance'), (Rec, 'Human Resources'), (Man, 'Maintenance'), (Cua, 'Rooms'), ] department=models.CharField( max_length=2, choices=depc_CHOICES, default=NONE, ) def is_upperclass1(self): return self.department in {self.IT, self.Cua} description =models.TextField() product=models.ForeignKey(assets, on_delete=models.CASCADE) attached_file=models.FileField(blank=True) notification=models.BooleanField(default=False) #forms.py class ContractsForm(forms.ModelForm): class Meta: … -
How to return a value from another model. Django Rest Framework
When I query all the comments of the post, I want to return the user's username. My two Models: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey( Post, on_delete=models.CASCADE, null=False, blank=False) title = models.TextField() date = models.DateField(auto_now=True) class User(AbstractUser): objects = UserManager() username = models.CharField(max_length=60, unique=True) avi_pic = models.ImageField( _('avi_pic'), upload_to=aviFile, null=True, blank=True) My Comments Serializer: class CommentSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField('get_username_from_user') avi_pic = serializers.SerializerMethodField('get_avi_pic') class Meta: model = Comment fields = '__all__' def get_username_from_user(self, comment): username = comment.user.username return username def get_avi_pic(self, comment): request = self.context['request'] avi_pic = comment.user.avi_pic.url return request.build_absolute_uri(avi_pic) My Comments View: class CommentView(APIView): authentication_class = [authentication.TokenAuthentication] permission_class = [permissions.IsAuthenticated] serializer_class = CommentSerializer # Get all comments from current post def get(self, request): post_id = request.data.get('id') post = Post.objects.get(id=post_id) comment = Comment.objects.filter(post=post).values() serializer = CommentSerializer(comment) return Response(serializer.data, status=status.HTTP_200_OK) In my console I get: 'QuerySet' object has no attribute 'user' Appreciate any help!! -
PayPal API Cross Site Request Cookie Issue (Django, JavaScript Issue)
I'm creating a site for my senior project and have run into some trouble creating a payment portal for my site. The site was working correctly the other night, and without making any changes, the buttons now fail to render and I am being spammed with errors regarding indicating a cookie in a cross site address. Attached is the checkout.html file which the PayPal js is included within, along with the error codes I am receiving from the console. Any help would be much appreciated! {% extends 'main.html' %} {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/checkout.css' %}"> </head> <body> {% block content %} <div class="row"> <div class="col-sm-6 mt-4 mb-4"> <div class="box-element" id="form-wrapper"> <h2>Recipient Information</h2> <form id="form"> <div id="recipient-info"> <div class="form-field"> <input required class="form-control" type="text" name="recipient_first_name" placeholder="Recipient First Name.."> </div> <div class="form-field"> <input required class="form-control" type="text" name="recipient_last_name" placeholder="Recipient Last Name.."> </div> <br> <div class="form-field"> <input required class="form-control" type="email" name="recipient_email" placeholder="Recipient Email.."> </div> <div class="row ml-auto"> <label class = "mt-1" for="pickup_location">Select a pickup location: </label> <select class="mt-2 ml-2" name="pickup_location" size="4" multiple> <option value="nabatieh">Nabatieh</option> <option value="tyre">Tyre</option> <option value="saida">Saida</option> <option value="beirut">Beirut</option> </select><br><br> </div> </div> <hr> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue"> </form> </div> <br> <div class="box-element hidden" … -
leaflet does not display the map in my django application
I am developing an application with django. In a page of this application I want to display a map with leaflet. I try to display a basic map according to the information I could have on the leaflet site but nothing is displayed. There is not even an error message in the console. templatefile.html: {% extends 'elec_meter/base.html' %} {% load static %} {% block title %}Geolocalisation des compteurs - Interactiv {% endblock %} {% block titre %} Carte {% endblock %} {% block css %} <link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js" integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" crossorigin=""> </script> <script src="{% static 'assets/js/main.js' %}"></script> <style> <link href="{% static 'assets/css/style.css' %}" rel="stylesheet" /> </style> {% endblock %} {% block add %}{% endblock %} {% block content %} <div class="row" onload="init"> <div id="mapid" style="height:450;"> </div> </div> {% endblock %} Here is the content of my js file which initializes the map: main.js function init(){ const coordGabon = { lat: -0.803689, lng: 11.609444 } const zoomLevel = 13; const mymap = L.map('mapid').setView([coordGabon.lat, coordGabon.lng],zoomLevel); const mainLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19,attribution: '© OpenStreetMap'}).addTo(mymap); } -
how to write DRF serializers for the desired output?
need to get the following output using the below given model structure { "User": [ { "id": 1, "name": "XYZ", "Task": [ { "id": "1", "task_name": "task 1" }, { "id": "2", "task_name": "task 2" } ] }, { "id": 2, "name": "ABC", "Task": [ { "id": "1", "task_name": "task 1" } ] } ] } This is how the model is designed and I want the above output without dealing with extra database query for each record (n+1). Can this be achieved using select_related or prefetch related or something else? class User(models.Model): name = models.Charfield() class Task(models.Model) task_name = models.Charfield() class UserTask(models.Model): user = models.Foreignkey(User, related_name = 'user') task = models.Foreignkey(Task, related_name = 'tasks') -
How to get dynamically created glb from django backend to display in three.js
I have an application that takes user input and creates a 3D model from that input in a python script. I now want to visualize this 3D object using three.js. My problem is that I cannot seem to get the data from the backend to the three.js GLTFLoader in the correct format. The glb data is generated with trimesh. I am certain the 3D model is created correctly because I can output it to a file and open it in Blender. The loading of static resources in the glb format through three.js also works. But since the content is dynamically created, I do not want to save it on the server-side unless the user decides to keep it. My current approach is to try and include the 3D model in the content of a template view. The three.js documentation says, glb data can be parsed from a js BufferArray. But it seems the data gets read as a binary string in js: "b'......'" The views.py: class PreviewView(TemplateView): template_name = 'editor/preview.html' context_object_name = 'preview_generated' def get_preview(self, request): from editor.tools.gltf import GLTFConverter raw_lines = json.loads(request.POST.get('vertex_sets')) if type(raw_lines[0]) is list: lines = [np.pad(np.array(line).reshape((-1,2)),[(0,0),(0,1)], mode='constant') for line in raw_lines] else: lines = [np.pad(np.array(raw_lines).reshape((-1,2)),[(0,0),(0,1)], mode='constant')] … -
Django super user keeps getting deleted when I create a new user either from admin or register page
As mentioned above, every time I create a super user using python manage.py createsuperuser, everything works fine and I am able to log in and view the admin page as usual. However, the moment I register another user, the superuser gets deleted and can longer 1.view the login page 2. view the admin page. If I use the shell and query my users, I only have the user that was registered. Somehow the superuser gets deleted? models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractUser, PermissionsMixin, BaseUserManager, AbstractBaseUser from .utils import generate_patient_id_for_user import uuid from rest_framework import serializers class PatientData(models.Model): id = models.AutoField(primary_key=True) heart_rate = models.IntegerField(default=0) sp02 = models.IntegerField(default=0) temp = models.DecimalField(decimal_places=2,max_digits=4, default=0) recorded_time = models.DateTimeField(auto_now=False) patient_rec = models.ForeignKey(to='CustomUser',on_delete= models.SET_NULL,null=True,blank=True) class CustomUserManager(BaseUserManager): def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) elif not username: raise ValueError(_('You must provide a user name')) elif not first_name: raise ValueError(_('You must provide a first name')) elif not other_fields.get('dob'): raise ValueError(_('You must provide a date of birth')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) other_fields.setdefault('is_active', True) other_fields.setdefault('patient_id', generate_patient_id_for_user()) user.set_password(password) user.save() return user def create_superuser(self, email, username, first_name, password, **other_fields): … -
Django view to combine parent and child table data
I've two Django models with a foreign key relationship: class Parent(models.Model): id = models.IntegerField() parent_name = models.CharField() class Child(models.Model) id = models.IntegerField() child_name = models.CharField() parent = models.ForeignKey(Parent, related_name='parent', on_delete=models.CASCADE) Both tables are high volume so looking for something very efficient. What's the best way to write an efficient django view to return json as: Expected JSON: [ { "id": 1, "parent_name": "Elon", "childs": [ { "id": 101, "child_name": "Elon son" }, { "id": 101, "child_name": "Elon daughter" } ] }, { "id": 2, "parent_name": "Jeff", "childs": [ { "id": 101, "child_name": "Jeff son" }, { "id": 101, "child_name": "Jeff daughter" } ] } ] -
send checkout details of the orders each to anyone press checkout button to clients whatsapp api using django
enter image description hereenter image description here how to implement a function like this to send checkout details of the orders each to anyone press checkout button to clients Whatsapp api using django def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request): form_value = OrderForm() if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method == 'POST':***emphasized text*** order.delete() return redirect('/') context={'item':order} return render (request, 'accounts/delete.html', context) def SendOrder(request ,order, sent_to_admin, plain_text, email) : if (email.id == 'customer_completed_order' or email.id == 'new_order') : link = str(str('https://wa.me/' + str(order.get_billing_phone('edit'))) + '/?text=') + urlencode('your text messages') print(str(str(str(str(str('<div style="margin-bottom: 40px;"> <h2>' + str(__('Customer WhatsApp link', 'text-domain'))) + '</h2> <p><a href="') + str(link)) + '" target="_blank">') + str(__('Contact', 'text-domain'))) + '</a></p> </div>',end=""); -
TLS with MQTT ASGI?
I want to use the MQTT ASGI Protocol Server for Django (https://pypi.org/project/mqttasgi/) but need a TLS connection for my MQTT client (I use HiveMQ as a broker). When I use port 8883 to start the server, it 'reconnects' inifinitely. Is there some way to configure TLS? Thanks in advance -
Django if check always goes into else
I'm trying to use if inside the for loop in Django, but it keeps getting into the else part. What causes this problem? yazilar.html {% for yazi in yazilar %} {{ yazi.tur }} # output : 2 {% if yazi.tur == 1 %} standart format {% elif yazi.tur == 2 %} quote format {% elif yazi.tur == 3 %} link format {% else %} nothing {% endif %} {% endfor %} -
Ajax and Django Like button
I made a like button with Ajax and it works, but only when I click on the 1st post, the like_count counter updates the instant value. The like_count value does not change after clicking the button for the 2nd and subsequent posts. ** When I click on the like button of the second and subsequent posts, I see a change in the like_count value of the first post. When I refresh the page, I see that the value of the 2nd and subsequent posts has changed.** My problem is that I want the like count value to change instantly for the 2nd and subsequent posts. could this be the problem (id="like_count") myviews.py @login_required(login_url="login") def like(request): if request.POST.get('action') == 'post': result = '' id = request.POST.get('postid') post = get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) mybutton.html {% if request.user.is_authenticated %} {% if post.like_count >= 2 %} <button style="margin-top: 10px;" class="btn btn-light like_button_true like-button" value="{{ post_item.id }}"> <img style="width: 32px; height:32px;" src="{% static 'img/likeTrue.png' %}" /> <br> <span id="like_count">{{post_item.like_count}}</span> </button> {% else %} <button style="margin-top: 10px;" class="btn btn-light like_button_detail like-button" value="{{ post_item.id }}"> <img …