Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having issue with xhr.send(blob) for Django, sending audio file
I am trying to send the blob to the backend but it failed. Code for views.py @login_required @ensure_csrf_cookie @require_http_methods({"GET","POST"}) def record_audio(request: HttpRequest) -> HttpResponse: if request.method == "GET": return render(request, 'recording/record.html') blob= request.FILES.get("blob", None) if blob is None: return HttpResponseBadRequest("Missing audio-blob parameter") now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") filename = f"{request.user.username}_{now}.wav" filepath = Path.joinpath(settings.MEDIA_ROOT, "recordings",filename) with open(filepath, 'wb') as audio_file: for chunk in blob.chunks(): audio_file.write(chunk) return HttpResponse(status=HTTPStatus.NO_CONTENT) Code for the sending blob part: var csrftoken = getCookie('csrftoken'); var xhr = new XMLHttpRequest(); xhr.open('POST', '/record-audio/', true); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.setRequestHeader("MyCustomHeader", "Put anything you need in here, like an ID"); // console.log(blob) // downloadBlob(blob) xhr.send(blob); I am also using the jquery-1.12.3.js -
Multi Database Architecture in Django
in my Django project, I have database architecture requirements like this users and organization details are stored in a single DB here that I named as auth_db and each organization may have its independent DB or multiple organization has a single DB this project follows a monolith architecture, all databases are configured in a single project. to achieve these I create two db routers and a middleware before that I store the db name in the auth_db the db name should be present in the request.user.organization.db_name, and all the databases are already configured inside the settings class AuthDBRouter: route_app_labels = {'auth', 'contenttypes', 'sessions', 'admin', 'user','organization', 'database'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return auth_db return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return auth_db return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == auth_db return None from django.utils.deprecation import MiddlewareMixin from rest_framework_simplejwt import authentication import threading from django.conf import settings THREAD_LOCAL = threading.local() class DBSelectionMiddleware(MiddlewareMixin): def process_request(self, request): user = authentication.JWTAuthentication().authenticate(request) if user: user = user[0] if user and not user.is_anonymous … -
Django-import-export is not getting imported in admin.py
I am trying to use django-import-export library to provide excel data upload action in the admin panel. I have done following pip install django-import-export Have added it to installed apps INSTALLED_APPS = ( ... 'import_export',) Have collected staticfiles python manage.py collectstatic However now when I am trying to import import_export in admin.py, It is showing an error that module is not found. Image of admin.py I have checked I am in same virtual environment. PIP freeze shows that the module django-import-export is installed in the virtual environment. PIP Freeze image Can someone help with what I am doing wrong here -
Optimize code and some bug with double click submit
my first question is some optimize and better clean code, one if inside view is used twice in another view, so how can i modify my code to cleaner code and second question is about when tried sumbit that views in template i need click twice submit button to add into db, when i click one nothing add and second time is like everything working, can someone tell me wheres some error def manual_montage_add(request: HttpRequest) -> HttpResponse: form_montage = forms.DailyMontageManualForm( request.GET or None, request=request ) formset = forms.MonterManualDailyFormset( queryset=MonterDailyHours.objects.none() ) if request.method == "GET": form_montage = forms.DailyMontageManualForm( request.GET or None, request=request ) formset = forms.MonterManualDailyFormset( queryset=MonterDailyHours.objects.none() ) if request.method == "POST": form_montage = forms.DailyMontageManualForm( request.POST, request=request ) formset = forms.MonterManualDailyFormset(request.POST) try: if formset.is_valid() and form_montage.is_valid(): montage = form_montage.save(commit=False) montage.user = request.user montage.save() for form in formset: if form.is_valid(): monter = form.save(commit=False) monter.daily_montage = montage monter.date = montage["date"].value() if ( form["status"].value() == "URLOP" or form["status"].value() == "L4" or form["status"].value() == "UŻ" ): start = "08:00:00" end = "16:00:00" monter.start_work = datetime.datetime.strptime( start, "%H:%M:%S" ) monter.end_work = datetime.datetime.strptime( end, "%H:%M:%S" ) monter.daily_hours = datetime.datetime.strptime( start, "%H:%M:%S" ) else: monter.start_work = form.cleaned_data["start_work"] monter.end_work = form.cleaned_data["end_work"] obj = calc_function( form.cleaned_data["start_work"], form.cleaned_data["end_work"], ) monter.sum_work = … -
Django can't connect to MySQL in Docker+Django+MySQL
I'm trying to pack my working student application into containers. Here is my docker-compose.yaml: version: "3.8" services: mysql_db: build: context: . dockerfile: ./docker/mysql/Dockerfile restart: unless-stopped env_file: env.dev ports: - "33061:3306" networks: - autopark_network backend: build: context: . dockerfile: docker/django/Dockerfile env_file: env.dev restart: on-failure depends_on: - mysql_db working_dir: "/app/autopark" expose: - 800 ports: - "8001:8000" command: ["python3", "manage.py", "runserver", "0.0.0.0:8000"] networks: - autopark_network networks: autopark_network: Here is env.dev: DEBUG=1 SECRET_KEY=<...> DJANGO_ALLOWED_HOSTS="localhost 127.0.0.1 [::1]" MYSQL_ENGINE=django.contrib.gis.db.backends.mysql MYSQL_DATABASE=autopark MYSQL_DATABASE_HOST=mysql_db MYSQL_DATABASE_PORT=33061 MYSQL_ROOT_PASSWORD=<...> MYSQL_USER=pavel MYSQL_PASSWORD=<...> I thought that both of my services will get those environment variables so I can be sure everything is ok. As if. I need GDAL for my project, that's why I started backend not with python but with ubuntu (here's my Dockerfile for backend): FROM ubuntu:22.04 MAINTAINER Pavel Vasilev <pvlvslv@yandex.ru> RUN apt -y update RUN apt -y install python3-dev python3-pip gdal-bin gdal-data WORKDIR /app/autopark ADD . /app/autopark RUN pip install -r requirements.txt Then I need initialization for my mysql_db (here's my Dockerfile for mysql_db): FROM mysql/mysql-server:latest COPY ./docker/mysql/init_db.sh /docker-entrypoint-initdb.d/ COPY ./docker/mysql/init_db.sql /usr/local/ RUN chmod +x /docker-entrypoint-initdb.d/init_db.sh And here is init_db.sh: #!/bin/bash mysql -u root --password="$MYSQL_ROOT_PASSWORD" << EOF SOURCE /usr/local/init_db.sql USE ${MYSQL_DATABASE}; GRANT ALL PRIVILEGES ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'; EOF init_db.sql was … -
Django queryset grouping by a field
I have models Subject, Topic and Question like this: class Subject(models.Model): subject = models.CharField(max_length=200, unique=True) class Topic(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) topic = models.CharField(max_length=200, blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, topic = ChainedForeignKey( "Topic", chained_field="subject", chained_model_field="subject", show_all=False, auto_choose=True, ) I am filtering Question model like this: proc_subj = Question.objects.filter(approval_status="Approved").filter(subject__in=mysubjects).values('subject__subject', 'topic__topic') \ .order_by('subject__subject').distinct() This gives output like: <QuerySet [{'subject__subject': 'ss1', 'topic__topic': 'ICA1'}, {'subject__subject': 'ss1', 'topic__topic': 'ICA2'}, {'subject__subject': 'ss1', 'topic__topic': 'PDL ICA-2'}, {'subject__subject': 'ss2', 'topic__topic': 'Structural lines of hard tissues of teeth'}, {'subject__subject': 'ss2', 'topic__topic': 'Oral mucosa ICA-2'}, {'subject__subject': 'ss3', 'topic__topic': 'Salivary glands ICA-2'}, {'subject__subject': 'ss3', 'topic__topic': 'POST ICA-2 Dental morphology/eruption & shedding'}]> If we look at the above query set ss1 as a subject there are three entries. I want to regroup based on similar subjects and get output like the below: <QuerySet [{'subject__subject': 'ss1', 'topic__topic': 'ICA1', 'topic__topic': 'ICA2', 'topic__topic': 'PDL ICA-2'}, {'subject__subject': 'ss2', 'topic__topic': 'Structural lines', 'topic__topic': 'Oral mucosa'}, {'subject__subject': 'ss3', 'topic__topic': 'Salivary glands ICA-2''topic__topic': 'POST ICA-2'}]> I tried by adding .grouped_by(subject__subject) also I tried template regroup tag both did not give me the desired results. Any one please give me a hand? The reason I am trying is to create a option grouped multi select list like this: -
how to deploy django (apiview ) web application in ec2 ? with DateaBase but without using frim AWS-RDS ? (is this for test deploy ment )?
I can deploy the Django from ec2. but I need from DB how can i connect DB without RDS-AWS its just testing deployment and I can't spend money because I am a student, please any one can show the answer ? some of them instruct me to create dB inside your ec2 but I can't have good knowledge and no other's tutorials. please help me to find the answer ? -
Django rest framework slow response time
I am working on a project. I am using Django rest framework. I have a category model. And there is only 2 rows. And the api response time is 180 ms avarage. it is too slow for only 2 rows. And api is very simple. Why it is too slow for such a simple api. here is my view class CategoryListView(generics.ListAPIView): queryset = Category.objects.order_by('order').all() serializer_class = CategorySerializer def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) print(queryset.query) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) here is my serializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ("id", "name", "order") And here is the query generated. SELECT "questions_category"."id", "questions_category"."created_at", "questions_category"."updated_at", "questions_category"."name", "questions_category"."name_tk", "questions_category"."name_ru", "questions_category"."icon", "questions_category"."order" FROM "questions_category" ORDER BY "questions_category"."order" ASC I am analyzing it with django-silk query time is 6 ms. but response time is 180 ms Could somebody help me with this? -
Profile matching query does not exist
I am following a tutorial on building a social media app using django. I have this bug that has kept me stuck for days despite doing exactly as the tutorial goes. Whenever i try to open the settings page of my profile, I get a doesNotExist error. the error seems to be coming from here " user_profile = Profile.objects.get(user=request.user) " This the views for my settings page @login_required(login_url='signin') def settings(request): # Check if logged in user has profile, if not redirect to create profile user_profile = Profile.objects.get(user=request.user) return render(request, 'settings.html', {'user_profile': user_profile}) Sometimes I get an error about the profile_img not being found. Although i couldn't get it to repeat itself at the time of asking for help here. But when I commented out the profile_img line in my modles.py, the error changed back to 'profile not matching query' This my models.py class Profile(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) location = models.CharField(max_length=150, blank=True) profile_img = models.ImageField(upload_to='profile_images', default='blank_profile_image.jpeg') However, removing the link to to my modles.py seems to make the settings page accessible. @login_required(login_url='signin') def settings(request): # Check if logged in user has profile, if not redirect to create profile #user_profile = Profile.objects.get(user=request.user) … -
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.