Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I properly configure `drf-spectacular` in my Django projects
I simply installed and configured drf-spectacular in my Django project, but when I visit the url http://127.0.0.1:8000/api/v1/schema/, Django throws this error. TypeError at /api/v1/schema/ Field 'id' expected a number but got <django.db.models.fields.related.ForeignKey: school>. This is my root urls.py file from django.contrib import admin from django.urls import path, include from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('schools.urls')), path('api/v1/years-terms/', include('years_terms.urls')), path('api/v1/schema/', SpectacularAPIView.as_view(), name='schema'), path('api/v1/schema/redoc/', SpectacularRedocView.as_view(url_name="schema", ), name='redoc'), path('api/v1/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name="schema"), name='swagger-ui'), ] In my settings.py file, I have this SPECTACULAR_SETTINGS = { "TITLE": "School Veil API Project", "DESCRIPTION": "A school management system", "VERSION": "1.0.0", } What could possibly be wrong? -
Whenever I try to execute django-admin command: +FullyQualifiedErrorId: CommandNotFoundException error
Every time when I install something on CMD, for example, Flutter, Python, or Django, I get this problem: This time when I try to execute django-admin startproject pyshop . django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin startproject pyshop . + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException And I already checked everything, such as dictation, such as the installation path I added it to Edit the system environment variables, and I checked the status of the Django installation, and they are all good, with no problems, yet the error appears again, and I watched almost all the educational videos or read almost all the articles, but it didn't work, it's Annoying, isn't it? What is the solution to this problem, please? I already checked everything, such as dictation, such as the installation path I added it to Edit the system environment variables, and I checked the status of the Django installation, and they are all good, with no problems -
how to serve static file in deplyment?
i have a django rest framework project which serve some endpoint.i deploy it on a linux server.But it is dosen't show any static file of django rest framework.In my project hasn't any static file.My nginx config is following server { listen 80; server_name 192.168.31.50; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django JSONField store timetable data and query only open businesses
Hi in my Django backend I need to store business's timetable and I do it through a JSONField like the example below: [ { "times":[ [ "7:00", "9:00" ], [ "", "" ] ], "closed":false }, { "times":[ [ "7:00", "9:00" ], [ "", "" ] ], "closed":false }, { "times":[ [ "7:00", "9:00" ], [ "", "" ] ], "closed":false }, ... ] Then I need to create a query to get all the opened businesses in a corresponding user_time at a day of current_day_index. How can I index the json, for example index = 0 => "Monday", to select the timetable for that specific day and then compare the user_time with the elements in the array "times" and check if the business is open or not? Are there better solutions to achieve this behaviour to store timetable data? Thank you -
I have an error during the session, code 400, message Bad request version ('')
Let's me explain that. Few days ago I installed a django app with docker, I had no problem with that, and later I tried to add a security for settings.py and now I have an error code 400, message Bad request version ('') You're accessing the development server over HTTPS, but it only supports HTTP. and now when I start creating new app I have a same error but I did not add security for new app So my files db.sqlite3 manage.py requirements.txt src venv I am using django 4.0 with psycopg 2.9.3 Next, when I am going to run a server python manage.py runserver I have seen that Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 27, 2023 - 09:17:44 Django version 4.0, using settings 'src.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I log in to the server http://127.0.0.1:8000/ I see on browser this https://localhost:8000/ and a same error code 400 Shoud i delete a docker? … -
I want to generate a form based on the previous form using django and html css javascript
suppose I am filling a form which has two entry: department(comps, extc, etrx, it) and year(fy, sy, ty). based on this form I want to generate a template of credit scheme table form Suppose user filled comps and fy then generate a credit scheme table form for that department and year and if user chooses extc and sy then generate new credit scheme table form. and if user again chooses comps and fy then generate previously generated credit scheme table form. I have one credit scheme table form. I have one form which has department and year as input How should I do this task. -
django (djangorestframework-simplejwt) : How to set up SIGNING_KEY value different for each user
I am using djangorestframework-simplejwt for setting up the jwt token based authentication In my user model i have column jwt_secret = models.UUIDField(editable=False, default=uuid.uuid4) I wanted to use different jwt_secret for each token user. So in future if i want to logoff a user from all places i can change this value In can see djangorestframework-simplejwt has a setting variable called SIGNING_KEY How to mention in the settings that it should use per user based SIGNING_KEY For more clearity -
Wagtail Change Image signal
Its my signal for cropping original images. Its work well in upload, but don't work when i change image in 'wagtail.images.views.images.edit'. /wagtail.hooks.py/ import os from django.db.models.signals import post_save from django.dispatch import receiver from wagtail.images import get_image_model ImageModel = get_image_model() @receiver(post_save, sender=ImageModel) def optimize_image_storage(sender, instance, created=False, **kwargs): if created: croped_image = instance.get_rendition('max-2000x2000|jpegquality-80') croped_file = croped_image.file.path original_file = instance.file.path try: os.rename(croped_file, original_file) except FileExistsError: # windows error os.replace(croped_file, original_file) instance.width = croped_image.width instance.height = croped_image.height instance.file_size = os.path.getsize(original_file) instance.save() -
Django audio recording issue: receiving Bad Request error
I am really new to Django and also building an application. I am building an audio journaling application with Django. I am trying to make a recorder with Django, and I have receive a bad request error. The code: views.py @login_required def record_audio(request): print("11",request.method) print("1") if request.method == 'POST': print("2") if 'blob' not in request.POST: print(request.POST) print("3") return HttpResponseBadRequest('Missing audio-blob parameter') print("4") now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") print("5") filename = f"{request.user.username}_{now}.wav" print("6") file_path = os.path.join(settings.MEDIA_ROOT, filename) # Save the audio file to the server print("7") with open(file_path, 'wb') as f: f.write(request.POST['blob'].encode()) return HttpResponse(status=204) # Return a 204 No Content response else: print("8") return render(request, 'recording/record.html') record.html {% extends 'base.html' %} {% load static %} {% block content %} <h1>Recorder</h1> <section class="experiment" > <br> <h3> Send Message: Speech to text </h3> <button id="start-recording">Start</button> <button id="pause-recording" disabled>Pause</button> <button id="resume-recording" disabled>Resume</button> <button id="stop-recording" disabled>Stop</button> </section> <section class="experiment"> <div id="audios-container"></div> </section> {% include "chat_script.html" %} <script src="https://cdn.WebRTC-Experiment.com/MediaStreamRecorder.js"></script> <script src="{% static 'js/jquery-1.12.3.js' %}"></script> <!-- <script src="{% static 'js/bootstrap.min.js' %}"></script> --> <!-- <script src="{% static 'js/script.js' %}"></script> --> <!-- <div> <audio id="audio-player" controls></audio> </div> --> {% endblock %} urls.py path('record-audio/',views.record_audio,name="record_audio"), chat_script.html <script> function captureUserMedia(mediaConstraints, successCallback, errorCallback) { navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback); } var mediaConstraints = { audio: true }; document.querySelector('#start-recording').onclick = … -
Django sessions not saving data from form, no error or apparent reason
I have a view with different 'stages' (as I wanted to keep the same URL without resorting to something like AJAX), which takes data from a form, does some processing, and then would save that data to the database. Because I can't forward some data via POST, I wanted to save that data in a session. For some reason, this is not working - at all. I can see the data being extracted from the form, and I can forward that via POST, but attempting to save or retrieve it to a session either results in blank data, or a KeyError. This is the view I am using (very trimmed down, but the error is reproducible) def processpayment(request, *args, **kwargs): if request.method == 'POST': form = paymentDetailsForm(request.POST) amount = request.POST.get('amount', False); stage = request.POST.get('stage', False); if (stage == "checkout"): return render(request, "payment.html", {'form': form, 'amount': amount, 'stage': stage}) if (stage == "complete"): return render(request, "payment.html", {'amount': request.session['amount'], 'stage': stage, 'name': request.session['name']}) if (amount == "custom"): if form.is_valid(): amount = form_data.get('amount') name = form_data.get('name') request.session['amount'] = amount request.session['name'] = name request.session.modified = True return render(request, "payment.html", {'form': form, 'stage': stage, 'amount': amount}) return render(request, "payment.html", {'amount': amount, 'stage': stage}) else: return … -
Django - How to make a relationship in Django that is related to a multiple ManyToManyField model
I am a django beginner. I have two models here that are used in another model as a ManyToManyField : In models.py : class Likelihoods(models.Model): Likelihood = models.CharField(primary_key=True, max_length=255) Param = models.CharField(max_length=255) class Consequences(models.Model): Consequence = models.CharField(primary_key=True, max_length=255) Param = models.CharField(max_length=255) class Inherent_risks(models.Model): Likelihood = models.ManyToManyField(Likelihoods, related_name= 'InherentRisk_Likelihood') Consequence = models.ManyToManyField(Consequences, related_name= 'InherentRisk_Consequence') After this, i added it to another model in order to create a form name Hira. class Hira(models.Model): Activity = models.CharField(max_length=255) Risk_Description = models.TextField(default="***") PBS = models.ManyToManyField(PBS) Physical_control = models.CharField(max_length=255) Administrative_control = models.CharField(max_length=255) Instrumented_control = models.CharField(max_length=255) Inherent_Risk = models.ForeignKey(Inherent_risks, on_delete=models.CASCADE, related_name='Inherent_risk' ) The form.py : class HiraForm(ModelForm): class Meta: model = Hira fields = '__all__' The question : The form i am getting I can't choose both a likelihood and a consequence (not even any data). What am I doing wrong ? -
How to use django oram to implement oracle wm_concat query
In oracle, I can use wm_concat to implement row-to-column conversion, as follows: SELECT * FROM STU_TEST name project Alice Machine Learning Alice Data Science Bob Web Development Bob Mobile Development Carol Data Science Carol Cloud Computing David Artificial Intelligence SELECT NAME,wm_concat(PROJECT) FROM STU_TEST GROUP BY NAME name wm_concat(PROJECT) Alice Machine Learning,Data Science Bob Web Development,Mobile Development Carol Data Science,Cloud Computing David Artificial Intelligence I want to implement this query using django orm, I tried the following, without success. 它返回了错误:cx_Oracle.DatabaseError: ORA-00937: not a single-group group function from django.db.models import CharField, Value from django.db.models.functions import Concat from django.db.models.aggregates import Count from myapp.models import StuTest from django.db.models import Func class GroupConcat(Func): function = 'LISTAGG' template = '%(function)s(%(expressions)s, \',\') WITHIN GROUP (ORDER BY %(expressions)s)' results = StuTest.objects.values('name').annotate(project_concat=GroupConcat('project')).order_by('name') for result in results: print(result['name'], result['project_concat']) How to implement this query? (In the actual environment, group by may not only include the name field, but also other fields) -
HTML element src attributes sends concatenated string to server
I have a ReactJs and Django project setup. I send a GET request to my localhost for localhost/index, the server running my Django project returns index.html which is correct. The index.html has a html element with src value "asset/script.js". It sends a request to Locahost/index/asset/script.js instead of Localhost/asset/script.js. Sometimes it sends the first path, sometimes the last path. why? Debugging, not sure whyt it doesnt work -
How to do pagination in Django? I have TypeError
I want to do pagination on my site. I do API-call to supplier's website. I get data, deserialize and save it in my model, then get those objects for view them. Also I get all unique names for query into model and error in that function. When I press "Next page" everything breaks. Before pagination everything works. view.py def search(request): url_for_search = 'http://ws.armtek.ru/api/ws_search/search?format=json' template = 'profiles/search.html' if request.method == 'GET': # API-call searched = request.GET.get('searched') headers = { 'Authorization' : basic_auth(login, password)} params = {some_params} res = requests.post(url_for_search,headers=headers,data=params) if 200 <= res.status_code < 300 : # Deserialize serializer = ProfileSerializer(data=res.json()['RESP'],many = True) serializer.is_valid() serializer.save() # Getting data names = get_unique_names(res.json()) number_products = len(res.json()['RESP']) products = Profile.objects.filter(NAME__in = names).distinct()[:number_products] # Pagination p = Paginator(Profile.objects.filter(NAME__in = names).distinct()[:number_products],10) page = request.GET.get('page') page_obj = p.get_page(page) return render(request, template, {"products":products, "page_obj":page_obj, 'searched':searched}) else: return HttpResponse('Error') get_unique_names() def get_unique_names(res_json): names = set([ item['NAME'] for item in res_json['RESP']]) return names ERROR in that line: names = set([ item['NAME'] for item in res_json['RESP']]) I dont want to do. Maybe I should do it with ListViev? but i don't sure, that it's gonna help -
unable to retrieve the refresh data from django view to html
I have issue fetching the data to html with Ajax , however I am getting correct output in my django view. Scenario: I have two filter on webpage 1st is to select the Project and 2nd is date range. 1st Scenario: whenever I am selecting the project I am able to get proper output to webpage but whenever I am trying to select the dates with project , I am able to get the output in my django view but not able to fetch the same to HTML. below is the script I am trying for ajax. <script> document .getElementById("inputproject") .addEventListener("change", function () { document.getElementById("project-form").submit(); }); //Date range as a button $("#daterange-btn").daterangepicker( { ranges: { {% comment %} Today: [moment(), moment()], {% endcomment %} Yesterday: [moment().subtract(1, "days"), moment().subtract(1, "days")], "Last 7 Days": [moment().subtract(6, "days"), moment()], "Last 30 Days": [moment().subtract(29, "days"), moment()], "This Month": [moment().startOf("month"), moment().endOf("month")], "Last Month": [ moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month"), ], }, startDate: moment().subtract(29, "days"), endDate: moment(), }, function (start, end) { // Update the selected date range in the span element $("#selected-range").html( start.format("YYYY-MM-DD") + " - " + end.format("YYYY-MM-DD") ); // Get the selected project from the form const project = $("#inputproject").val(); // Create an object with … -
Djang-select2 breaking adaptive page
Im using django-select2 and i have 2 loading js files "select2.full.min.js" and "django_select2.js" and if they`re both enabled it breaks my adaptive page and i got this: If i turn off one of them in chrome developer tools pages works fine but i cant understand what`s the problem Im loading this with form.media.js template.html {% block content %} {{ form.media.css }} <div class="container mt-3"> <form action="{% url 'create_worklog' %}" method="post"> {% csrf_token %} <p class="mb-3">{{ form.worklog_date.label }}:</p> <div class="input-group " id="id_worklog_date" data-td-target-input="nearest" data-td-target-toggle="nearest"> {% render_field form.worklog_date|add_class:"form-control" type='text' data-td-target="#id_worklog_date" %} <span class="input-group-text" data-td-target="#id_worklog_date" data-td-toggle="datetimepicker"> <i class="fas fa-calendar"></i> </span> </div> <div class="mt-3 mb-3"> <p class="mb-3">Контрагент:</p> {% render_field form.contractor_counter|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Объект:</p> {% render_field form.contractor_object|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Разделы:</p> {% render_field form.contractor_section|add_class:"w-100" %} </div> <div class="mt-3 mb-3"> <p class="mb-3">Описание:</p> {% render_field form.description|add_class:"form-control" %} </div> <div class="form-footer text-center"> <button type="submit" class="btn btn-primary w-50">Создать</button> </div> </form> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> {{ form.media.js }} {% endblock %} -
Django inline formset missing_management_form error when deleting item
I am using an inline formset in a Django project and I keep getting a "missing_management_form" error when I submit the form. This happens only when I trying to delete item and hit Save button, it works well if I add new items. Exact error message: {'missing_management_form': 'ManagementForm data is missing or has been tampered with. Missing fields: %(field_names)s. You may need to file a bug report if the issue persists.'} Here is my code: # views.py from django.views.generic.edit import CreateView, UpdateView from django.db import transaction from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin from django.shortcuts import get_object_or_404 from .forms import OrderForm, OrderItemFormset from .models import Order, OrderItem class OrderCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Order form_class = OrderForm template_name = 'add_order.html' success_message = "Order created successfully!" def form_valid(self, form): context = self.get_context_data() order_item_formset = context['order_item_formset'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if order_item_formset.is_valid(): order_item_formset.instance = self.object order_item_formset.save() return super().form_valid(form) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: order_item_formset = OrderItemFormset(self.request.POST, instance=self.object) else: order_item_formset = OrderItemFormset(instance=self.object) data['order_item_formset'] = order_item_formset return data def get_success_url(self): return reverse('edit_order', kwargs={'pk': self.object.pk}) class OrderUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Order form_class = OrderForm template_name = 'edit_order.html' success_message = "Order updated … -
is virtual environment only for development or even for running application
I am using ubuntu 22.04 with python 3.10.6 version. My Django application currently works on python 3.7 version and it gives issues in 3.10 version. I want to use virtual environment with python 3.7 version to make application run. If i run the application with Gunicorn for production, will it run 3.7 version of virtual environment of machine version of 3.10? My project uses Gunicorn, nginx and django. -
I am facing this issue in django framework
-while I am making a project in django django -admin startproject hello -I am facing this issue in django , while using this command server is not working -python manage.py runserver -server show this error: -python: can't open file 'manage.py': [Errno 2] No such file or directory -
How to get the date of last change from multiple Django models?
The environment is Django 4 and Python 3.10+. In the application there are multiple data models, each with 'created' and 'modified' DateTimeFields. I need to get the timestamp of last data modification - either creation of new object or modification of a existing one, for cache invalidation. Currently the code checks for the newest creation timestamp and is like this: from django.db.models import Max qs_1 = Model_1.objects.all() qs_2 = Model_2.objects.filter(active=True).order_by('created') qs_3 = Model_3.objects.filter(active=True).order_by('created') last = max(list((itertools.chain(list(queryset.aggregate(Max('created')).values()) for queryset in (qs_1, qs_2, qs_3) if queryset.count()))))[0] My questions are as follows: The expression to get the last creation date is quite convoluted. Is there a way to compute the latest timestamp over multiple models using the ORM alone? It can be done in pure SQL, so it should be possible in the ORM. How do I extend it to also compare the modified fields of the models? -
How can I access and insert values into a database in django?
This is my code: import sqlite3 def add(email, password): conn = sqlite3.connect('database.sqlite3') conn.execute(f"""insert into Users('email', 'password') Values('{email}', '{password}')""") conn.commit() conn.close() @csrf_exempt def save_enq(request): if request.method == 'POST': email = request.POST.get('email') passw = request.POST.get('password') add(email, passw) print("Done!") return render(request, 'index.html') # there is more code but it is irrelevant This is my DB: And this is my error: please help me, I am new to programming. Thank you. :) -
Is there any way to change python version in virtual environment on Windows PC?
The Python version of my windows pc is 3.10.9 but Client's live project python version is 3.8.0. I installed python 3.8.0 for the project but all the other project that I made with python3.10.9 got error. To use many version of python at windows pc is complicated you know. So I want to know is there any option to change my python in virtual environment for the project if I will install again python3.10.9? -
Django Forms two models with foreign key
I am trying to implement the booking function in my Django project. I have two models, one for the customer (Fordonsregister) and one for the service (FordonsService), a one to many relationship as one customer (ID is vehicle registration number: "regnr" which is the primary key in the customer model and the foreign key in the service model (code below). When a customer wants to book they click on a certain service (generated from the service types model (ServiceTypes, below) and get redirected by the urls.py to that specific service url. I would then like the customer to fill out only certain fields. The customer should only fill out the primary key, the foreign key in the form should be auto filled. the "typ" in the service model should be autto filled as the URL is different for the chosen service type. The models: from django.db import models # Create your models here. class Fordonsregister(models.Model): regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False) namn = models.CharField(max_length=255, null=True, blank=True) tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True) email = models.EmailField(null=True, blank=True) kund_sedan = models.DateTimeField(auto_now=True) kund_points = models.IntegerField(default=0) def __str__(self) -> str: return self.regnr class Meta: ordering = ['regnr'] verbose_name = 'Kunder' verbose_name_plural = … -
I can't load a .joblib file to my views.py on my django project
My .joblib file is in the same directory as views.py literally next to each other but views.py cannot load it and once I runserver FileNotFoundError is thrown. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import joblib @csrf_exempt def test(response): if response.method == 'POST': age = int(response.POST['age']) gender_str = str(response.POST['gender']) if gender_str == 'Male': gender_value = 1 else: gender_value = 0 openness = int(response.POST['openness']) neuroticism = int(response.POST['neuroticism']) conscientiousness = int(response.POST['conscientiousness']) agreeableness = int(response.POST['agreeableness']) extraversion = int(response.POST['extraversion']) personality_values_1 = [[gender_value, age, openness, neuroticism, conscientiousness, agreeableness, extraversion]] theModel = joblib.load('PersonalityTestLogisticRegression.joblib') prediction = theModel.predict(personality_values_1) prediction_value = prediction[0] return render(response, "main/Review_Test.html", {'prediction':prediction_value}) I tried everything I can and I'm new to django. Pulling my hair rn. -
Cannot assign member "image_url" for type "Article" "Literal['http://default']" is incompatible with "property"
impot_data: from blog.models import Article def run(): for i in range(5,15): article= Article() article.title="Article num° #%d" % i article.desc="description article num° #%d" % i article.image_url ="http://default" print("opération réussie ")