Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Creating a new post, but it belongs to none
Creating a new checklist, the checklist get created but I have to go inn admin panel to set what task it belongs to. The task is a foreignkey in the checklist. views.py def project_detail(request, slug): ''' Detailed view of given project ''' context = {} project = get_object_or_404(Project, slug=slug) tasks = Task.objects.filter(task_completed=False, project=project) context.update({'project': project}) checklist_form = ChecklistForm(request.POST or None) if request.method == "POST": # Create new Checklist if 'save_new_checklist' in request.POST: if checklist_form.is_valid(): print("\n\n New checklist form is valid") author = Profile.objects.get(user=request.user) new_checklist = checklist_form.save(commit=False) new_checklist.user = author new_checklist.checklist = tasks new_checklist.save() return redirect('project_detail', slug=slug) context.update({ 'tasks': tasks, 'checklist_form': checklist_form, 'title': tasks }) return render(request, 'projects/tasks.html', context) models.py class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() project = models.ForeignKey(Project, blank=True, null=True, related_name='task', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def __str__(self): return self.title class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) description = models.TextField(default="Checklist description") task = models.ForeignKey(Task, blank=True, null=True, related_name='checklist', on_delete=CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, … -
React do not hit Django API on kubernetes
I have a django drf API and a react APP in a cluster kubernetes. My API is not exposed (i cannot expose it because of security conditions). React APP is exposed with an ingress. React need to consume Django API (via axios). But it seems that axios requests are made by browsers so api service is unreachable. Need someone already faced this issue? Thanks in advance! Gauthier -
ReportLab problem with addEntry for Django
I have a problem with addEntry in ReportLab, not adding chapters to table of contents only displays "Placeholder for table of contents 0", I don't know why. This is my first ReportLab test and I started with Django. Chapter generation works, only TableOfContent remains.I have a problem with addEntry in ReportLab, not adding chapters to table of contents only displays "Placeholder for table of contents 0", I don't know why. This is my first ReportLab test and I started with Django. Chapter generation works, only TableOfContent remains. from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer #from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch from django.http import HttpResponse, HttpResponseBadRequest #from io import BytesIO from reportlab.platypus import SimpleDocTemplate, Paragraph, PageBreak from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import mm, inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.pdfmetrics import registerFontFamily from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex #from reportlab.lib.pagesizes import letter, A5 from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER, TA_RIGHT PAGESIZE = (140 * mm, 216 * mm) BASE_MARGIN = 5 * mm def generatePDF(request,id): pdfmetrics.registerFont(TTFont('Berylium', 'resources/fonts/Berylium/Berylium.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBd', './resources/fonts/Berylium/Beryliumbold.ttf')) pdfmetrics.registerFont(TTFont('BeryliumIt', './resources/fonts/Berylium/BeryliumItalic.ttf')) pdfmetrics.registerFont(TTFont('BeryliumBI', './resources/fonts/Berylium/BeryliumboldItalic.ttf')) registerFontFamily('Berylium', normal='Berylium', bold='BeryliumBd', italic='BeryliumIt', boldItalic='BeryliumBI') PAGE_HEIGHT=defaultPageSize[1] PAGE_WIDTH=defaultPageSize[0] book = Book.objects.get(id=id) Title = book.title pageinfo = book.title Author = … -
Django testing: test fails on create view with post request
I am building test for my views and I am unable to build correct one for generic CreateView. I am following this documentation mostly: https://docs.djangoproject.com/pl/4.0/topics/testing/advanced/#django.test.RequestFactory Does anyone have sollution for this? blog.models class Post(models.Model): title = models.CharField(max_length=128) intro = models.TextField() content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('blog:post-detail', kwargs={'pk': self.pk}) def __str__(self): return self.title blog.views class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'intro', 'content', 'category'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) blog.urls app_name = 'blog' urlpatterns = [ path('post/new/', views.PostCreateView.as_view(), name='post-create'), # some other paths,] blog.tests.test_views class PostViewsTests(TestCase): def setUp(self): self.author = User.objects.create_user( username='abcUser, email='abcuser@mail.com', password='abcpassword') self.category = Category.objects.create(name='New test category') self.new_post = Post.objects.create( title='Lorem Ipsum', intro='Neque porro quisquam est ', content='There is no one who loves pain itself...', author=self.author, category=self.category) self.client = Client() self.factory = RequestFactory() def test_post_create_view_if_adds_new_post(self): data = { 'title': 'Lorem Ipsum2', 'intro': 'Neque porro quisquam...', 'content': 'Neque porro quisquam... - There is no...', 'category': self.category } request = self.factory.post(reverse('blog:post-create'), data=data) request.user = self.author response = views.PostCreateView.as_view()(request) newest_post = Post.objects.order_by('-date').first() self.assertEqual(response.status_code, 200) self.assertEqual(newest_post.title, 'Lorem Ipsum2') test's result: Found 6 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). … -
Asynchronous Amazon Transcribe speech2text display transcripts with Django
I'm trying to build a fullstack web app with AWS Transcribe service and Django and Python. What I want to achieve is something like displaying transcripts from speaker in real time word by word. A demo can be found here: https://www.loom.com/share/f49e8d2b264a4c9b8803a7b0612d103f?t=0 The AWS Transcribe sample code can be found: https://github.com/awslabs/amazon-transcribe-streaming-sdk/blob/develop/examples/simple_mic.py But I'm having trouble displaying the text line by line. What I can achieve so far is I can allow the user to speak for 10 seconds and then display the whole transcript on a web page. See my code below: # Create your views here. def home(request): return render(request, 'aws_transcribe_model/home.html') def startVideoChat(request): t1 = threading.Thread(target=startTranscribing) t1.start() t1.join(10.0) print("\n ------------------------------------ \n") print("transcribing finished") print(CONSTS.transcript) return render(request, 'aws_transcribe_model/startvideochat.html', {'transcript': CONSTS.transcript}) def startTranscribing(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(sample_Amazon_Transcribe_simple_mic.basic_transcribe()) loop.close() I've been looking into things but have not found a solution how to display the text line by line. As you can see in method startVideoChat I can only return once with the html file. Is there a simple way to do this? -
Django can't save a form to specific Model
after messing around with the code for an hour, I have to ask you. So I have a model called Ticket where someone can open a ticket and it will be send to the admin. Now I tried to add a feature so that the user and admin can write messages in this ticket. My try: \\views.py def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) waiting_message = "Mark as 'Waiting'" solved_message = "Mark as 'Solved'" if obj.reopened_counter > 5: solved_message = 'Ticked solved forever' waiting_message = 'Ticked solved forever' button_form = TicketSolved(request.POST) time.sleep(2) if button_form.is_valid: obj.reopened_counter += 1 if obj.reopened_counter > 5: obj.ticket_waiting = True obj.ticket_solved = False if obj.ticket_waiting == False and obj.ticket_solved == True: obj.ticket_waiting = True obj.ticket_solved = False else: obj.ticket_waiting = False obj.ticket_solved = True obj.save() user_form = TicketMessagesForm( request.POST, instance=TicketMessages(#no idea what to do hea# maybe id=id?#)) if user_form.is_valid(): instance = user_form.save(commit=False) # something to save the user message instance.save() return render(request, 'ticket-system.html', {'obj': obj, 'waiting_message': waiting_message, 'solved_message': solved_message, 'button_form': button_form, 'user_form': user_form}) The useless button_form is just because I didnt know how to handle to forms, two Post requests. You can ignore this ticket_waiting/ticket_solved thing. Important is the the TicketMessageForm. This form is just for the … -
Django ModelViewSet It takes a long time to display requests on the screen
I measured how many seconds it takes to prepare the data for the request, 4 seconds came out. In the browser, the request is displayed only after 20 seconds. What could this be related to? views.py class ProductImproveView(ModelViewSet): filterset_class = ProductFilter serializer_class = ProductListingSerializerLightImproved def get_queryset(self): return { 'qs': Product.objects.all()[:30], 'count': Product.objects.all().count() } def list(self, request, processed_queryset=None, *args, **kwargs): start_time = datetime.now() result = self.get_queryset() queryset = result['qs'] count = result['count'] serializer = self.get_serializer(queryset, many=True, context={'request': request}) d = serializer.data g = JsonResponse({ 'count': count, 'next': 'nd', 'results': d }) print(g.content) print(datetime.now() - start_time) # 4 seconds return g urls.py router = DefaultRouter() router.register(r'products-improve', ProductImproveView, basename='products') urlpatterns = [] urlpatterns += router.urls -
Django Model Form Integer as Drop Down
I have a simple Model form in my project as follows: class InviteForm(forms.ModelForm): class Meta: model = Invite fields = ['max_guests', 'rsvp_guests', 'rsvp_attendance'] Max Guests is just an integer and appears for the user to type in. As the value is always small (<10), I would like this to be a dropdown instead with all values 0-max. Is there a way to overwrite an integer input as such? -
Django Form Field Max not Setting from Instance
I am trying to provide my form in Django a dynamic max value based on the model instance it is being passed (such that the user cannot set more guests than the model has stored they are allowed). I do not run into any errors but this max just does not take effect (I am able to put and save what ever in there). Beyond using the instance on init, is there anything else that should be done? My form: class RSVPForm(forms.ModelForm): class Meta: model = Invite fields = ['rsvp_guests'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['rsvp_guests'].widget.attrs.update( {'max': self.instance.max_guests}, ) My view where the instance is passed: def view_rsvp_create(request, id): invite = get_object_or_404(Invite, id=id) form = RSVPForm(request.POST or None, instance=invite) if form.is_valid(): new_invite = form.save(commit=False) new_invite.save() return redirect('view_rsvp_overview', name = invite.event.wedding.subdomain, code = invite.guest.code) data = {'form': form} template='experience/rsvp-create.html' return render(request, template, data) The template: {% load crispy_forms_tags %} <form class="form-horizontal form-material" method="post"> {% csrf_token %} {{ form | crispy }} <div class="form-group"> <div class="form-group text-center m-t-20"> <div class="col-12"> <button class="btn btn-success btn-block btn-lg waves-effect waves-light" type="submit">Add</button> </div> </div> </div> </form> -
Integrate Machine learning model with a webapp using django or flask
Hello , I am trying to make a fake news detector using machine learning. I have trained a model which can detect fake news based on the dataset it is trained on. But now my question is how do I showcase this model in a webapp (made with django or flask) so the end user can use it Please can you help me with this or at least helping me find a resource which can help me solve my problem !! -
Can I trigger Celery task on table update in Django?
For example, I have a model: class SomeModel(model.Model): is_active = BooleanField(default=False) ... Is it possible to trigger Celery task when is_active changes to True? The most important thing here is that I need to trigger it regardless of the way is_active changed, whether it changed via shell, admin panel, api call etc. The DB I use is psql. -
Is there any way to make a manual join using Django ORM?
lets say I have the following models: class ModelA(models.Model): pass class ModelB(ModelA): pass class ModelC(models.Model): model_a = models.ForeignKey(ModelA) class ModelD(models.Model): model_c = models.ForeingKey(ModelC) And I need to filter all the instances of ModelD that have a relation in ModelB. Is there any way to remove the unnecesary joins in the query that the queryset will produce ? ModelD.objects.filter(model_c__model_a__model_b__id__isnull=False) If there's any way to make a filter like this: ModelD.objects.filter(model_c__model_b__id__isnull=False) I know how to make the query on SQL, but for terms of readabilty and code maintenance I would like to know if there's any way to make the manual join or to remove that intermediate join. Thanks in advance for the replies ! -
Django: list view not recognized
I have to do this project of classified ads for Coursera. Essentially every user can post, update and delete advertisements. The problem is that even if the objects are correctly stored (I checked tables and objects via admin and manually with the command line), the ad list doesn't show up and it tells "There are no ads in the database." even though there are ads. I'm looking everywhere but I cannot find the error. Here's the code: ad_list.html: views.py: from ads.models import Ad from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView class AdListView(OwnerListView): model = Ad class AdDetailView(OwnerDetailView): model = Ad class AdCreateView(OwnerCreateView): model = Ad fields = ['title', 'text', 'price'] class AdUpdateView(OwnerUpdateView): model = Ad fields = ['title', 'text', 'price'] class AdDeleteView(OwnerDeleteView): model = Ad owner.py: from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin class OwnerListView(ListView): """ Sub-class the ListView to pass the request to the form. """ class OwnerDetailView(DetailView): """ Sub-class the DetailView to pass the request to the form. """ class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current … -
Django reCAPTCHA with multiple forms
I have a DJANGO application where I protect forms with reCAPTCHA v2 invisible. I have no issue protecting 1 form, everything works well and I have been using this feature for quite some time. However, if I have 2 forms on the same page, EACH protected with their own captcha, it doesn't work. Here's what happens: OK: both forms have their individual onSubmit_xxxand onSubmit_yyy function (with a different widget uuid) OK: both forms get their "submit" event properly redirected to the verifyCaptcha_xxx or verifyCaptch_yyy function NOK: after grecaptcha.execute(), ALWAYS the onSubmit_xxx function (of the first form) is executed (with the wrong widget uuid) I am using Django 2.1 with Python 3.5 Any hints? Thanks a lot!! -
How to Call a Javascript function onclick event inside jinja template?
{% for person in teacher %} <tr class="bg-gray-100 border-b"> <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"></td> <td class="p-0 py-4 whitespace-nowrap text-sm font-medium text-gray-900"> <img src="{{person.customuser.profile_pic.url}}" class="rounded-lg w-32" alt="Avatar" /> </td> <td class="text-sm text-gray-900 font-light px-6 py-4 whitespace-nowrap"> <p>{{person.customuser.first_name}} {{person.customuser.last_name}}</p> </td> <td class="text-sm text-gray-900 font-light px-4 py-4 whitespace-nowrap"> {% for item in person.subjects.all %} <p>{{item.name}}</p> {% endfor %} </td> <td class="text-sm text-gray-900 font-light px-4 py-4 whitespace-nowrap"> <div class="flex items-center justify-center"> <div id="btnView" class="inline-flex shadow-md hover:shadow-lg focus:shadow-lg" role="group"> <button type="button" class="rounded-l inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-blue-700 focus:bg-blue-700 focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out">Edit</button> <button onclick='viewDetails()' type="button" class=" inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-green-700 focus:bg-green-700 focus:outline-none focus:ring-0 active:bg-green-800 transition duration-150 ease-in-out">View</button> <button type="button" class=" rounded-r inline-block px-6 py-2.5 bg-[#4951bf] text-white font-medium text-xs leading-tight uppercase hover:bg-red-700 focus:bg-red-700 focus:outline-none focus:ring-0 active:bg-blue-800 transition duration-150 ease-in-out">Delete</button> </div> </div> </td> </tr> {% endfor %} I want to call a javascript function viewDetails({{person.id}}) inside onclick event when the user presses the button.I want the value {{person.id}} to be passed as an argument which is coming from the for loop in jinja tag. Is it possible? -
Django usage of ForeignKey
I have this micro ticket "system" \\models.py class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() creator_adress = models.GenericIPAddressField(null=True) start_date = models.DateTimeField(default=timezone.now) ticket_waiting = models.BooleanField(default=True) ticket_solved = models.BooleanField(default=False) reopened_counter = models.IntegerField(default=0) ... Until now, only one message (when the user opens the ticket) can be sent by the user, which will be forwarded to the admin. But the admin and the user can't write any other messages back and forth under the ticket yet. If you use a new model for this, which is connected to every single ticket like so? class TicketMessages(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) admin_message = models.TextField() user_message = models.TextField() What is the best way to implement this? Thank you very much :> -
Uvicorn async workers are still working synchronously
Question in short I have migrated my project from Django 2.2 to Django 3.2, and now I want to start using the possibility for asynchronous views. I have created an async view, setup asgi configuration, and run gunicorn with a Uvicorn worker. When swarming this server with 10 users concurrently, they are served synchronously. What do I need to configure in order to serve 10 concurrent users an async view? Question in detail This is what I did so far in my local environment: I am working with Django 3.2.10 and Python 3.9. I have installed gunicorn and uvicorn through pip I have created an asgi.py file with the following contents import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyService.settings.local') application = get_asgi_application() I have created a view with the following implementation, and connected it in urlpatterns: import asyncio import json from django.http import HttpResponse async def async_sleep(request): await asyncio.sleep(1) return HttpResponse(json.dumps({'mode': 'async', 'time': 1).encode()) I run locally a gunicorn server with a Uvicorn worker: gunicorn BudgetService.asgi:application -k uvicorn.workers.UvicornWorker [2022-01-26 14:37:14 +0100] [8732] [INFO] Starting gunicorn 20.1.0 [2022-01-26 14:37:14 +0100] [8732] [INFO] Listening at: http://127.0.0.1:8000 (8732) [2022-01-26 14:37:14 +0100] [8732] [INFO] Using worker: uvicorn.workers.UvicornWorker [2022-01-26 14:37:14 +0100] [8733] [INFO] Booting worker … -
Passing variables to extended template
I'm having templates that later my all other templates extend. Most basic template is base.html. It includes the navigation bar: {% include 'includes/navigation.html' %} Navigation bar should display different titles depending on the role set: {% if role == "admin" %} <p class="title">Welcome to the Administrator Dashboard!</p> {% elif role == "user" %} <p class="title">Welcome to your Dashboard!</p> {% endif %} From base.html a few other layouts extend, for example 2_column.html {% extends "layouts/base.html" %} {% block content %} <div class="block block_main col-md-9"> {% block block_main %}{% endblock block_main %} </div> <div class="block block_side col-md-3"> {% block block_side %}{% endblock block_side %} </div> {% endblock content %} And only from these templates I build all my other html files. For example login.html: {% extends "layouts/2_column.html"%} {% block block_main %} <h3 class="block_title">Login</h3> <form method="post"> <!-- Form --> <div class="input-group"> <label for="file_id">Username</label> <input type="text" id="username"> </div> </form> {% endblock block_main %} I cannot figure out how to pass the role correctly all the way up to the navigation.html. Is that even possible? I've tried to wrap up the whole template in: {% with role="admin" %} {% endwith %} but if {% extends ... %} is inside it tells me that the with … -
submitting a value to Django view through admin SB2 sidebar
I am using the SB admin2 bootstrap dashboard template, and there is a side bar with collapse menus that I am planning on using. I aim to have the user choose one of these 7 options, where each option would have a different value or name and to pass this value/name to a django view called modify once the user clicks on one of the 7 options. HTML: <!-- Nav Item - Pages Collapse Menu --> <li class="nav-item"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-cog"></i> <span>Options</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Filter Options:</h6> <a class="collapse-item" href="buttons.html">Option1</a> <a class="collapse-item" href="buttons.html">Option2</a> <a class="collapse-item" href="buttons.html">Option3</a> <a class="collapse-item" href="buttons.html">Option4</a> <a class="collapse-item" href="buttons.html">Option5</a> <a class="collapse-item" href="buttons.html">Option6</a> <a class="collapse-item" href="buttons.html">Option7</a> </div> </div> </li> URLS: path('dashboard', modify, name='dashboard'), How can I achieve this without changing the layout of the side bar showed in the image? ( I tried using django forms, but I ended up with a dropdown list with a layout different than this one) -
Django forms not working (the button is doing nothing)
I am new to Django and after I created two forms (TopicForm and EntryForm) only the second one is not working. When I click the button Add Entry, nothing happens. I can't see where the issue actually is, pretty strange because I did almost the same thing for the first form and eveything is good.Tell if I need to share any other files. forms.py: from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text': 'Entry:'} widgets = {'text': forms.Textarea(attrs={'cols': 80})} urls.py: """Defines URL patterns for learning_logs.""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ # Home page path('',views.index, name='index'), # Page that shows all topics. path('topics/', views.topics, name='topics'), # Detail page for a single topic. path('topics/<int:topic_id>/', views.topic, name='topic'), # Page for adding a new topic path('new_topic/', views.new_topic, name='new_topic'), # Page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), ] views.py: from django.shortcuts import render, redirect from .models import Topic from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show … -
Django filtering if multiple foreign key return , display only first foreign key data
I want to get all the quizArchive where qbank, qset match by ID. But only those model that user's first created. I have this model: class QuizArchive(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quizarchive") questionset = models.ForeignKey( "qbank.QuestionSet", on_delete=models.CASCADE, related_name="qarchive" ) qbank = models.ForeignKey( "qbank.QuestionBank", on_delete=models.CASCADE, null=True, blank=True, related_name="qbank", ) wrong = models.ManyToManyField(Question, related_name="qarchivew", blank=True) skipped = models.ManyToManyField(Question, related_name="qarchivesk", blank=True) right = models.ManyToManyField(Question, related_name="qarchiver", blank=True) selected_answer = models.JSONField(blank=True, null=True) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user} takes {self.questionset}" Serializer Code: class LeaderboardSerializer(serializers.ModelSerializer): class Meta: model = QuizArchive fields = ["user", "wrong", "right", "skipped", "updated_time","questionset"] def to_representation(self,instance): leaderboard = super().to_representation(instance) return leaderboard API Code: class QSetLeaderBoard(views.APIView): permission_classes = [AllowAny,] def get(self,request,*args, **kwargs): qset = QuestionSet.objects.filter(id=int(kwargs.get("qset"))).first() qbank = QuestionBank.objects.filter(id=int(kwargs.get("qbank"))).first() qarchive = QuizArchive.objects.filter(qbank=qbank,questionset=qset) serializer = LeaderboardSerializer(qarchive,many=True) data = serializer.data return Response(data) Result : [ { "user": 1, "wrong": [], "right": [], "skipped": [ 1 ], "updated_time": "2022-01-26T12:44:12.055967Z", "questionset": 1 }, { "user": 2, "wrong": [ 1 ], "right": [], "skipped": [], "updated_time": "2022-01-26T13:00:27.761721Z", "questionset": 1 }, { "user": 1, "wrong": [ 1 ], "right": [], "skipped": [], "updated_time": "2022-01-26T12:58:52.798367Z", "questionset": 1 }, { "user": 2, "wrong": [], "right": [ 1 ], "skipped": [], "updated_time": "2022-01-26T13:00:47.148016Z", "questionset": 1 } ] But I only … -
Django endpoint executes but never returns Response
The endpoint used to work just fine, but lately as I tested it, it does all the logic it has to do, but when it comes to return the HttpResponse() it never does. I got some logs on my code (the print in this example) and I get to the line before returning the Response but it just doesn't return it, it's like it gets stuck after doing the print(). def endpoint(): # some logic here... print('I got here') return HttpResponse('...', status=200) Also this happens when the "logic" inside it gets a massive amount of data as input, eventhough it executes just fine, it never returns. With smaller data as input it works perfectly and returns. Honestly I've no idea why this is happening since there aren't any errors showing up. -
Error Message: why i am getting "None" although i have add get() at views.py in Django ??? Can anyone help me
This is my Views.py file and in this file I am trying to get the value from HTML from django.shortcuts import render from .models import kitchenData from django.http import HttpResponse def kitchen(request): if request.method == 'POST': table_num = request.POST.get('table_num') full_name = request.POST.get('full_name') qty = request.POST.get('qty') drink_name = request.POST.get('drinks_name') drink_qty = request.POST.get('drinks_qty') message = request.POST.get('message') price = request.POST.get('price') status = request.POST.get('status') print(table_num,full_name,qty,drink_name,drink_qty,message,price,status) return render(request, 'kitchen/kitchen_order.html') else: return render(request, 'kitchen/kitchen_order.html') HTML Photo [![i have attached the output][1]][1] [1]: https://i.stack.imgur.com/y4pYy.png -
Automatic Ordinal Number in django queryset ? How to sort this thing in Django?
I have problem to sort such thing as 'Ordinal Number'. For example, I have my Parent Model (Order) and child (Item). I don't know how make Items ID field starting from 1 to N where N is number of items in this particullar Order. It's hard to explain for me , so I put some img with things I want to make and try to explain it by example. My problem on screen And those are my models.py: class Order(models.Model): PENDING = 0 DURING = 1 DONE = 2 STATUS = ( (PENDING, 'Oczekuję'), (DURING, 'W trakcie'), (DONE, 'Zakończone'), ) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user') date_created = models.DateTimeField(auto_now_add=True, null=True) slug = RandomSlugField(length=7, exclude_lower=True, exclude_upper=True, exclude_vowels=True) status = models.SmallIntegerField(choices=STATUS, default=PENDING) class Meta: verbose_name = "zamówienie" verbose_name_plural = "zamówienia" def __str__(self): return "Zamówienie ID#{} z dnia {}".format(self.slug, self.date_created.strftime('%d/%m/%y')) def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) class Item(models.Model): order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL) lenght = models.DecimalField(max_digits=4, decimal_places=0) width = models.DecimalField(max_digits=4, decimal_places=0) lenght = models.PositiveSmallIntegerField(blank=False) quantity = models.SmallIntegerField(default=1, blank=False, null=False) description = models.CharField(max_length=255, blank=True, null=True) lenght1 = models.BooleanField(default=False) lenght2 = models.BooleanField(default=False) width1 = models.BooleanField(default=False) width2 = models.BooleanField(default=False) class Meta: verbose_name = "formatka" verbose_name_plural = "formatki" def __str__(self): return "{} x {}".format(self.width, self.lenght) -
Improve db performance in DetailView
I want to improve speed and performance of my blog and avoid the duplicate queries. I'm using the Django debug toolbar for that btw. Note: I'm indexing my models. Here are the models I have: class Post(Model): name ... ... author = ForeignKey(Author..) comments = ManyToManyField(Comment...) ... class Comment(Model): content... ... author = ForeignKey(Author...) replies = ManyToManyField(Reply...) class Reply(Model): content... ... author = ForeignKey(Author...) ... Is there any way to improve the speed of the post detail page, it's above 2 seconds before caching. and 1 second after caching. Here is my try: class PostDetailView(HitCountDetailView): ... def get_queryset(self): return super(PostDetailView, self).get_queryset().select_related().prefetch_related() .... Also I'm using the django-hitcount to track visitors, but it's quite slowy, any fix for that too.