Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django execute previous action on refresh
I have tried to add a book in to the database using an HTML form. After the submission, the page redirect to a page where all the books are listed .Then whenever I refresh the page , the data is became duplicated. How do i resolve this problem? This is my URLS.py from django.urls import path from . import views app_name='library' urlpatterns =[ path('', views.home, name='home'), path('book/',views.book,name='book'), path('book_details/<int:book_id>',views.book_details,name='book_details'), path('book_edit/<int:book_id>',views.book_edit,name='book_edit'), path('book_delete/<int:book_id>',views.book_delete,name='book_delete'), path('update/<int:book_id>',views.update,name='update'), path('author/',views.author_view,name='author_view'), path('addbook/',views.add_book,name='add_book'), path('books/',views.add_submit,name='add_submit'), ] This is my VIEWS.py def add_submit(request): if request.method =='POST': title=request.POST.get('t_title') print(title) author_name=request.POST.get('a_author') author, created=Author.objects.get_or_create(Name=author_name) summary=request.POST.get('s_summary') date=request.POST.get('d_date') book=Book(Title=title,Author=author,Summary=summary,Published_date=date) book.save() books=Book.objects.all() return render(request,'books.html',{'books':books}) #This is my FORM <form action="{% url 'library:add_submit' %}" method="POST"> {% csrf_token %} <div class="form-outline mb-4"> <input type="text" id="bname" name="t_title" class="form-control" /> <label class="form-label" for="bname">Title</label> </div> <div class="form-outline mb-4"> <input type="text" id="bauthor" name="a_author" class="form-control" /> <label class="form-label" for="bauthor">Author</label> </div> <div class="form-outline mb-4"> <textarea rows="5" cols="33" id="bsummary" name="s_summary" class="form-control"></textarea> <label class="form-label" for="bsummary">Summary</label> </div> <div class="form-outline mb-4"> <input type="date" placeholder="" id="pdate" name="d_date" class="form-control" /> <label class="form-label" for="pdate">Published_Date</label> </div> <!-- Submit button --> <button type="submit" class="btn btn-primary btn-block">SUBMIT</button> </form> -
AttributeError: 'tuple' object has no attribute 'model'. How to fix this error?
I'm new to Django. Please help me to solve this error. I'm not getting any solution. I tried many stackoverflow solutions and GitHub solutions but I'm not getting where the error is coming from. urls.py # from django.contrib import admin from django.urls import path, include from rest_framework import routers from user_profile.views import UserProfileViewSet, CoursesViewSet router = routers.DefaultRouter() router.register(r'user', UserProfileViewSet) router.register(r'courses', CoursesViewSet) urlpatterns = [ path('', include(router.urls)) ] models.py from django.db import models # Creating user profile model. class Courses(models.Model): courses = models.CharField(max_length= 100, blank=True) def __unicode__(self): return self.courses class UserProfile(models.Model): user_id = models.AutoField(primary_key = True) imgUrl = models.CharField() user_name = models.CharField(max_length=100) user_description = models.TextField() university_college = models.CharField(max_length=100) course = models.ForeignKey(Courses, blank=True, null=True, on_delete=models.CASCADE) views.py from django.shortcuts import render from rest_framework import viewsets from user_profile.models import Courses, UserProfile from user_profile.serializers import UserProfileSerializer, CoursesSerializer # Use these two when you'll create url of one class inside another class # from rest_framework.decorators import action # from rest_framework.response import Response class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all(), serializer_class = UserProfileSerializer class CoursesViewSet(viewsets.ModelViewSet): queryset = Courses.objects.all(), serializer_class = CoursesSerializer serializers.py from rest_framework import serializers from user_profile.models import Courses, UserProfile class UserProfileSerializer(serializers.HyperlinkedModelSerializer): user_id = serializers.ReadOnlyField() class Meta: model = UserProfile fields = '__all__' class CoursesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model … -
MultiValueDictKeyError(key) [closed]
Hola estoy aprendiendo Django y creando un formulario pero cuando lo envio me aparece lo si mi vista mis modelos mi html espero me pueda alguien ayudar :( -
npx rollup -c [!] SyntaxError: Invalid or unexpected token
While using rollup, if I use following configuration file export default { input: 'src/main.js', output: { file: 'bundle.js', format: 'cjs' } }; I am getting this error npx rollup -c [!] SyntaxError: Invalid or unexpected token rollup.config.js (1:0) 1: ��{ ^ I don't understand why it is not comprehending es6 syntax, this is the reason we use rollup. -
Django Model formset is partially working
I have normally just a simple question but I can't get it working. I have a view where customers can add, delete or edit their addresses. view.py: ... customer_addresses = CustomerAddresses.objects.filter(CustomerID=customer) AddressFormSet = modelformset_factory(CustomerAddresses, form=CustomerAddressesForm, extra=0) formset = AddressFormSet(queryset=customer_addresses, form_kwargs={'user': User.ID}) if request.method == 'POST': if 'add_address' in request.POST: add_address_form = CustomerAddressesForm(User.ID, request.POST) if add_address_form.is_valid(): add_address_form.save() if 'edit_address' in request.POST: address_id = request.POST.get('id_Address') address_data = CustomerAddresses.objects.get(pk=address_id) edit_address_form = AddressFormSet(request.POST, queryset=customer_addresses, form_kwargs={'user': User.ID}) print('ERROR', edit_address_form.errors) messages.error(request, 'ERROR') if edit_address_form.is_valid(): instances = edit_address_form.save(commit=False) for instance in instances: instance.save() return redirect('addresses') if 'delete_customer_address_id' in request.POST: delete_customer_address_id = request.POST.get('delete_customer_address_id') request.session['delete_customer_address_id'] = delete_customer_address_id return redirect('delete-customer-address') if 'register_customer' in request.POST: register_form = CustomerAddressesForm(user=user_id) if register_form.is_valid(): customer = register_form.save(commit=False) customer.UserID = user_id customer.save() # You can redirect to a success page or login the user directly redirect(request.META.get('HTTP_REFERER')) else: add_address_form = CustomerAddressesForm(user=User.ID) and my form: class CustomerAddressesForm(forms.ModelForm): Title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'autofocus': True}), required=False) Address_Firstname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) Address_Lastname = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) Zip = forms.IntegerField( widget=forms.TextInput(attrs={'class': 'form-control', 'maxlength': '5', 'data-toggle': 'maxlength'}), label='Postnummer') City = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) Address_Company = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), required=False) Street = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True}), required=False) Country = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-select'}), queryset=CountryList.objects.values_list('countryname', flat=True).order_by( 'code'), initial='Denmark', to_field_name='countryname') Is_Default_Shipping_address = … -
How can I add the currently logged in username to the access log of django.server?
I'm trying to add the currently logged in username, if any, to the access log of a Django app: INFO [django.server:161] "GET / HTTP/1.1" 200 116181 ^ username should go here My main problem is how do I share the user/username between the middleware and the filter, since in the filter I don't have access to the request object? I've got a working solution using thread-local for storage, but this doesn't seem like a good idea. Especially since I can't cleanup the value in process_request as it is then cleared too early, before the log line is printed. Solution with threading.local() log.py import logging import threading local = threading.local() class LoggedInUsernameFilter(logging.Filter): def filter(self, record): user = getattr(local, 'user', None) if user and user.username: record.username = user.username else: record.username = '-' return True class LoggedInUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.process_request(request) return self.get_response(request) def process_request(self, request): from django.contrib.auth import get_user user = get_user(request) setattr(local, 'user', user) django settings MIDDLEWARE = ( ... 'commons.log.LoggedInUserMiddleware', ... ) ... LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { ... 'verbose_with_username': { 'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(username)s %(message)s' } }, 'filters': { 'logged_in_username': { '()': 'commons.log.LoggedInUsernameFilter', } }, 'handlers': { 'console_with_username': … -
Why is a single product page not loading in Django project
I am trying to make an ecommerce project and I already set up products page, but It should load a product description page after goint to api/products/2 page, example(2 is a product id). views.py: @api_view(['GET']) def getProduct(request, pk): product = None for i in products: if i['_id'] == pk: product = i break return Response(product) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes, name="routes"), path('products/', views.getProducts, name="products"), path('prodcucts/<str:pk>/', views.getProduct, name="product"), ] I already tried int:pk instead of str:pk -
Django model relations and dividing models into few tables in larger project
I have few problems with Django models (relations mostly), but I'll start from code than make desciption and put questions... Django models and relations in short (very simplified) version: # Shorten version of services SERVICES = [ ("TC", "Tires Cleaning"), ("EC", "Exterior Cleaning"), ("IC", "Interior Cleaning"), ("CW", "Cleaning & Washing - full service"), ("WX", "Application of wax"), ] class Client(models.Model): name = models.CharField(max_length=35) surname = models.CharField(max_length=35) car = models.CharField(max_length=25) class SingleService(models.Model): service_name = models.CharField(max_length=35) service_type = models.CharField(max_length=1, choices=SERVICES, default="CW") price = models.IntegerField() class SetOfServices(models.Model): set_of_services = ???? price_of_set = ??? class Purchase(models.Model): client = OneToOneField(client) order = models.ForeignKey(SetOfServices, on_delete=models.CASCADE, blank=True, null=True) price = ??? I want to make small project (Car Wash) with 8+ django models. Client is coming to car wash and I want to store its name/ surname and car make/model/type etc in DB for future refference (clients coming back will get discount and free coffee). Then I have SingleService model with about 20-30 services - they have different name and price because of diferernt tasks / time to make and options / extra features. SetOfServices model must consist of few single services (custom, but customized from Django admin panel, probably only once, at setup / configuration time). … -
Django: matching query does not exist. Error: 500
I'm trying to find a bug - already a second day. The goal was to create a button to save in-session a piece of information about a particular page that would be "read later". I'm trying to find out why I can't find a match in my query. The id that should be generated in POST is 8, but from what I understand from logs, it's 0. I'm looking for suggestions on how to find out where the problem is. I exchausted all ideas that I had. Additionally, I wonder if is it a good or bad idea that in my views.py I defined called model EssayCls in two functions where I define it with different names. In def get as selected_essay = EssayCls.objects.get(slug=slug), but in def post as post = EssayCls.objects.get(slug=slug). My views.py: class MyEssaysView(View): def is_stored_essay(self, request, post_id): stored_essays = request.session.get("stored_essays") if stored_essays is not None: is_saved_for_later = post_id in stored_essays else: is_saved_for_later = False return is_saved_for_later def get(self, request, slug): # print("GET: slug:", slug) # test user_agent = get_user_agent(request) selected_essay = EssayCls.objects.get(slug=slug) user_feedback = UserFeedback() context = { 'essay_found': True, 'essay_all': selected_essay, 'post_tags': selected_essay.tags.all(), 'form': user_feedback, 'comment_form': CommentForm(), 'comments': selected_essay.comments.all().order_by("-id"), 'saved_for_later': self.is_stored_essay(request, selected_essay.id) } if request.method == … -
Reusing a database record created by means of Celery task
There is a task which creates database record {R) when it runs for the first time. When task is started second time it should read database record, perform some calculations and call external API. First and second start happens in a loop In case of single start of the task there are no problems, but in the case of loops (at each loop's iteration the new task is created and starts at certain time) there is a problem. In the task queue (for it we use a flower) we have crashed task on every second iteration. If we add, at the and of the loop time.sleep(1) sometimes the tasks work properly, but sometimes - not. How to avoid this problem? We afraid that task for different combination of two users started at the same time also will be crashed. Is there some problem with running tasks in Celery simultaneously? Or something we should consider, tasks are for scheduled payments so they have to work rock solid -
How do I apply higher permissions to child pages in Wagtail?
I am building an intranet site for my organization with Wagtail and we are in the process of adding a knowledge base. The entire site needs to be restricted to logged-in users, but certain pages need to only be accessible to users in certain groups. For instance, only members of the IT group should be able to access the pages underneath the IT Knowledge Base page. Currently if I set the top-level page to be accessible only by logged-in users, that permission is applied to every page on the site, and I am barred from setting more specific permissions on any child page. It is imperative that I be able to set more specific permissions on child pages. I was able to find Wagtail Bug #4277 which seems to indicate that the logic for more specific permissions is implemented but not exposed in the admin UI. I am not familiar with the inner workings of Wagtail yet, especially how Wagtail permissions intersect with Django permissions. How can I add more specific permissions to child pages? -
How to disable TLS Renegotation in EB AWS for Linux AMI?
It is a security best practice to disable TLS Renegotiation in production. What is the best way to do this in an Apache2-based Elastic Beanstalk Deployment (Python/Django)? -
The system cannot find the file specified (django)
Hi I'm creating pdf file but I face an error [WinError 2] The system cannot find the file specified but I don't know where is the error if os.path.exists(pdf_file_output): with open(pdf_file_output, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(pdf_file_output) return response -
AJAX not working on Django and returning 500 Error
I'm trying to send an AJAX request from my template that takes you to a url and runs the view function. However, I'm getting a 500 Error in my console. My view is also using a custom decorator, all required code is below: Decorator def user_has_delete(func, redirect_url="Home:Deny"): def wrapper(request, *args, **kwargs): if request.user.is_anonymous: return redirect(redirect_url) if request.user.is_authenticated: if not request.user.is_denier: return redirect(redirect_url) else: return func(request, *args, **kwargs) return wrapper URL Pattern path('Vet/DenyAppointment/<int:appointment_id>', views.delete_appointment) View @user_has_delete @never_cache def delete_appointment(request, appointment_id): appointment = get_object_or_404(Appointments, pk=appointment_id) appointment.delete() return redirect('Dashboard') Template Portion {% for appointment in appointments %} <div class="col-sm-12 col-lg-8 AppointmentDiv offset-sm-0 offset-lg-2 Space-b-sm"> <h2>{{ appointment.fullDate }}</h2> <ul> <li>{{ appointment.title }}</li> <li>{{ appointment.day }}</li> </ul> <button type="submit" class="theme" id='{{ appointment.id }}' onclick="deleteAppointment({{ appointment.id }})">Delete Appointment</button> </div> {% endfor %} AJAX <script> function deleteAppointment(appointmentId) { $.ajax({ url: '/Vet/DenyAppointment/' + appointmentId, type: 'GET', success: function(response) { window.location.href = "/Dashboard"; } }); } </script> -
I want to connect mssql server in django rather than default database please suggest me code
I want to connect mssql server in django rather than default database please suggest me the code which, I've to write in "settings.py" file only " settings.py" file code what i've to write in the file -
phyton JSONDecodeError Extra data
Why can such an error occur? Traceback At some point, users going to the site catch a 500 error, the backend accepts json from another application -
React and nginx: refused to connect to localhost
I have my React (frontend) and Django REST (backend) running on a remote Ubuntu server with nginx. I also have a simple reverse proxy defined in conf.d/bookmarks.conf to manage all of that: server { listen 80; listen [::]:80; location /api/ { # Backend proxy_pass http://127.0.0.1:1337/api/; } location / { # Frontend root /var/www/bookmarks/html/; index index.html; try_files $uri $uri/ /index.html; } } I run my Django app with runserver python manage.py runserver 127.0.0.1:1337, and React static files are stored in the folder described above I try to connect to API with React: const generateOpendIdLink = async () => { const generateOpendIdLinkEndpoint = 'http://127.0.0.1/api/opendid-link-generator/'; const requestOptions = { method: 'GET', headers: {'Content-Type': 'application/json'}, }; try { const response = await fetch(generateOpendIdLinkEndpoint, requestOptions); if (response.status == 200) { ... }; } catch (error) { console.log(error); }; }; And get an error GET http://127.0.0.1/api/opendid-link-generator/ net::ERR_CONNECTION_REFUSED This is quite odd, because I could connect to API from the web no problem: running the same GET on the server IP address http://XX.XXX.XX.XX/api/opendid-link-generator/ from Postman works as expected. This is also true when I change 127.0.0.1 for the server IP in the React code, it all starts to work. I also set ALLOWED_HOSTS = ['*'] for test … -
copy a model instance and update a filed in new copy
this is my model. I want to make a copy from my model with copy function. and update the created_time to this time and eventually return the post id from django.db import models from django.utils import timezone class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def copy(self): blog = BlogPost.objects.get(pk=self.pk) comments = blog.comment_set.all() blog.pk = None blog.save() for comment in comments: comment.pk = None comment.blog_post = blog comment.save() return blog.id class Comment(models.Model): blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) text = models.CharField(max_length=500) I also want copy function makes a copy from post and comments, would you help me to correct my code and update the time in my function. thank you. -
how do I configure my Django app to use Dreamhost email?
I created a django app that has a contact form where users can send an email to the company (The email configured in the APP) I am getting "SERVER ERROR 500" After reading this: django email settings on dreamhost I tried the following format in my settings.py: EMAIL_HOST = 'smtp.dreamhost.com' # I also tried pop.dreamhost.com / imap.dreamhost.com with their respective port numbers. EMAIL_USE_TLS = True # I also tried EMAIL_USE_SSL EMAIL_PORT = 587 # I also tried 25 and 465 EMAIL_HOST_PASSWORD = 'EMAIL_PASSWORD' # also tried SERVER_PASSWORD EMAIL_HOST_USER = 'my_dreamhost_email' # Also tried admin@mydomain.com EMAIL_SUBJECT_PREFIX = '' SERVER_EMAIL = 'my_dreamhost_email' # also tried 'localhost' / 'admin@mydomain.com' ADMINS = (('Jack Shedd', 'jack@example.com'),) # I used my details PS: The app is working perfectly if I use gmail What are the correct details to use? Thanx in advance -
Issue displaying question for answer in views.py
I ran into a problem I have questions that are related to items_buy_id , there are also choices that are related to question_id questions Questions items_buy_id It turns out to connect And with the choice you will not contact as it should My models.py from django.db import models from datetime import datetime from phonenumber_field.modelfields import PhoneNumberField from django_resized import ResizedImageField from email.policy import default from django.utils.translation import gettext_lazy class Items_buy(models.Model): class Meta: db_table = 'items_buy' verbose_name = 'Телефон который покупаем' verbose_name_plural = 'Телефоны которые покупаем' image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона') model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ') text = models.TextField(max_length=500, verbose_name='Текст') max_prise_iphone = models.FloatField(verbose_name='Максимальная цена telefoha') image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy') def __str__(self): return self.model_produkt class Question(models.Model): class Meta: db_table = 'question' verbose_name = 'Вопрос к телефону' verbose_name_plural = 'Вопросы к телефону' items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) title = models.CharField(max_length=150,verbose_name='Заголовок вопросa') question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text') max_prise_qustion = models.FloatField(verbose_name='Максимальная цена') def __str__(self): return self.title class Choice(models.Model): class Meta: db_table = 'choice' verbose_name = 'Выбор ответа' verbose_name_plural = 'Выбор ответов' #items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT) question_id = models.ForeignKey(Question, on_delete=models.RESTRICT) title = models.CharField(max_length=1000, verbose_name='Заголовок выбора') points = models.FloatField(verbose_name='Цена ответа') #lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа') def __str__(self): return self.title My urls.py … -
Django advanced query on the same model
I have a Kit and KitInOut models: class Kit(models.Model): name = models.CharField(max_length=255, blank=True, null=True) class KitInOut(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) out = models.BoolField(default=True) creation_timestamp = models.DateTimeField() I want to find out which kits are out and dont have the the same kit again in the resulting query, which is something like : "select * from KitInOut where, for each kit k, keep it in the result if it went out** (kit_went_out=1) and there's no other KitInOut k2 where k2.kit=k and k2.creation_timestamp > k.creation_timestamp" Here's the code I have, which is so un-optimized that I can't use it with more than 500 KitInOut rows: k_in_out_s = KitInOut.objects.filter(out=True) result = [] for obj in k_in_out_s: if (KitInOut.objects.filter( kit=obj.kit, out=False, creation_timestamp__gt=obj.creation_timestamp, ).count() == 0): result.append(obj) return result How to optimize this? -
How to build a multi-module react-library where components can be imorted via import { MyComponent } from "shared-ui/my-component"
I built a react component library using Vite.js. Here's the vite-config: // vite.config.js export default defineConfig({ resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, build: { lib: { entry: resolve(__dirname, "src/index.js"), name: "SharedUI", formats: ["es"], fileName: "shared-ui", }, rollupOptions: { plugins: [peerDepsExternal()], output: { globals: { react: "React", }, }, }, }, }); Here's my folder structure: shared-ui/ ├─ src/ | ├─ index.js │ ├─ components/ │ │ ├─ index.js │ │ ├─ select | | | ├─index.js | | | ├─select.component.jsx │ │ ├─ input | | | ├─index.js | | | ├─input.component.jsx ├─ vite.config.js ├─ dist The shared-ui/src/index.js-file contains the following: // shared-ui/src/index.js export * from "./input"; export * from "./select"; The vite build command created one file shared-ui.js, which lands in dist folder. If I install the package (in my case in an app using pnpm workspace) I can import the Select-component using: import { Select } from "shared-ui"; and it works. But I want to achieve imports like: import { Select } from "shared-ui/select"; How is that possible? I tried using rollup-plugin-includepaths like // vite.config.js import includePaths from "rollup-plugin-includepaths"; let includePathOptions = { include: {}, paths: ["src/components"], external: [], extensions: [".js", ".jsx"], }; //... vite … -
I am having problem with Nginx default 80 port when I upload media files
I upload a file to the server using the post method, but it appears on the default port 80. However, I run Nginx on port 8001. This is what I see when I check my endpoint with 8001 port. File look like port 80. http://xxx.xxx.x.xx/media/files/excel/macro/data.xlsx But I check with 8000 port http://xxx.xxx.x.xx:8000/media/files/excel/macro/data.xlsx My nginx/default.conf file : upstream django_asgi { server django_asgi:8000; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { client_max_body_size 100M; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://django_asgi; client_max_body_size 100M; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 3600; proxy_connect_timeout 3600; proxy_send_timeout 3600; keepalive_timeout 3600; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /static/ { alias /code/staticfiles/; } location /media/ { alias /code/media/; } } My Dockerfile : FROM python:3.8 ENV PYTHONUNBUFFERED 1 ENV REDIS_HOST "redis" RUN mkdir /code RUN mkdir code/staticfiles RUN mkdir code/mediafiles WORKDIR /code RUN pip install --upgrade pip RUN pip install psycopg2 COPY requirements.txt /code/ RUN pip install uwsgi RUN apt-get update && apt-get install -y tdsodbc unixodbc-dev RUN pip install -r requirements.txt ADD . /code/ RUN python manage.py collectstatic --no-input RUN python manage.py migrate --no-input My docker-compose.yml … -
can't send value to database postgresql with Django and javascript
i'm try use Ajax send correctAnswers to postgresql with Django but it error. I don't know where I missed it. function checkAnswers() { window.scrollTo(0, 0); var correctAnswers = 0; for (var i = 0; i < questions.length; i++) { var radios = document.getElementsByName("question" + (i + 1)); var questionCol = document.getElementsByClassName("col-12")[i]; var isCorrect = false; for (var j = 0; j < radios.length; j++) { if (radios[j].value == questions[i].correctAnswer && radios[j].checked) { correctAnswers++; isCorrect = true; break; } } document.getElementById("result").innerHTML = "คุณได้คะแนน " + correctAnswers + " / " + questions.length; var backButton = document.createElement("input"); backButton.setAttribute("type", "button"); backButton.setAttribute("value", "กลับไปหน้าหลัก"); backButton.setAttribute("class", "btn btn-primary center1"); backButton.setAttribute("onclick", "location.href='User-page.html'"); document.getElementById("quizForm").appendChild(backButton); $.ajax({ url: "/submit_quiz/", type: "POST", data: { correctAnswers: correctAnswers }, success: function (response) { console.log("ส่งค่าไป data base สำเร็จ"); }, }); } It has no ajax response. -
How to sort querysets from different models based on two fields?
I have querysets from different models which have only two fields in common: datetime and dt_created, and I would like to sort the objects first on datetime and then on dt_created, so that objects with the same datetime are sorted based on field dt_created. How can I do that ? Until now I was able to combine and sort the queryset with datetime like this: lst_qs = list(qs_trades) + list(qs_deposits) + list(qs_withdrawals) sorted_lst = sorted(lst_qs, key=lambda x: x.datetime)