Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to fetch data with axios from Django backend using relative path
I am currently developing a web application using React for my frontend and Django for my backend. The frontend and backend are running on separate local servers. I am trying to fetch some data from my Django backend using axios in my React application with the following code: const handleButtonClick = () => { setLoading(true); axios .get("/bucket-size/") .then((response) => { const size = response.data.bucketsize; const unit = response.data.unit; setOutput(size + " " + unit); }) .catch((error) => { console.error(error); }) .finally(() => { setLoading(false); }); }; The Django backend route looks like this: path('bucket-size/', BucketSize.as_view(), name='bucket-size'), Note -- i do not want to add a proxy to my package.json since the backend will be running on Docker and i want it to fetch relatively. Can anyone help? -
Generate IFCRoad via IFCOpenShell
I have this model class Tramif_PCI_agrup(models.Model): id = models.AutoField(primary_key=True) pci = models.FloatField(null=True) geom = models.LineStringField(geography=True, srid=4326, null=True) That i want to translate into an IFCRoad using the IFCOpenShell library to get a final IFC file with every Object with its geom and its PCI value. This is what i tried but it didnt work # Get all objects from the Tramif_PCI_agrup model tramif_pci_agrups = Tramif_PCI_agrup.objects.all() # Create a blank model ifc_file = ifcopenshell.file(schema='IFC4X3') # Create an IfcRoad entity road = ifc_file.create_entity("IfcRoad") road.Name = "Simple Road" # Fetch objects from the model and iterate over them for tramif_object in tramif_pci_agrups: # Extract geometry and PCI values from the model object geom = tramif_object.geom pci = tramif_object.pci # Convert the geometry to WKT format wkt_geom = geom.wkt # Create an IfcAlignment entity for each object alignment = ifc_file.create_entity("IfcAlignment") alignment.Name = f"Alignment {tramif_object.id}" alignment.Description = f"PCI: {pci}" # Create an IfcAlignmentCurve entity for the geometry curve = ifc_file.create_entity("IfcAlignmentCurve") curve.Axis = ifc_file.create_entity("IfcCurve") curve.Axis.Points = ifc_file.create_entity("IfcPointList") curve.Axis.Points.Coordinates = [(coord[0], coord[1], 0) for coord in GEOSGeometry(wkt_geom)] # Add the alignment curve to the alignment entity alignment.Representation = curve # Add the alignment entity to the road road.Representation = alignment # Write the IFC file ifc_file.write("/images/road_test.ifc") But … -
How to set env variables for django test in vscode
I would like to set env variable for django test in vscode. These env variables will be different from env variables to be used in django run server. -
TinyMCE is not working correctly in my django project
I have created a Django blog site where I can write blog posts both from the main site and the admin site. To compose my blog posts, I am using the TinyMCE editor. When I am in the admin site, I can successfully write and submit my blog posts using TinyMCE. However, when I attempt to write a blog post from the main site using TinyMCE, I encounter an issue. Although my submit button appears to be working correctly, it does not perform any action upon clicking it. Strangely, if I refresh the page and then click the submit button again, my blog post gets posted, and everything works fine from that point onward. Please tell me What is the mistake that I'm doing. This is my tiny.js file var script= document.createElement('script'); script.type='text/javascript'; script.src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload=function(){ tinymce.init({ selector: "#id_content", height:656, plugins: [ 'advlist autolink link image lists charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', 'table emoticons template paste help' ], toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | link image | print preview media fullpage | ' + 'forecolor … -
Gunicorn Fargate ELB healthcecks fail before auto scale
I have setup a django application using gunicorn server on ECS with Fargate backend. I have setup auto scaling based on both CPU and Memory utilisation. Fargate capacity: 2 vCPU and 4 GB RAM The problem is that whenever the load is high, even before the CPU utilisation is high, the ELB healthchecks are failing and as a result the task is getting deregistered and never leads to auto scaling. gunicorn is running with 2 workers and 4 threads. gunicorn <appname>.wsgi:application --workers 2 --threads 4 I'm trying to understand the reason for this and how to solve this issue. -
why for loop not working in django .Error in rendering html in django using for loop
i am writing code to get a carousal which consists of products using for loop in python But there is some isuue it is generating everthing but not generating my items inside carousal Things defined here: list_of_range=[[0, 1, 2], [3, 4]] Now my no of slides in carousal is generated pretty well but items in side each slide is not get generated Here's the code in index.html <div class="container mt-5" > <div id="carouselContainer" class="carousel slide" data-ride="carousel"> <div class="carousel-inner justify-content-center"> {% for i in list_of_range %} {% if i == list_of_range.0 %} <div class="carousel-item active"> {% else %} <div class="carousel-item "> {% endif %} <div class="row"> {% for d in list_of_range.i %} <div class="col-sm-3 col-md-3"> <div class="card" style="width: 18rem"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyRql003EXAw9EVs6V3koKd5wXbW0Lt-yJOA&usqp=CAU" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">{{products.0.product_name}}</h5> <p class="card-text"> Some quick example text to build on the card title and make up the bulk of the card's content. </p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> </div> {% endfor %} and the code in main.py is as follows : def index(request): all_products_list = Product.objects.all() n= len(all_products_list) nslides = n//3+ ceil((n/3)-n//3) print(nslides) prod_range_list = [] to_range = n for c in range(nslides): if to_range/3>=1: prod_range_list.append(list(range(c * … -
how do you associate a user with a payment when using mpesa express on python django
the response body on the call back is usually: { "Body": { "stkCallback": { "MerchantRequestID": "21605-295434-4", "CheckoutRequestID": "ws_CO_04112017184930742", "ResultCode": 0, "ResultDesc": "The service request is processed successfully.", "CallbackMetadata": { "Item": [ { "Name": "Amount", "Value": 500 }, { "Name": "MpesaReceiptNumber", "Value": "WHAkLK451H35OP" }, { "Name": "Balance" }, { "Name": "TransactionDate", "Value": 20171104184944 }, { "Name": "PhoneNumber", "Value": 254710549039 } ] } } } } This is my callback url, which works fine and saves the data in a model. How can you associate a user with a payment once the response is received and saved in a general model not associated with any user: @csrf_exempt def callbackurl(request): if request.method == 'POST': m_body =request.body.decode('utf-8') mpesa_payment = json.loads(m_body) payment = StatusPayment( phoneno=mpesa_payment['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value'], transcode=mpesa_payment['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value'], ) payment.save() context = { "ResultCode": 0, "ResultDesc": "Accepted" } return JsonResponse(dict(context))` -
Is it possible in Django to use threaded=True (like in Flask) to e to handle each request in a new thread?
On Flask you can use threaded=True to handle each request in a new thread. For example: if __name__=="__main__": app.run(host="0.0.0.0", port=8000, threaded=True) With Django can i use something like threaded=True (or simil) to handle each request in a new thread? (without using async). Or is it more complicated in Django? -
Reverse for 'task_complete' with arguments '('',)' not found. 1 pattern(s) tried: ['tasks/(?P<task_id>[0-9]+)/complete\\Z']
estoy haciendo una todo app con Django y estoy queriendo hacer el update/delete de las tareas pero me salta el error del titulo, dejo las partes del código que, entiendo, son de interés: El HTML completa la tarea: <form action="{% url 'task_complete' task.id %}" method="POST"> {% csrf_token %} <button> Complete </button> </form> La lista de patterns: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('singup/', views.singup, name="singup"), path('tasks/', views.tasks, name="tasks"), path('tasks/create/', views.create_task, name="create_task"), path('tasks/<int:task_id>/', views.task_detail, name="task_detail"), path('tasks/<int:task_id>/complete/', views.task_complete, name="task_complete"), path('logout/', views.singout, name="logout"), path('singin/', views.singin, name="singin"), ] La función que debería completarlas: def task_complete(request, task_id): task = get_object_or_404(Task, pk=task_id, user=request.user) if request.method == "POST": task.date_completed = timezone.now() task.save() return redirect('tasks') Esperaba que complete la tarea y deje de aparecer en tareas, pero tira el error Reverse for 'task_complete' with arguments '('',)' not found. 1 pattern(s) tried: ['tasks/(?P<task_id>[0-9]+)/complete\Z'] -
how to set log level for a specific url path in django?
my view is below @api_view(['GET']) def get_test(request): return HttpResponse('Ok', status.HTTP_200_OK) and my path in urls.py in urlpatterns is as below. path('api/test', views.get_test), This path is called a lot as part of the liveness probe in kubernetes and i want the log level just for this url to be set to CRITICAL so that it would not be logged or ideally i want to disable django logging altogether for this particular url and right now it is set to DEBUG by default. How do i go about changing the log level or disable the log? -
Error during template rendering in DjangoCMS plugin from {% translate 'Clear' %} [closed]
I’m trying to create a custom CMS Plugin and when i click to create the plugin this error happens: Error during template rendering from {% translate 'Clear' %} How can i solve this? In the past it was working. I don’t what happens. Thank you! I tryed to access the template "/usr/local/lib/python3.8/site-packages/filer/templates/admin/filer/widgets/admin_file.html" but i couldn't because it was build by docker. -
Power BI Embedded for customers - Creating embeded URL
I'm embedding a Power BI report on a "Embed for customer" manner and authenticating via service account. I have managed to get the embed token for a single report and a single workspace using Microsoft guides. The issue comes when making a POST request to https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}. I get a 403 error. Also, note that I am using Django and the final purpose is to process everything on the backend and just send a URL to the front end to put inside an iframe. This is my Django View: from django.shortcuts import render from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.views import View from django.shortcuts import get_object_or_404 from .models import Dashboard, ReportConfig, EmbedConfig, EmbedTokenRequestBody from .serializer import DashboardSerializer from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from powerbi.aadservice import AadService import requests import json class DashboardView(viewsets.ModelViewSet): serializer_class = DashboardSerializer permission_classes = [IsAuthenticated] def get_queryset(self): # Retrieve the user's groups user = self.request.user user_groups = user.groups.all() # Filter the dashboards based on group membership queryset = Dashboard.objects.filter(group__in=user_groups) return queryset class PbiEmbedService(View): def get(self, request, workspace_id, report_id, additional_dataset_id=None): '''Get embed params for a report and a workspace''' report_url = f'https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports/{report_id}' api_response = requests.get(report_url, headers=self.get_request_header()) if api_response.status_code != … -
Django-MPTT using Parent and Child in same form
My goal is straightforward: I want to enable the selection of a parent category first and then choose its corresponding child categories. Unfortunately, I am encountering difficulties in implementing this functionality. My code is <form> <div class="mb-3"> <label for="main-category" class="form-label">Ana Kategori</label> <select class="form-select" id="main-category" name="main_category"> <option value="">Seçin</option> {% recursetree categories %} <option value="{{ node.id }}">{{ node.name }}</option> <div class="mb-3"> <label for="sub-category" class="form-label"></label> {% if not node.is_leaf_node %} <select class="form-select" id="children" name="children"> <option value="{{ node.id }}">{{ children }}</option> {% endif %} {% endrecursetree %} </select> </div> </div> <button type="submit" class="btn btn-primary">Gönder</button> </form> current result: -
Django - How to display search term on results page?
I’ve made a successful form and it’s working accordingly displaying the search results when a user makes a form submission. However, I’m stuck with one new addition to this search functionality. How do I get to display the search term with my current code? I’m trying to display the current search term in search_results.html but can’t get the term to display work. The only thing that appears is a blank space. I'm guessing I'm doing something wrong in views.py but don't know what exactly. Any help is gladly appreciated. Thanks! search_results.html <h1>Results for "search term here {{ title_contains_query }}”</h1> base.html (Where the search bar is located) <div class="search-container"> <form method="get" action="{% url 'search_results' %}"> <div class="input-group"> <input type="text" name="q" class="form-control gs-search-bar" placeholder="Search GameStation Games..." value=""> <span class="search-clear">x</span> <button type="submit" class="btn btn-primary search-button"> <span class="input-group-addon"> <i class="zmdi zmdi-search"></i> </span> </button> </div> </form> </div> views.py def is_valid_queryparam(param): return param != '' and param is not None def BootstrapFilterView(request): user_profile = User_Info.objects.all() user_profile_games_filter = Game_Info.objects.all() title_contains_query = request.GET.get('q') if is_valid_queryparam(title_contains_query): user_profile_games_filter = user_profile_games_filter.filter(game_title__icontains=title_contains_query) if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context = { 'user_profile': user_profile, 'user_profile_games_filter': user_profile_games_filter } else: context = { 'user_profile': user_profile, 'user_profile_games_filter': user_profile_games_filter } return render(request, "search_results.html", context) -
Django SQL Dealing
I'm working in a Django app and want to query one of my models to perform data dealing. I tried to perform from django.db import connections cursor = connections['default'].cursor() cursor.execute("select * from Collections") print(cursor.fetchall()) Got the following message: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Could not understand the problem since I am already querying models in my views with QuerySet. Any solutions? -
How to make transactions based on the frequency of transaction in Django
I'm new to Django, but I'm working on a project that allows users to create transactions. I would like to be able to create transactions that are recurring, based on a frequency. For example, a user could create a recurring transaction that is paid out every month. I'm not sure how to best implement this functionality. I've been looking at the django-scheduler library, but I'm not sure if that's the best way to go. Does anyone have any ideas on how to implement this functionality? Here is the transaction model that I'm using: class Type(models.TextChoices): """Class for transaction types.""" DEPOSIT = 'Deposit' PAYMENT = 'Payment' class Frequency(models.TextChoices): """Class for tansactin frequency""" ONETIME = 'One-time' DAILY = 'Daily' EVERY_WEEK = 'Every week' EVERY_TWO_WEEKS = 'Every two weeks' EVERY_THREE_WEEKS = 'Every three weeks' EVERY_MONTH = 'Every month' EVERY_TWO_MONTHS = 'Every two months' EVERY_QUARTER = 'Every quarter' EVERY_SIX_MONTHS = 'Every six months' EVERY_YEAR = 'Every year' EVERY_TWO_YEARS = 'Every two years' class Transaction(models.Model): """Transaction model.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) transaction_type = models.CharField( max_length=30, choices=Type.choices, default=Type.PAYMENT, ) transaction_date = models.DateField() frequency = models.CharField( max_length=30, choices=Frequency.choices, default=Frequency.ONETIME, ) category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, blank=True, related_name='transactions', ) subcategory = models.ForeignKey( SubCategory, on_delete=models.CASCADE, null=True, … -
I get a 403 forbidden in my django project after submiting a form. I know there's a problem with CSRF token
I think the problem is in part due to the fact im not using the HTML template tag since, I'm creating a project using the JS generating the HTML from there. For addressing this in the HTML i added this script(before the js script I use): <script> var csrfToken = '{{ csrf_token }}'; </script> Im using the following script after the form code to send the information to my django project: const apiSendDataUser = (event) => { event.preventDefault(); const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value; const formData = new FormData (event.target); fetch('https://127.0.0.1:8000/myProject/post_user',{ method: 'POST', body: formData, headers: { 'X-CSRFToken': csrfToken } }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Error: ' + response.status); } }) .then(data => { // Handle the response data console.log(data); }) .catch(error => { // Handle any errors console.error(error); }); }; And finally, the post_user function on the views.py is: @require_POST def post_user(request): try: email = request.POST['email'] if not User.objects.filter(email).exists() : username = request.POST['username'] password = request.POST['password'] User.objects.create_user(username=username, password=password, email=email) return JsonResponse( { "success":True, "message": "Usuario añadido." } ) except Exception as e: return JsonResponse({ "success": False, "message": e.args[0] }, status=404) I think is all, I dont know how to handle things with … -
django, the form is always wrong
I have a django application and I am writing two-factor authentication by email for it (a code should be sent to the mail). But the problem arises at the stage of checking the current email and password. as I understand it, the if form.is_valid() check does not work and constantly returns a form error. Please enter a correct %(username)s and password. Note that both fields may be case-sensitive. and This account is inactive. Although I am sure that I am entering the correct user data and there is is_active : True in the database table. My user model is redefined like this: class User(AbstractUser): email = models.EmailField(_("email_address"), unique=True) class RoleChoise(models.TextChoices): standard = "ST", "standart" admin = "AD", "admin" worker = "WK", "worker" inactive = "IA", "banned" role = models.CharField(choices=RoleChoise.choices, default=RoleChoise.standard, max_length=2) #another my fields my custom authorization function looks like this: class LoginOrSendCodeView(FormView): template_name = 'accounts/login.html' form_class = UserLoginForm success_url = reverse_lazy('login') def post(self, request, *args, **kwargs): if "OTP_code" in request.POST: ... #my other form handler, it works else: form = UserLoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, email=email, password=password) if user: if user.role != "IA": if user.two_factor_authentication: otp_model_object = OtpModel(user=user) otp_model_object.save() otp_model_object.send_otp_in_mail() return render(request, … -
KeyError: 'receiver' in self.scope[]
I am trying to retrieve data through self.scope[] in Django channels but I keep getting KeyError. How can I get the receiver part through self.receiver_username without the error? See the code details below: consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.receiver_username = self.scope['url_route']['kwargs']['receiver'] self.accept() routing.py websocket_urlpatterns = [ re_path(r'ws/socket-server/(?P<receiver>\w+)/$', consumers.ChatConsumer.as_asgi()), ] chat.html <div id="chat-messages"></div> <form id="form"> <input type="text" name="message" placeholder="Type a message..."> <input type="text" name="receiver" value="test"> <button id="send-button">Send</button> </form> <div id="messages"></div> <script> var receiver = 'test'; let url = `ws://${window.location.host}/ws/socket-server/` + receiver + '/' const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) if(data.type === 'chat'){ let messages = document.getElementById('messages') messages.insertAdjacentHTML('beforeend', `<div> <p>${data.message}</p> </div>`) } } let form = document.getElementById('form') form.addEventListener('submit', (e)=> { e.preventDefault() let message = e.target.message.value chatSocket.send(JSON.stringify({ 'message': message })) form.reset() }) </script> When I try to retrieve the var receiver through self.receiver_username, I got the following error: KeyError: 'receiver' WebSocket DISCONNECT /ws/socket-server/test/ [127.0.0.1:51206] -
How to check if user is logged in using class based custom middleware?
I want to redirect not logged in users to login page every request they do. I have a custom class based middleware. I found on stackoverflow a solution to the problem using function based middleware. When I try to use this function inside my class, it doesn't work. But if I remove class and leave the function, it works fine. How can I fix this problem? # class based class CustomMidd: def __init__ (self, get_response): self.get_response = get_response def __call__(self, request): self.check_user(request) self.process_request(request) response = self.get_response(request) return response # def process_request(self, request): # allowed_ips = ['127.0.0.1'] # my ip # ip = request.META.get('REMOTE_ADDR') # if ip not in allowed_ips: # raise Http404 # return None def check_user(self,request): if request.user.is_authenticated or request.path == '/login/': response = self.get_response(request) return response return redirect('/login/') # function based def require_login(get_response): def middleware(request): if request.user.is_authenticated or request.path == '/login/': response = get_response(request) return response return redirect('/login/') return middleware It should also raise 404 error if ip is not allowed. So if I leave only function, it works, but I can't check ip now. When I try to enter main page, it returns an error Field 'id' expected a number but got.... This is because at the … -
Django form.is_valid() doesnt let anything go through. (False)
The program doesnt have any typos. when i try to write to the database via forms and press submit, the request will come back, but wont be inserted into database. # views.py from django.shortcuts import render from django.http import HttpResponse from .models import Book from .forms import BookForm # Create your views here. def homepage_welcome(request): return render(request, 'homepage.html') def addbook(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): form.save() return render(request, 'bookadded.html') return render(request, 'addbook.html') else: return render(request, 'addbook.html') def borrowbook(request): books = Book.objects.all() return render(request, 'borrowbook.html', {'booklist': books}) def book(request, pk): book = Book.objects.get(id=pk) context = {'book':book} return render(request, 'book.html', context) def bookadded(request): return render(request, 'bookadded.html') # forms.py from django.forms import ModelForm from .models import Book class BookForm(ModelForm): class Meta: model = Book fields = '__all__' # urls.py from django.urls import path from . import views urlpatterns = [ path('', views.homepage_welcome), path('addbook/', views.addbook, name='addbook'), path('borrowbook/', views.borrowbook), path('book/<str:pk>/', views.book, name = 'book'), path('bookadded/', views.bookadded), ] # models.py from django.db import models from django.utils import timezone # Create your models here. class Book(models.Model): booktitle = models.CharField(max_length=100) content = models.TextField() date_created = models.DateTimeField(default=timezone.now) I tried running the code without the if form.is_valid(): line, but that resoulted in "ValueError at /homepage/addbook/". then … -
Has superset functionality changed?
I've been using Django and superset in docker containers. I had these two lines of codes <div class="container"> <a target="_blank" href="http://localhost:8088/login?username={{ username }}&redirect=/superset/dashboard/services/?standalone=0&expand_filters=0">Explore Dataset</a> </div> <div> <iframe src="http://localhost:8088/login?username={{ username }}&redirect=/superset/dashboard/services/?standalone=&show_filters=1" style="position:absolute;top:220px;bottom:0px;width:100%;height:100%"></iframe> </div> Up until last week they have both worked. The first one to function as a link to the actual superset page and the iframe to show a specific dashboard on the page. I rebuilt my containers last week and now my iframe doesn't work. It shows 'localhost refused to connect.' The other link, however, does work still. Is anyone aware of a change in superset (or Django) and a possible fix or workaround to get this working again? -
django docker, how to copy local db data to the docker db?
I have dockerized a existing django app and an existing postgres database.the tables are created in the docker container. But the tables are empty . There is no data in it. if I connect to the docker container. And I do a \d+ | Schema | Name | Type | Owner | Persistence | Size | Description | --------+------------------------------------------+----------+---------------+-------------+------------+------------- | public | hotelWelzijnAdmin_animal | table | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_animal_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_category | table | hotelwelzijn | permanent | 8192 bytes | | public | hotelWelzijnAdmin_category_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_groups | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_groups_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | public | accounts_account_user_permissions | table | hotelwelzijn | permanent | 0 bytes | | public | accounts_account_user_permissions_id_seq | sequence | hotelwelzijn | permanent | 8192 bytes | | … -
Can I use Prisma as the ORM inside of Django instead of Django's ORM?
I'd like to use Django + Django Rest Framework as my backend for a bunch of reasons (maturity, great tooling, security, etc.). I'm curious about using Prisma as the ORM layer instead of Django's ORM. Is there anything technically infeasible with this setup, or are there any major gotchas that may not be obvious that would make this a terrible idea? -
Make endpoint that returns a list of strings using Django Rest Framework
I have this Artist model: class Artist(models.Model): name = models.CharField(max_length=100) #songs = models.ManyToManyField('Song', related_name='artists') def __str__(self): return self.name class Meta: ordering = ('name',) I want to make a api endpoint that returns all the Artists row names as a list of string like for example: ["50 Cent", "Eminem", "Snoop Dogg", ...] . i have created this artists/names/ url in my urls.py: path('artists/names/', views.artist_names, name='artist_names'), I have tried two ways already: Using a python list: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) artist_names_list = list(artists) return Response(artist_names_list) Using ListSerializer in my serializers.py: class ArtistNameSerializer(serializers.Serializer): name = serializers.ListSerializer(child=serializers.CharField()) and in my views.py i created the artist_names method: @api_view(['GET']) def artist_names(request): artists = Artist.objects.values_list('name', flat=True) serializer = ArtistNameSerializer(artists, many=True) return Response(serializer.data) From both of them when i go to the endpoint i get: GET /api/artists/names/ HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Can someone help? What am i doing wrong?