Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
skeleton estimation of human pose
This is the code I have so far, my aim is to reproduce something like this: But I end up with this How would I go about ensuring the edges are correct? How would I display the coordinates? def visualise_coordinates(request): xdata = np.array([-0.013501551933586597, -0.14018067717552185, 0.03889404982328415, -0.01468866690993309, -0.052195221185684204, -0.019107796251773834, 0.1497691571712494, 0.3384685516357422, -0.01354127749800682, 0.20444869995117188, -0.01537160761654377, 0.10283246636390686, 0.16161373257637024]) ydata = np.array([-0.9542085528373718, -1.0142440795898438, -0.5674616694450378, -0.6482287049293518, -0.21104587614536285, -0.26092272996902466, 0.01090222503989935, -0.06246425583958626, 0.07578188925981522, -0.06475285440683365, 0.27830997109413147, 0.16628871858119965, 0.40817680954933167]) zdata = np.array([0.4491078853607178, 0.26747873425483704, 0.3288397789001465, 0.15092524886131287, 0.14701153337955475, -0.013860990293323994, 0.31942757964134216, -0.10401999950408936, 0.2921887934207916, -0.2079567015171051, 0.12265170365571976, -0.21420519053936005, -0.07994606345891953]) fig = go.Figure(data=[go.Scatter3d(x=xdata, y=ydata, z=zdata, mode='lines', line_width=2, line_color='blue')]) plot_div = opy.plot(fig, auto_open=False, output_type='div') return render(request, 'visualise_coordinates.html', context={'plot_div': plot_div}) -
Autofill form to get value with AJAX at models in Django
Dear All need some help to get data when user input I have html file <!DOCTYPE html> <html> <head> <title>Form Pencarian</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/smoothness/jquery-ui.css" /> <!-- tambahkan link CSS bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" > </head> <body> <div class="container mt-5"> <form id="searchForm"> <div class="searchContainer form-group"> <label for="searchText">Perbandingan ke 1</label> <div class="input-group rounded"> <input type="text" class="form-control rounded searchText" name="searchText" placeholder="Ketik untuk perbandingan"> <div class="input-group-append"> <button type="button" class="close closeBtn"><span>&times;</span></button> </div> </div> </div> </form> </div> <script> $(document).ready(function() { var formCount = 1; var autocompleteList = $('<div class="autocomplete-list"></div>'); $("#searchForm").on("keyup", ".searchText", function(e) { var searchText = $(this).val(); var searchContainer = $(this).parent().parent(); if (searchText !== "" && searchContainer.next(".searchContainer").length === 0 && formCount < 4) { formCount++; var newForm = $('<div class="searchContainer form-group"><label for="searchText">Perbandingan ke ' + formCount + '</label><div class="input-group rounded"><input type="text" class="form-control rounded searchText" name="searchText" autocomplete="off"><div class="input-group-append"><button type="button" class="close closeBtn"><span>&times;</span></button></div></div></div>'); searchContainer.after(newForm); $(this).next(".closeBtn").show(); $(this).attr("disabled", false); $(".submitBtn").remove(); var submitBtn = $('<button type="submit" class="submitBtn btn btn-primary btn-block">Cari</button>'); $("#searchForm").append(submitBtn); // AJAX call untuk mengambil data dari database Produk $.ajax({ url: "/percobaan/", type: "GET", dataType: "json", contentType: 'application/json', data: { term: searchText }, success: function(data) { console.log(data); var autocompleteList = $('<div class="autocomplete-list"></div>'); $.each(data, function(index, value) { var autocompleteItem = $('<div class="autocomplete-item">' + value.fields.nama_produk + '</div>'); autocompleteItem.on("click", function(e) { … -
Cookiecutter Django, Initial docker-compose build fails with docker error
I have created a fresh cookiecutter-django project on a windows machine. The initial "docker-compose -f local.yml build" fails with "failed to solve: executor failed running [/bin/sh -c apt-get update && apt-get install --no-install-recommends -y build-essential libpq-dev]: exit code: 100" Any help would be appreciated. -
How can I set default value to a form field and then hide it away?
models.py class MyUser(AbstractUser): username = None # remove username field email = models.EmailField(_("email address"), unique=True) full_name = models.CharField(max_length=100) phone = models.CharField(max_length=20) is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) is_supervisor = models.BooleanField('supervisor status', default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # fields required when creating a new user in terminal objects = MyUserManager() def __str__(self): return self.full_name forms.py class MyUserCreationForm(UserCreationForm): class Meta: model = MyUser fields = ("email",) class StudentRegisterForm(MyUserCreationForm): class Meta: model = MyUser fields = ['email', 'phone', 'password1', 'password2'] So I want to create a student user based on my MyUser model. Everything should align with the fields on the MyUser model, the only difference here is that I want to set the "is_student" field to "True" automatically and hide this field away when I create a student user. How can I do that? -
Formset ignores form's initial value
Here's a form, MyForm which has a field my_field with an initial value of 10. forms.py from django import forms class MyForm(forms.Form): my_field = forms.IntegerField( initial=10, widget=forms.NumberInput( { 'class': f'form-control', } ), label='', ) whenever a formset is generated from this form, it ignores the initial value, otherwise it works perfectly fine: views.py from django.forms import formset_factory from django.shortcuts import render from myapp.forms import MyForm def generate_formset(form_class, request, **kwargs): factory = formset_factory(form_class, **kwargs) match request.method: case 'POST': return factory(request.POST, prefix=form_class.prefix) case _: return factory(prefix=form_class.prefix) def index(request): formset = generate_formset(MyForm, request) if request.method == 'POST': print(formset.cleaned_data) return render(request, 'index.html', {'formset': formset}) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} <button type="submit">Submit</button> </form> </body> </html> Here's what happens when I just submit the form without modifying the field value. I'm expecting to see a value of 10 in the cleaned form but I get nothing instead. [{}] [29/Mar/2023 01:07:34] "POST / HTTP/1.1" 200 867 Then I set the value to 5, it works fine: [{'my_field': 5}] [29/Mar/2023 01:07:47] "POST / HTTP/1.1" 200 866 -
Status code 500 when I click on my product
This is my first time using redux and django. I click the link to one of my products that takes me to the products page, but I get a 500 error instead. My django server is running in the back and I know it's working because I get an error response in my terminal. I suspect my issue might be my views.py but I'm not sure since I'm not very familiar with django yet. ProductPage.js import React, { useState, useEffect } from "react"; import { Link, useParams } from "react-router-dom"; import { Row, Col, Image, ListGroup, Card, Button } from "react-bootstrap"; import Rating from "../components/Rating"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import { useDispatch, useSelector } from "react-redux"; import { listProductsDetails } from "../actions/productActions"; function ProductPage() { const { id } = useParams(); const dispatch = useDispatch(); const productDetails = useSelector((state) => state.productDetails); const { loading, error, product } = productDetails; useEffect(() => { dispatch(listProductsDetails(id)); }, [id]); return ( <div> <Link to="/" className="btn btn-light my-3"> Go Back </Link> {loading ? ( <Loading /> ) : error ? ( <ErrorMessage variant="danger">{error}</ErrorMessage> ) : ( <Row> <Col md={6}> <Image src={product.image} alt={product.name} fluid /> </Col> <Col md={3}> <ListGroup variant="flush"> <ListGroup.Item> <h3>{product.name}</h3> … -
Django form + formset for a single model
I have a Bird model, which has 2 fields 'common_name' and 'scientific_name'. For a scientific_name there can be multiple common names. So I need to get 'scientific_name' once and 'common_name' multiple times upon clicking 'Add_More' button and then save each common name with its scientific name as model objects. Please help me with re writing the below code to achieve this. current models.py class Bird(models.Model): common_name = models.CharField(max_length=250) scientific_name = models.CharField(max_length=250) current forms.py BirdFormSet = modelformset_factory( Bird, fields=("common_name", "scientific_name"), extra=1 ) current views.py class BirdAddView(CreateView): template_name = "add_bird.html" def get(self, *args, **kwargs): # Create an instance of the formset formset = BirdFormSet(queryset=Bird.objects.none()) return self.render_to_response({'bird_formset': formset}) def post(self, *args, **kwargs): formset = BirdFormSet(data=self.request.POST) if formset.is_valid(): formset.save() return redirect(reverse_lazy("bird_list")) return self.render_to_response({'bird_formset': formset}) -
Speechmatics submit a job without audio argument
I have implemented a SpeechMatics speech to text application with their API as given in this document with the code below : from speechmatics.models import ConnectionSettings from speechmatics.batch_client import BatchClient from httpx import HTTPStatusError API_KEY = "YOUR_API_KEY" PATH_TO_FILE = "example.wav" LANGUAGE = "en" settings = ConnectionSettings( url="https://asr.api.speechmatics.com/v2", auth_token=API_KEY, ) # Define transcription parameters conf = { "type": "transcription", "transcription_config": { "language": LANGUAGE } } # Open the client using a context manager with BatchClient(settings) as client: try: job_id = client.submit_job( audio=PATH_TO_FILE, transcription_config=conf, ) print(f'job {job_id} submitted successfully, waiting for transcript') # Note that in production, you should set up notifications instead of polling. # Notifications are described here: https://docs.speechmatics.com/features-other/notifications transcript = client.wait_for_completion(job_id, transcription_format='txt') # To see the full output, try setting transcription_format='json-v2'. print(transcript) except HTTPStatusError: print('Invalid API key - Check your API_KEY at the top of the code!') The code uses a file as an argument for the submit_job function. I want to submit a job, with fetch_data that uses a URL instead of a local file. However, the submit_job function requires an audio argument. I just want to use fetch_data option as given here and no audio argument as given below : conf = { "type": "transcription", "transcription_config": { … -
Reverse for 'submit_review' with no arguments not found. 1 pattern(s) tried: ['submit_review/(?P<game_id>[0-9]+)/\\Z']
l got an error when trying to create the form for Star Ratings, to me l have failed to get the mistake for the erroor it returns. so, am requesting anyone who knows, to help me and solve that error, thanks I'm Samuel Below is the browser error NoReverseMatch at /action/3444/ Reverse for 'submit_review' with no arguments not found. 1 pattern(s) tried: ['submit_review/(?P<game_id>[0-9]+)/\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/action/3444/ Django Version: 4.1.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'submit_review' with no arguments not found. 1 pattern(s) tried: ['submit_review/(?P<game_id>[0-9]+)/\\Z'] Exception Location: C:\N2G-PROJECT\venv\lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix Raised during: Action.views.action_description Python Executable: C:\N2G-PROJECT\venv\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\\n2g-project\\my_site', 'C:\\Users\\AdminSb\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\AdminSb\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\AdminSb\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\AdminSb\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\N2G-PROJECT\\venv', 'C:\\N2G-PROJECT\\venv\\lib\\site-packages'] Server time: Tue, 28 Mar 2023 22:52:52 +0000 Below are my Code editor codes (Vs code) **#Action/urls.py** urlpatterns = [ path('action', views.action , name='action'), path('action/<slug:description>/', views.action_description, name='action_description'), path('submit_review/<int:game_id>/', views.submit_review, name='submit_review') ] **#Action/forms.py** class Game_ReviewForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'placeholder': "write Review"})) class Meta: model= ActionReview fields=['subject','content','stars'] **#Action/views.py** def submit_review(request,game_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ActionReview.objects.get(user__id=request.user.id, game_name__id=game_id) form = Game_ReviewForm(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you! , Your review has been Updated Successfully.') return redirect(url) except ActionReview.DoesNotExist: form =Game_ReviewForm(request.POST) if form.is_valid(): data=ActionReview() data.subject = form.cleaned_data['subject'] … -
Django automated runserver and functional test
Im trying to use invoke module to automate my django functional tests, but I realised as the runserver command is rolling on my script waits until its finished to run the next command from invoke import task @task def runserver(c): c.run('python manage.py runserver') @task def test(c): c.run('python functional_test.py') @task(runserver, test) def build(c): pass I wanted to run both simultaneously, maybe with async or threding but cant figure out how. -
Django tutorial urls.py problems
I can only seem to get the initial Django landing page, no matter what I try. I feel like I understand the way it should work but there is obviously something wrong. I have tried the polls tutorial and several others on youtube and I am constantly having the same problem where the urls.py doesn't seem to include the things I believe to be in there. Any help would be greatly appreciated. mysite/mysite/urls.py# from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include('polls.urls')), path("admin/", admin.site.urls), ] mysite/polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] mysite/polls/views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def index(request): return HttpResponse("Hello, world!") -
Serialize several models in Django
I am looking to optimize the serialization of multiple models. Currently, I am able to serialize the models through the use of SerializerMethodField and providing the needed fields. I would like to use directly the serializer SiteSchoolSerializer to fetch in advance the results using queryset.select_related to reduce the time of the queries. I have the models: site.py: class SchoolDistance(models.Model): school_id = models.ForeignKey(School, on_delete=models.SET_NULL, db_column="school_id", null=True) school_distance = models.DecimalField(max_digits=16, decimal_places=4, blank=False, null=False) class Site(models.Model): date_created = models.DateTimeField(auto_now=False, blank=True, null=True) address = models.CharField(max_length=255, null=True, blank=True) nearest_school = models.ForeignKey(SchoolDistance, on_delete=models.SET_NULL, db_column="nearest_school", blank=True, null=True) ------------------ location_asset.py: class Location(models.Model): name = models.CharField(null=True, blank=True, max_length=255) location_type = models.CharField(null=True, blank=True, max_length=255) class Meta: unique_together = [['name','location_type']] ordering = ("id", ) class School(Location): description = models.CharField(null=True, blank=True, max_length=255) keywords = models.CharField(null=True, blank=True, max_length=255) class Meta: ordering = ("id", ) With the following serializers: distance.py class SiteSchoolSerializer(serializers.ModelSerializer): class Meta: #school = SchoolSerializer() model = SchoolDistance #fields = ('school_id', 'school_distance','school) why failing? fields = ('school_id', 'school_distance') ------------------ location_types.py: class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ( "id", "name" ) -------- get.py: class SiteGetSerializer(serializers.ModelSerializer): # nearest_school = serializers.SerializerMethodField() nearest_school = SiteSchoolSerializer(required=False) class Meta: model = Site fields = ( "id", "address", "nearest_school", #Should include name besides id and distance … -
CS50W - Network - Like Button working but Like count is not updating
I am currently working on Project4 from CS50W. The task is to write a social media like site where users can post, follow and like. I have implemented a like button to every post (which is wokring fine) unfortunately I have to refresh the page for the like to show. I whould rather want the like to update directly after clicking the like button. I am creating the div for the posts via Javascript and calling the like_post function onclick function load_posts() { // get posts from /posts API Route fetch('/all_posts') .then(response => response.json()) .then(posts => { // create a div element for each post posts.forEach(post => { let div = document.createElement('div'); div.className = "card post-card"; div.innerHTML = ` <div class="card-body"> <h5 class="card-title">${post['username']}</h5> <h6 class="card-subtitle mb-2 text-muted">${post['timestamp']}</h6> <p class="card-text">${post['text']}</p> <button class="card-text like-button" onclick="like_post(${post.id});"><h3> ♥ </button> </h3> ${post['likes']} </div> `; // append div to posts-view document.querySelector('#posts-view').append(div); }); }); } function like_post(post_id) { fetch('/post/' + post_id, { method: 'PUT', body: JSON.stringify({ like: true }) }); } this is my view funtion to handle most post related requests @csrf_exempt @login_required def post(request, post_id): # Query for requested post try: post = Post.objects.get(pk=post_id) user = User.objects.get(username=request.user) except Post.DoesNotExist: return JsonResponse({"error": "Post not found."}, status=404) … -
Django form validation fails because of some DateTimeForm field problem
I'm trying to process data from the form which adds a news item to the site. Here is the form (forms.py) class AddnewsForm(forms.Form): title = forms.CharField( label="Headline", widget=forms.TextInput, max_length=50, required=True, help_text="Write your headline here", validators=[validators.MinLengthValidator(3), validators.MaxLengthValidator(50)], ) summary = forms.CharField( label="Summary", widget=forms.Textarea(attrs={'rows':3}), required=True, help_text="Annotate your item", validators=[validators.MinLengthValidator(10), validators.MaxLengthValidator(100)], ) contenttext = forms.CharField( label="Content", widget=forms.Textarea(attrs={'rows':7}), required=True, help_text="Write your content here", validators=[validators.MinLengthValidator(10), validators.MaxLengthValidator(1000)], ) author = forms.CharField( label="Author", widget=forms.TextInput, max_length=50, required=True, disabled=True, help_text="This field is generated automatically", ) created = forms.DateTimeField( label="Creation timestamp", widget=forms.DateTimeInput, required=True, disabled=True, help_text="This field is generated automatically", ) show = forms.BooleanField( label="Publish", widget=forms.CheckboxInput, required=False, disabled=True, ) def __init__(self, curus, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'addnews' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = '/news/add' self.helper.add_input(Submit('submit', 'Submit')) self.helper.layout = Layout( HTML(""" <h2 style="font-family: 'Segoe UI'; text-align: center; color: #060942">Let us create an item:</h2> """), Div( 'title', 'created', 'author', 'summary', 'contenttext', 'show', style="margin-left: 5px", css_class='was-validated', ) ) self.fields['author'].queryset = curus self.fields['author'].initial = curus self.fields['created'].initial = datetime.datetime.now self.fields['show'].initial = 1 class Meta: model = News fields = ['title', 'created', 'author', 'summary', 'contenttext', 'show'] and the related model (model.py) class News(models.Model): itemid = models.IntegerField(db_column='ItemID', primary_key=True) title = models.CharField(db_column='Title', max_length=50, blank=True, null=True) summary = models.TextField(db_column='Summary', blank=True, null=True) contenttext = … -
Celery works from terminal but not with supervisorctl
Anyone please can give me a help here? Running: celery -A app worker --loglevel=info from my backend folder, directly from terminal works fine, but when I try to set supervisor to run, it does not work at all: I tried the .conf like this: [program:celery_worker] directory=/var/www/html/appfolder/backend/ command=/var/www/html/appfolder/backend/venv/bin/celery -A app worker --loglevel=info user=root stdout_logfile=/root/logs/gunicorn-error.log redirect_stderr=true numprocs=1 autostart=true autorestart=true startsecs=10 stopwaitsecs=600 stopasgroup=true priority=998 And when I see the Tail: supervisor: couldn't exec /var/www/html/appfolder/backend/venv/bin/celery: ENOENT supervisor: child process was not spawned I have already tried the command like this: /root/scripts/celery_worker_start and then, the celery_worker_start like this: #!/bin/bash NAME="Celery Worker" PROJECT_DIR=/var/www/html/appfolder/backend/ VENV_DIR=/var/www/html/appfolder/backend/venv/ echo "Starting $NAME as `whoami`" # Activate the virtual environment source "${VENV_DIR}/bin/activate" cd "${PROJECT_DIR}" if [ -d "${VENV_DIR}" ] then celery -A app worker --loglevel=info fi But it does not work at all: Starting Celery Worker as root /root/scripts/celery_worker_start: 17: celery: not found -
Django URLs returning 404 page not found error after adding a trailing slash
I am working on a Django project and I am having some trouble with the URLs. I recently added a trailing slash to the URLs in my "urls.py" file for the app(I have only one), and now i'm getting a "Page not found (404)" error whenever I try to access anypage (only "http://127.0.0.1:8000/HomeS" works). I want to access studio page(or any) without the "HomeS" . It works if I enter the url manually.(for example : http://127.0.0.1:8000/studio ) I get a "Page not found (404)" error. Here's the error message that I see:Error page I have checked my code and I believe that my URLs are correctly defined. Here relevant part of my "url.py" file : url.py I have tried restarting the server, clearing the cache, and even creating a new virtual environment, but the error persists. I would appreciate any help in resolving this issue. Thank you. -
How to get a customer ID from event object (webhooks) in stripe using Django?
I can't find where is the the customer id when I receive an avent from Stripe webhooks after a transaction was made: @csrf_exempt def StripeWebhookView(request): CHECKOUT_SESSION_COMPLETED = "checkout.session.completed" payload = request.body sig_header = request.META["HTTP_STRIPE_SIGNATURE"] endpoint_secret='whsec_o0T4qLvSeI0kjhpUs2JcHq9F0Ik9VUeY' try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) if event["type"] == CHECKOUT_SESSION_COMPLETED: **customer_id_stripe = event["data"]["object"]["customer"]** print('customer_id:', customer_id_stripe) I have tried to fetch the customer id by using this line of code: **customer_id_stripe = event["data"]["object"]["customer"]** but when I print customer_id_stripe it print None and to be honest, when I check out the full object I recieved from Stripe this is what I get: { "id": "evt_1MqMKgESXHNK1nmVaYJeR1PX", "object": "event", "api_version": "2022-11-15", "created": 1679947678, "data": { "object": { "id": "cs_test_a1A15S4eEOZc3WPfyTT5aJeGhhXRi5DK8xQiRnbgs8iG16rZ8oN032V8rm", "object": "checkout.session", "after_expiration": null, "allow_promotion_codes": null, "amount_subtotal": 50, "amount_total": 50, "automatic_tax": { "enabled": false, "status": null }, "billing_address_collection": null, "cancel_url": "http://127.0.0.1:8000/discovery/", "client_reference_id": null, "consent": null, "consent_collection": null, "created": 1679947653, "currency": "usd", "custom_fields": [ ], "custom_text": { "shipping_address": null, "submit": null }, # **"customer": null,** "customer_creation": "if_required", "customer_details": { "address": { "city": null, "country": "IL", "line1": null, "line2": null, "postal_code": null, "state": null }, "email": "anon@gmail.com", "name": "asdasd", "phone": null, "tax_exempt": "none", "tax_ids": [ ] }, "customer_email": null, "expires_at": 1680034053, "invoice": null, "invoice_creation": { "enabled": false, "invoice_data": { "account_tax_ids": … -
When using Django's Prefetch object, it makes one query per related object
So I've been developing with Django for a while. I am familiar with prefetch_related and was noticing some strange behavior today when working with Prefetch objects. I was under the impression that a queryset executed with prefetch_related would make 2 queries, 1 for the parent objects, and another for the children filtering on the parent object ids. However, when I print the queries being executed using pretch_related with a Prefetch object, I noticed that one query was being made per related object which diminishes the desired effect of prefetch_related. Can anyone fill me in to why this is happening based on the following code and returned SQL. Schedule.objects.prefetch_related("shifts") # SQL returned [{"sql": 'SELECT "schedule"."id" FROM "schedule" LIMIT 21', "time": "0.033"}, { "sql": 'SELECT "shift"."id" FROM "shift" WHERE "shift"."shift_id" IN (1, 2) ORDER BY "shift"."order" ASC', "time": "0.062", } ] The above is what I expected Now the problem queryset Schedule.objects.prefetch_related( Prefetch( "shifts", queryset=Shift.objects.filter( state__in=[StopPointStates.COMPLETED, StopPointStates.PENDING] ) .order_by("assigned_at", "priority", "order") .only("id"), ) ).only("id") # SQL returned [{"sql": 'SELECT "schedule"."id" FROM "schedule" LIMIT 21', "time": "0.009"}, { "sql": 'SELECT "shift"."id" FROM "shift" WHERE ("shift"."state" IN (\'completed\', \'pending\') AND "shift"."shift_id" IN (1, 2)) ORDER BY "shift"."assigned_at" ASC, "shift"."priority" ASC, "shift"."order" ASC', "time": "0.015", … -
Uploading Django project to Heroku - blank page showing Internal server error
So I've deployed my first project to Heroku using PostgresQL. To my excitement, I managed to upload my files to both Github and Heroku. But to my disappointment, when I open the website, I only see a page showing "Internal Server Error". Why does this error show and how can I resolve it? I've been spending 9 month learning, HTML, CSS, Java, Python, Django, React, Bootstrap. This is the last step before I have a page online. So I appreciate all help! My project settings: """ Django settings for my_portfolio_project project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from dotenv import load_dotenv BASE_DIR = Path(__file__).resolve().parent.parent load_dotenv() # env = environ.Env() # # Reading the .env-file # environ.Env.read_env("\my_portfolio_project\.env") # Build paths inside the project like this: BASE_DIR / 'subdir'. # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Make sure your SECRET_KEY setting is set to a unique, strong, and secure value. Don't use the default value … -
gdal required on django but why?
I imported 3 tables on to my postgresql. These tables have the names of countries, regions, cities and then IP to countries. They are pretty old but very exhaustive. In my models I have not created any geo field or any point field, the latitude and longitude were expressed as float fields and I did that precisely to avoid having to install libraries. Yet, when I was writing makemigrations, I got an error that I needed to install gdal library. Reluctantly I did, but then it asked me that I needed to install GLIBCXX_3.4.30 library. It turns out they are not available for Fedora. What is this lousy break? I am using Fedora 37 and I am pretty annoyed at this, because, why would django tell me that I have to install that? Has it detected that the tables in postgresql have city names, latitude and longitudes? they are expressed as float fields in the table cells. -
Djano page with two views
Mockup of page with two views How can I make a page like the one in the URL above? I tried to do it using a partial for the form, but I need help figuring out how to handle the URL routing. Is there a better way to do this? The first view is a Folium map. The second view in a ModelForm. I'm open to suggestions. I tried to make the form a partial. -
How can I use a property inside another property? Django
I have the following model with three properties to know the consumption according to the reading: class ConsElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='consumoelect') data= models.DateField(default=datetime.now) read_morning = models.IntegerField(default=0) read_day = mod def get_rm(self): c_m = list(ConsElect.objects.filter(data__gt=self.data).values('read_morning')[0:1]) return ((c_m[0]['read_morning '] - self.read_morning )) cons_m= property(get_rm) def get_rd(self): c_d = list(ConsElect.objects.filter(data__gt=self.data).values('read_day')[0:1]) return ((c_d[0]['read_day'] - self.read_day)) cons_d= property(get_rd) def get_total(self): #It's not correct, I don't know how to implement it return cons_d + cons_m #I need to get the sum of the above two properties I need a third property in the model to store the sum of the two previous properties, how can I call the two previous properties inside the new property -
Django/react authenticated user not being returned
I am trying to show user profile page when user is logged in.I tested it with postman and printed in terminal and it is working.I can login and a user object is returned and when I go to the user profile route it returns the posts of the logged in user.However,it is not working properly with react.I can login with react and the user is authenticated in in the backend but when I go to the user profile route the user id is retuned none and no post is showing even in the terminal. Here in postman it logs in and then for myprofile route is shows the user id and a list of his posts. Here I login with the same user using react and I can login successfully but when going to myprofile it returns none for user id and so empty queryset for posts. Django: urls.py from django.urls import path,include from . import views # from .views import ChangePasswordView urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.custom_login, name='login'), path('logout/', views.custom_logout, name='logout'), path('myprofile/', views.user_profile, name='user_profile'), path('edit_user/', views.edit_user_profile, name='edit_user_profile'), path('activate/<uidb64>/<token>', views.activate, name='activate'), path("passwordreset/", views.password_reset_request, name="password_reset1"), path('reset/<uidb64>/<token>/', views.passwordResetConfirm, name='password_reset_confirm'), path('password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')), ] views.py from django.contrib.auth.decorators import login_required from django.shortcuts … -
How can I implement authentication and authorization in a Django REST API using JSON Web Tokens (JWT)?
I am building a Django REST API and I want to add authentication and authorization to it. I have researched and found that JSON Web Tokens (JWT) is a popular solution for this purpose. However, I am having trouble implementing it in my Django API. Can someone please provide a step-by-step guide or code example on how to implement JWT authentication and authorization in a Django REST API? Thank you in advance for your help. I tried to implement JWT authentication and authorization in my Django REST API following several online tutorials and articles. I installed the necessary packages, such as Django Rest Framework JWT and PyJWT, and attempted to follow the provided code examples to configure my API for JWT authentication and authorization. -
I have an issue rendering image from database using django
``Images are rendering from other pages but nit rendering new page views.py def hotels(request): mhtl = Hotel.objects.all() context = { 'my_rms': mhtl, } return render(request,'affiliate/hotels.html', context) type here models.py class Hotel(models.Model): title = models.CharField(null=True, blank=True, max_length=100) price = models.CharField(null=True, blank=True, max_length=100) card_img = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return self.title` The html page {% extends 'affiliate/base.html' %} {% load static %} {% block content %} <h2>Find your next stay</h2> <h3>HERE</h3> <h5>--- WIDGET WIDGET WIDGET WIDGET ---</h5><hr> <!--CARDS--> {% for m in my_rms %} <img src="{{ m.card_img }}"> <h5>{{m.title}}</h5> <p>${{ m.price }}</p> {% endfor %} <hr> {% endblock content %} other datas are rendering except the image and the message from the terminal is: [28/Mar/2023 10:17:48] "GET /hotels/images/ht7.jpg HTTP/1.1" 404 2991 Not Found: /hotels/images/ht7.jpg I am trying to find a way to resolve this please I tried a for lood to retrieve data from a specific model otherdatas are rendering only image is not.`