Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you avoid multiple bootstrap offcanvas overriding each other?
I am coding a website using django, and want to visualize django models in my html template. I run a for loop iterating the models, and creates a offcanvas button for each. When output the model title in the different offvanvas, they overwrite each other. I have two models with titles: 628671 and 801451, but no matter which offcanvas button i click, it the same. The format {{ data.title }} is correct and i used to showcase list of models succesfully with title as in picture_1(Models with titles). So there seem to be a problem with offcanvas overriding each time i render the button in my loop. HTML code: {% for data in emotion_data %} <-- this is in the html file, it is a django-tool. <div class="offcanvas-header"> <h5 class="offcanvas-title" id="offcanvasBottomLabel">{{ data.title}}</h5> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body large"> <div id="{{ data.title }}" class="chart" style="width: 100%; min-height: 500px;"></div> </div> </div> <td><a href="#">{{ data.title }}</a></td> <td> <button type="button" id="{{ data.title }}" class="btn btn-primary" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom" aria-controls="offcanvasBottomLabel"> Vis graf </button> </td> Picture_1:Models with title Picture_2: Offcanvas example -
Django + Javascript : Table columns build dynamically with JSON datas. Row structure broken
I retrieve on my (Django template) page 2 sets of data : 1: warehouses 2: items. With the first I wan't to create dynamically the TD's of my table after getting an Ajax search response from my view. I want to create all TD for all warehouses available in the warehouses JSON and if a product has a stock on this warehouse PK, in the same time, I populate the QTY tableBody.innerHTML += ` [...] <td>${item.fournisseur__nom}</td>`; JSON.parse(warehouses).forEach((wh) => { tableBody.innerHTML += ` <td> `; for (let i = 0; i < item.sststock.length; i++) { if (item.sststock[i].sst_id == wh.pk) { tableBody.innerHTML += item.sststock[i].qty; } }; tableBody.innerHTML += ` </td> `; }); tableBody.innerHTML += ` <td>${item.qty}</td> [...] Alas, here the result : Also new at JS, I don't understand why I need to json.PARSE twice my warehouse datas once at the top of my script, and another time in when I foreach Warehouses for building TD's. Otherwise, a warehouses.forEach is not a function error raises. JSON Warehouses : [{"model": "warehouses.warehouse", "pk": 1, "fields": {"code": "TRE"}}, {"model": "warehouses.warehouse", "pk": 2, "fields": {"code": "BAG"}}, {"model": "warehouses.warehouse", "pk": 3, "fields": {"code": "DROP"}}, {"model": "warehouses.warehouse", "pk": 4, "fields": {"code": "RN3"}}] I pass my warehouse data in … -
How to save IP address in django and check the saved value
I have to do an exercise: save IP address of admin and print an alert if this address change. I tried a lot of times, even with middleware but it doesn't work. #models.py from django.db import models from django.utils import timezone from django.conf import settings from django.contrib.auth.models import User from smapp.utils import sendTransaction from django.shortcuts import get_object_or_404 import hashlib def random_number(): return User.objects.make_random_password(length=10,allowed_chars='123456789') # Create your models here. class Lot(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=100) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) tracking_code=models.CharField(max_length=10,default=random_number) hash=models.CharField(max_length=64,default=None,blank=True) txId=models.CharField(max_length=66,default=None,blank=True) def writeOnChain(self): self.hash = hashlib.sha256(self.text.encode('utf-8')).hexdigest() self.txId = sendTransaction(self.hash) self.save() def publish(self): self.save() def __str__(self): if not self.hash: return str(self.writeOnChain()) else: return self.title class ip(models.Model): ip_address = models.GenericIPAddressField() And then my view: from django.shortcuts import render,HttpResponse from .models import Lot from .models import ip # Create your views here. def client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') get_ip= ip() get_ip.ip_address= ipaddress get_ip.save() return ipaddress def home_page(request): return render(request, 'smapp/home_page.html', {}) def lot_details(request): if request.method == "POST": searched = request.POST['searched'] tracks=Lot.objects.filter(tracking_code__contains=searched) return render(request, 'smapp/lot_details.html', {'searched': searched,'tracks':tracks}) else: return render(request, 'smapp/lot_details.html', {}) My question is: there is a way to do it? get_ip.save() where save my ip address and where i can check it? My problem is not to find … -
how to add print button that prints all the inserted records in django admin side?
[enter image description here][1] How Can I print all the inserted records by adding the print button? [1]: https://i.stack.imgur.com/yS1A0.png -
How to debug angular frontend with django server on vscode (Unverified Breakpoint)?
I'm running a django server for the backend of my application and angular for the frontend side. Basicaly to make my application work I start my django server: python manage.py runserver And on angular I use: ng build --output-path django_static_folder/ang --watch --output-hashing none I'm trying to debug angular code using vscode. I have an issue with "Unverified Breakpoint" on vscode. I checked many thread about this issue but none of them talked about how to debug when the server is not managed by angular using ng serve Here is my actual configuration: { "version": "0.1.0", "configurations": [ { "name": "Angular debug", "type": "firefox", "request": "launch", "url": "http://127.0.0.1:8000/", "webRoot": "${workspaceFolder}", } ] } The workspaceFolder is my angular workspace folder. The url is the one from django server. So when I start the debugger, the firefox app launch and I'm in my application but I cannot put any breakpoint. I believe that the issue is coming from the fact that I'm not using angular server. Maybe I should but then I don't know how to redirect to the correct url on the django server side ? Can anyone help me on this subject ? -
raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'generate_payroll' with no arguments not found
this is my views.py def qualified(request, employee_id): current_date = datetime.date.today() _history = PayrollModel.objects.all() for her in _history: if(her.employee_id_id == employee_id): # mnt = her if((current_date.month != her.month_year.month and current_date.month > her.month_year.month) and current_date.year == her.month_year.year): return messages.success(request, "HAPPY BD") else: return messages.success(request, "SAD BD") def generate_payroll(request, employee_id): qualification = qualified(request, employee_id=employee_id) current_date = datetime.date.today() if (qualification == True): overTimeValue = calculate_overtime(employee_id) allowanceValue = calculate_allowance(employee_id) bonusValue = calculate_bonus(employee_id) employee = EmployeeModel.objects.get(pk=employee_id) salary = PayGradeModel.objects.get(pk=employee.basic_salary_id) ssf = calculate_ssf(salary) netValue = (float(salary.amount) + float(overTimeValue) + float(bonusValue) + float(allowanceValue)) - float(ssf) # allowanceValue payroll = PayrollModel.objects.create(employee_id_id=employee_id) payroll.month_year = current_date payroll.basicSalary = salary.amount payroll.ssf_deduction = float(ssf) payroll.over_time = float(overTimeValue) payroll.bonus = float(bonusValue) payroll.allowance = allowanceValue payroll.gross_pay = salary.amount payroll.net_salary = float(netValue) payroll.save() messages.success(request, 'payroll generated successfully') return HttpResponseRedirect('/get_payroll') else: # payrolls = PayrollModel.objects.filter(employee_id_id=employee_id) return render(request, 'payrolls/get_payroll.html', {'payrolls': payroll} models.py class PayrollModel(models.Model): month_year = models.DateField(null=True) # month_year = MonthField( # "Month value", help_text="some help...", null=True) gross_pay = models.CharField(max_length=100, null=True) bonus = models.CharField(max_length=100, null=True) allowance = models.CharField(max_length=100, null=True) ssf_deduction = models.CharField(max_length=100, null=True) over_time = models.CharField(max_length=100, null=True) net_salary = models.CharField(max_length=100, null=True) employee_id = models.ForeignKey( EmployeeModel, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class Meta: db_table = 'payrolls' ordering = ['-updated', '-date_created'] urls.py path('employees/<int:pk>/payrolls/generate_payroll', views.generate_payroll, name='generate_payroll'), … -
How to manually create a cron job to run a Django script?
I have been trying to run some code as a cron job using Django. There are a number of packages that help do this, but they do not seem to support the latest Django version (4.0). Instead of continuing to search for packages, I was wondering if it is possible for me to simply write a python script within my Django folder structure, and manually configure a cron job to run this. Something like setting up: */30 * * * * python3.8 /var/djangoproject/crons/cron.py Is this possible? Is there any drawback or risk in doing it like this instead of using a package that is made for this? I don't see anyone recommending this so before implementing it I wanted to see if this is a good idea. -
After Changing Python Version 3.6 to 3.10 I got cannot import name 'Callable' from 'collections'
File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid_init_.py", line 5, in from .celery import app as celery_app File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid\celery.py", line 3, in from celery import Celery File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\five.py", line 306, in getattr module = import(self.object_origins[name], None, None, [name]) File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\app_init.py", line 14, in from celery import state File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery_state.py", line 20, in from celery.utils.threads import LocalStack File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\utils_init.py", line 20, in from collections import Callable ImportError: cannot import name 'Callable' from 'collections' (C:\Users\Codertjay\AppData\Local\Programs\Python\Python310\lib\collections_init_.py) -
Django Rest Framework -Serializer inside serializer using same instance
So, I have a weird legacy issue where I have one model "Data", and for serialization purposes I need to restructure the fields. class Data(models.Model): id ... field_a field_b field_c date Then I have the serializers: class DataInfoSerializer(ModelSerializer): class Meta: model = Data fields = ['field_a', 'field_b', 'field_c'] class DataSerializer(ModelSerializer): data_info = DataInfoSerializer(required=False, read_only=True) class Meta: model = Data fields = ['id', 'date', 'data_info'] Now I somehow have to get DRF to use the same instance of Data that is passed into the "DataSerializer" to render the DataInfoSerializer. Any ideas how to achieve this? Or a better way. -
Data view in html table from django views
I am trying to display data the tables from the database in some tables in an HTML template from django views. The problem is that the words are in a list and I want each word to be in each field in the table, How can I do that? views.py: if request.method == 'POST': context = {} tp = request.POST.get('tp') ms = request.POST.get('mode_selection') elif tp == "Download" or tp == "Preview": usr = User.objects.get(username=request.user) if ms=='2': data = WordDifferentTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'result') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'result'] elif ms=='3': data = LogicAnaloguiesTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'result', 'distance_to_word12') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'result', 'distance_to_word12'] elif ms=='4': data = SimilarWInContextTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'] else: data = WordsTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5',) hds = ['word1', 'word2', 'word3', 'word4', 'word5',] return render (request, "base.html",context) else: return render (request, "base.html") HTML table: {% if data %} <div style="padding-top: 30px" class="row"> <h3 align="center">Preview</h3> <table style="border: 1px solid #dddddd;"> <thead> <tr style="border: 1px solid;"> {% for h in hds %} <th style="border: 1px solid;">{{h}}</th> {% endfor %} </tr> </thead> <tbody style="border: 1px solid;"> {% … -
How to set up a project using Saleor with a default django frontend
I want to start a project where I build a webshop and I got interested in Saleor. I would like to use this with the "default" django frontend. I was wondering how to start setting up the project. I want to fork the project but want to be able to update from origin when possible. For my project I might need to change models to my liking. What had in mind is for example the product model that I create a seperate app within saleor and make my own models that inherits from the Saleor products. But i don't know if this is the best way to do this. And does anybody else have an idea or suggestion on how to start this? Thanks -
Django framework project name is not valid [closed]
'rgshop.' is not a valid project name. Please make sure the name is a valid identifier. -
django and javascript question show and hide edit form from list of selected queries
I have the following in my index <div id="posts"> {% for post in posts %} <div class="card"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'profile' post.user.username %}">{{post.user.username}}</a> wrote:</h5> {%if post.user_id == user.id %} <div class="cardn"> <a href="#" onclick="editpost()">Edit</a> <div class="card-body" id="card-body" style="display: none"> <form action="editpost/{{post.id}} " method="post"> {% csrf_token %} <div class="form-group"> <label for="post_text" class="h4">Edit Post</label><br> <textarea name="post_text">{{post.text}}</textarea> </div> <button type="submit" class="btn btn-primary btn-sm">Edit</button> </form> </div> </div> {%endif%} <p class="card-text" id="post_text_{{post.id}}"> {{ post.text }}</p> <p class="card-text"><small class="text-muted">on: {{post.post_date}}</small></p> <p class="card-text"> <div data-id="{{post.id}}" class="card-link {% if post.current_like > 0 %} fas {%else%} far {% endif %} fa-heart">&nbsp<small class="text-muted">{{post.like_set.count}}</small> </div> </p> </div> </div> {% empty %} <h2>No posts</h2> {% endfor %} what i would like to reach is to show only the edit form for the clicked edit button using javascript here is my view def editpost(request, id): post = Post.objects.get( id=id) if request.method == "POST": text = request.POST.get("post_text") Post.objects.filter( id=id, user_id=request.session['_auth_user_id']).update(text=text) return HttpResponseRedirect(reverse("index")) else: return render(request, "network/editpost.html", { 'post': post }) my JS thats not working document.addEventListener("click", editPost); function editPost(event){ // Listener sees triggering event const clickedThing = event.target; // Event has useful properties const userCard = clickedThing.closest(".cardn"); if(userCard){ // Makes sure button has a `card` ancestor before proceeding // Now, with … -
Authorization in react with django rest api backend
I was trying to make an app where users could come and make rooms and their friend could join the room. I am using Django rest_framework as the backend and react as the frontend. For create room, the logic I was trying to implement was that if the user has already made a room and somehow clicking on create room the old room would be returned instead of creating a new room (I was trying to store the session id which then Django uses to retrieve the room if available. The request is made by axios in app.js. But each time the user press Create Room the session id is getting refreshed thus creating a new room. This is the posting part in App.js createRoom = () => { axios.post('http://localhost:8000/api/createroom', { withCredentials: true, }) .then(res => { const data = res.data; console.log(data); }) .catch(err => { console.log(err); }) } Django view to handle post request class CreateRoomView(APIView): def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset.first() else: room = Room(host=host) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) My logic seems to work in postman but not in react. Can someone explain what I … -
SSH Tunnel to private RDS instance from django
I have a django application and a RDS instance in a private VPC. I would to connect to it from my local machine, using a ssh tunnel. I already have this configured and I have tried the connection from pg-admin so there should be no problem in that configuration. My problem now is how to make that ssh tunnel in django. I have tried this solution, but it looks like sshtunnel python package does not support openssh keys.. I have tried to generate a valid key with ssh-keygen -t rsa but it still contains an OPENSSH private key. I think that's because I'm generating the key from MacOs. So I generated from a Linux environment and added it correctly. Now, my configuration looks like this: from sshtunnel import SSHTunnelForwarder ssh_tunnel = SSHTunnelForwarder( '<ec2 host amazon>', ssh_private_key='~/ec2-db', ssh_private_key_password='', ssh_username='ubuntu', remote_bind_address=('localhost', 5432), ) print("Here") ssh_tunnel.start() print("THere") DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'HOST': '<rds amazon dns>', 'PORT': ssh_tunnel.local_bind_port, 'NAME': '***', 'USER': '***', 'PASSWORD': '***', }, } The server with that configuration can start, but I cannot access it on localhost:8000 so I suppose the db connection has been made successfully but now I cannot check it. Any idea what may be … -
Hosting more than one django project on Apache Vhosts
Am trying to host more than one django projects [USING WINDOWS] on apache using virtual hosts same ip address but different port eg. 91 and 92 respectively. Whenever I call port 91 return project A but when I call port 92 still return project A. Virtual Hosts configurations are per image below. Static contents are served by nginx -
Django Channels consumers.py scope['user'] returns anonymousUser
I'm trying to create one to one chat but when I'm trying to get self.scope['user'] it returns AnonymousUser consumers.py class ChatConsumer(SyncConsumer): def websocket_connect(self,event): #error me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) self.thread_obj = Thread.objects.get_or_create_personal_thread(me,other_user) self.room_name = f'{self.thread_obj.id}_service' print(f"{self.channel_name} connected") async_to_sync(self.channel_layer.group_add)(self.room_name,self.channel_name) self.send({ 'type':'websocket.accept' }) def websocket_receive(self,event): print(f"{self.channel_name} message received {event['text']}") msg = json.dumps({ 'text':event.get('text'), 'username':self.scope['user'].username }) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type':'websocket.message', 'text':msg } ) def websocket_message(self,event): print(f"{self.channel_name} message sent {event['text']}") self.send({ 'type':'websocket.send', 'text':event.get('text') }) def websocket_disconnect(self,event): print(f"{self.channel_name} disconnected") async_to_sync(self.channel_layer.group_discard)(self.room_name,self.channel_name) print(event) routing.py from channels.routing import ProtocolTypeRouter,URLRouter from django.urls import path from .consumers import ChatConsumer,EchoConsumer from channels.auth import AuthMiddlewareStack import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter([ path('ws/chat/',EchoConsumer()), path('ws/chat/<str:username>/',ChatConsumer()), ]) ) }) I think the problem is here in auth.py: @database_sync_to_async def get_user(scope): """ Return the user model instance associated with the given scope. If no user is retrieved, return an instance of `AnonymousUser`. """ # postpone model import to avoid ImproperlyConfigured error before Django # setup is complete. from django.contrib.auth.models import AnonymousUser if "session" not in scope: raise ValueError( "Cannot find session in scope. You should wrap your consumer in " "SessionMiddleware." ) session = scope["session"] user = None try: user_id = _get_user_session_key(session) … -
Django Form: How to create a new related object to a multiple select widget
I am quite sure I am missing something obvious at this point. Lets say I want to create a planed trainingssession which model looks like this: class PlannedTrainingSession(models.Model): created_by = models.ForeignKey(Member, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) aimed_date = models.DateField(null=True, blank=True) team = models.ForeignKey(Squad, null=True, blank=True, on_delete=models.CASCADE) run = models.ForeignKey(PlannedRun, null=True, blank=True, on_delete=models.CASCADE) and a run which model looks like this: class PlannedRun(models.Model): name = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=5000) distance = models.PositiveIntegerField(null=True, blank=True) effort = models.CharField(max_length=8, choices=[('low', _('low')), ('moderate', _('moderate')), ('intense', _('intense'))], blank=True) Now I basically want to recreate the functionality of the django admin interface, where I could create a PlannedTrainingSession with a form and select or add a related PlannedRun. So basically an add button next to the selection drop down which then opens a new form in a tab. How would I achieve that? -
How to select different ModelForms based on select value for DJANGO model form
I have a list of values. Within the list of values is a status which has a hyperlink to a particular model form. I want to dynamically change the hyperlink based on the select value to direct the user to different forms based on the select value. So, for example, when the Model value is pending, I want the hyperlink to go to the pending form. When the status is invoice sent and the use clicks the hyperlink I want the user to to go to the payment form. The code is below <table id="example1" class="table table-bordered table-striped" data-order='[[ 0, "desc" ]]' data-page-length='25'><button onClick="refreshPage()" class="btn btn-secondary float-right" title="Refresh"><i class="fa fa-sync"></i></button> <thead> <tr> <th>Script No.</th> <th>Entered on</th> <th>Script Type</th> <th>Patient</th> <th>Address</th> <th>Email</th> <th>Contact No</th> <th>Product</th> <th>Form</th> <th>Units</th> <th>Dispensing Price</th> <th>Status</th> <th>Dispatch Date</th> <th>Worksheet ID</th> <th></th> </tr> </thead> <tbody> {% for script in scripts %} <tr> <td>{{script.pk}}</td> <td>{{script.entered_on}}</td> <td>{{script.get_script_type_display}} <td>{{script.patient}}</td> <td>{{script.patient.address}}&nbsp;{{script.patient.city}}&nbsp;{{script.patient.AU_states}}&nbsp;{{script.patient.postal_code}}</td> <td>{{script.patient.email}}</td> <td>{{script.patient.mobile_number}}</td> <td>{{script.product}}</td> <td>{{script.product.form.description}}</td> <td>{{script.quantity}}</td> <td>$&nbsp;{{ script.dispensing_price }}</td> {% if script.dispatch_date is not none %} <td>{{script.get_script_status_display}}</td> {% else %} <td> <a class="edit" href="#" data-url="{% url "script:script_update_status" script.pk %}">{{script.get_script_status_display}}</a></td> {% endif %} {% if script.dispatch_date is none %} <td>Not Sent</td> {% else %} <td>{{script.dispatch_date}}</td> {% endif %} {% if script.document_id is none … -
When user registers to my app I have to collect: landing url and timestamp of landing url
Scenario: User clicks a link on some forum or ad and he lands on: myapp.com/?lg=1231231 ( or myapp.com/landing/bobby - we don't have these yet but I mean this should be global - not just on home route ) we have to store that landing page url and timestamp when he landed in session. User can then browse the site ( unregistered ) - and then he might decide to sign up - and we want that information stored. How can I accomplish this task? -
Django foreign key field read and write
I am using Django rest framework for a project. In the project, there is a Student model, which has a foreign key referring to a user object. class Student(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE ) When I read from Student, I would also like to get all the fields of the nested user. I can do that with nested serializers: class StudentSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Student fields = '__all__' However, if I want to create a new user I cannot use the same serializer, because there is no way to pass a foreign key to the user field, and Django does no support nested create. I am currently using an additional field user_id = serializers.IntegerField(write_only=True) to get the foreign key for write, and customized the create method to handle the logic. I also tried using two different serializers for creating and fetching data. Both way worked, but I am just wondering if there is a more intuitive way to implement this? A more convenient or standard way perhaps? Is there some syntax that works like: if read: user = UserSerializer() that avoids creating two different things for the same serializer field under different conditions? -
How to change url path to name in django instead of id
sorry if I ask very a simple question, I'm just starting to learn about WebDev and I have a question about django url and I used rest framework. I have http://localhost:8000/api/projectList/1 and I want to change id to the name in the url, for example http://localhost:8000/api/projectList/project This is the code: model.py class ProjectList(models.Model): project = models.CharField(max_length=200) project_name = models.CharField(max_length=200) category = models.CharField(max_length=200) academic = models.CharField(max_length=200) view.py class ProjectListSerializer(serializers.ModelSerializer): class Meta : model = ProjectList fields = '__all__' class ProjectListViewset(viewsets.ModelViewSet): queryset = ProjectList.objects.all() serializers_class = ProjectListSerializer class ProjectListListView(generics.ListAPIView): serializer_class = ProjectListSerializer def get_queryset(self): return ProjectList.objects.all() class ProjectId(generics.RetrieveUpdateDestroyAPIView): queryset = ProjectList.objects.all() serializer_class = ProjectListSerializer urls.py urlpatterns = [ path("", include(router.urls)), path("projectList/", ProjectListListView.as_view()), path("projectList/<int:pk>", ProjectId.as_view()), ] Thank you, sorry for my simple question and my bad English. -
How can I adjust the user search of Django Guardian?
I'm using the GuardedModelAdmin of Django Guardian to let the Admin set the permissions. I get this "User identification" field with the helptext "Enter a value compatible with User.USERNAME_FIELD": Instead, I would like to have the helptext "Enter the users email address". How can I get that? -
Need to return the object from the celery shared task queue process
I have faced the error "kombu.exceptions.EncodeError: Object of type 'JsonResponse' is not JSON serializable " In my settings.py : CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' So it only accepts response as a json value. But i need to return the object or instance Example : I need to return file path. Thanks in advance. @shared_task def celery_upload(path, id , user_id): upload = Upload() result = upload.file_generation_validation(path, id , user_id) excel = Excel() file_path = excel.Export(result["error"], "aaa") return file_path if I return result it will be successful, But file_path object throws error. -
Django orm left join return data like mysql
I have two table like this: class Classroom(models.Model): name = model.ChartField() class Student(models.Model): name = model.ChartField() classroom = model.ForeignKey(to='Classroom', related_name='students') there has some data like this: | Classroom | Student | | ----- | ------- | | Classroom_A | student_1, student_2, student_3 | | Classroom_B | (no Student) | Now I want to get the data by Django orm like this (return 4 rows data): | Classroom_name | student_name | | --- | --- | | Classroom_A | student_1 | | Classroom_A | student_2 | | Classroom_A | student_3 | | Classroom_B | null | How can I write the orm? The result is similar this (This is not what I want): data = [] for classroom in Classroom.objects.all(): students = classroom.students.all() if students: for student in students: classroom.student = student data.append(classroom) else: classroom.student = None data.append(classroom)