Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to convert data in xml to json using python
I need to convert xml data to json format. I am using django for backend, and I'm not really comfortable parsing data from xml, so I thought about converting data in json and then parsing it. The xml data format is as shown below: <?xml version='1.0' encoding='ASCII'?> <add> ... <doc> <field name="id">1</field> <field name="title1">subtitle1</field> <field name="title2">subtitle2</field> </doc> ... </add> I need to convert format into json using python. Also, if there is any better way to do it, please let me know. I tried converting using online converters but the json data is not accurate. I'm getting the values but not the keys and some converters are throwing error. -
Getting 'Broken Pipe' Error with AJAX Request in Django
I keep encountering a "Broken pipe" error when making an AJAX request in Django. The request is intended to retrieve text and selected languages, among other data, then translate it in the views, with the translated text appearing in the output window. Here's my AJAX code snippet: Here is AJAX code: var outputTextarea = document.getElementById("output-textarea"); // AJAX request $(document).ready(function () { $('.translate-button').click(function () { // Retrieve input data var fromLanguage = document.getElementById("from-language-selectbox").selectedOptions[0]; var toLanguage = document.getElementById("to-language-selectbox").selectedOptions[0]; var isFlashcard = document.getElementById("is-flashcard-switch2").checked; var selectedDecks = document.getElementById("decks-list-selectbox").selectedOptions; console.log(selectedDecks) var selectedDeckValues = []; var inputText = document.getElementById("input-textarea").value; console.log(inputText); for (var i = 0; i < selectedDecks.length; i++) { selectedDeckValues.push(selectedDecks[i].textContent); } console.log(selectedDeckValues); var outputTextarea = document.getElementById("output-textarea"); $.ajax({ url: '{% url "mainapp:translator" %}', data: { 'input_text': inputText, 'is_flashcard': isFlashcard, 'decks': selectedDeckValues, 'from_language': fromLanguage.textContent, 'to_language': toLanguage.textContent, }, dataType: 'json', success: function (data) { console.log("success"); outputText = data.output_text; outputTextarea.textContent = outputText; }, error: function (xhr, status, error) { console.log("Error occurred: " + error); } }); }); }); And here is view: def translator(request): """View for translatation.""" if request.headers.get("x-requested-with") == "XMLHttpRequest": #Retrieve data from AJAX request input_text = request.GET.get("input_text") is_flashcard = request.GET.get("is_flashcard") if is_flashcard == "true": is_flashcard = True else: is_flashcard = False decks = ["superdeck", "talja"] #request.GET.get("decks") from_language … -
Firebase State changing problems, Page does not change its aspect when user is logged in
Basically when the user is logged in I want the homepage to have written my account instead of login/register. I tried my chatpgt since I'm a beginner but it is not working. I would really appreciate a help. I have no idea how to solve it. <script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-auth.js"></script> <script> import { initializeApp } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.10.0/firebase-analytics.js"; import { getAuth, onAuthStateChanged} from "https://www.gstatic.com/firebasejs/10.10.0/firebase-auth.js"; // Your web app's Firebase configuration const firebaseConfig = { I have removed my keys here }; // Initialize Firebase const app = firebase.initializeApp(firebaseConfig); const auth = firebase.auth(); // Listen for auth state changes onAuthStateChanged(auth, user => { if (user) { // User is signed in, show "My Account" link document.querySelector('.navigation').innerHTML = ` <a href="chat" class="nav-link">Chat</a> <a href="account" class="nav-link">My Account</a> `; } else { // No user is signed in, show "Login / Register" link document.querySelector('.navigation').innerHTML = ` <a href="chat" class="nav-link">Chat</a> <a href="auth" class="nav-link">Login / Register</a> `; } }); </script> Here is the nav bar in the html: <header> <div class="header-container"> <div class="logo-container"> <h1 class="site-title">Athena</h1> </div> <nav class="navigation"> <a href="chat" class="nav-link">Chat</a> <a href="auth" class="nav-link">Login / Register</a> </nav> </div> </header> -
I cant configure LOGIN_REDIRECT_URL Django
I want to setting that after succesfully login with google it redirect me to the profile_detail.html page LOGIN_REDIRECT_URL = "/polls/profile/" LOGOUT_REDIRECT_URL = "/" views.py def profile_detail(request): return render(request, "profile_detail.html") urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path("", views.home, name='home'), path("logout/", views.logout_view, name='logout'), path('googleLogin/', views.googleLogin, name='googleLogin'), path('profile/', views.profile_detail, name='profile_detail'), path('profile_creation/', views.create_profile, name='profile_creation') ] -
JSON Decode Exception
import requests import json URL = "http://127.0.0.1:8000/TESTGET_api/" def get_data(id = None): data = {} if id is not None: data = {'id':id} json_data = json.dumps(data) r = requests.get(url= URL, data = json_data ) data = r.json() print(data) get_data() this is the code, the problem lies at r.json(). Please guide with the solution. I tried using print(r.content) before data = r.json(). but still not working. -
CPU and time problem with gunicorn,django,nginx
We are got a project on gunicorn,django and nginx. Got a table in postgres with 600000 records with a big char fields(about 7500). That problem solved by triggers and searchvector. Also there api(rest) and 1 endpoint. On this endpoint db request take about 0.3 s. Its normal for us. But getting response take about 1 minute. I think maybe that gunicorn. While we are waitint for a response one on process take 100%. gunicorn.service User=www-data Group=www-data WorkingDirectory=/home/***/market ExecStart=/home/***/venv/bin/gunicorn \ --access-logfile - \ -k uvicorn.workers.UvicornWorker \ --workers 8 \ --threads 20 \ --bind unix:/run/gunicorn.sock \ --timeout 200 \ --worker-connections 1000 \ *.asgi:application This is phisical hosting with 8 cores CPU User CPU time 201678.567 ms System CPU time 224.307 ms Total CPU time 201902.874 ms TOTAAL TIME 202161.019 ms SQL 385 ms Trying change count of workers,threads,change from wsgi to asgi,but nothing help. -
Does deleting an image from a model delete it from the media folder?
I'm making a social networking website project to practice Django I am curious as to whether deleting an image from a model also deletes it from the media folder? For example, I have a field in my User model where a user can upload their profile picture. As standard, I save that profile picture in my media folder and a reference to that media folder is used by my model to load it. But, if the user wishes to delete that picture, I use User.profilepic.delete() to delete it Does that mean that the picture also gets deleted from the media folder or I have to handle that separately? I tried looking it up on the net but I couldn't find a direct answer. All of the articles talk about deleting the image from the DATABASE. But none from the folder. Thanks in advance. -
Django: object has no attribute 'cleaned_data'
my models.py is Like this: from django.db import models class Form(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.EmailField() date = models.DateField() occupation = models.CharField(max_length=80) # Magic Method def __str__(self): return f"{self.first_name}{self.last_name}" My forms.py is: And my views.py is: from django.shortcuts import render from .forms import ContactForm from .models import Form def index(request): # To fetch data from webpage if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): first_name = form.cleaned_data["fname"] last_name = form.cleaned_data["lname"] email = form.cleaned_data["email"] date = form.cleaned_data["date"] occupation = form.cleaned_data["occupation"] print(first_name) # To store in database Form.objects.create(first_name=first_name, last_name=last_name, email=email, date=date, occupation=occupation) return render(request, "index.html") And I am getting the following error: 'ContactForm' object has no attribute 'cleaned_data' In 'views.py' -- "if form.is_validate()" is returning "False"..and the following code is not executing. -
How to only display superusers in ManyToManyField field when creating an instance in admin page
We have this model: # models.py from django.conf import settings User = settings.AUTH_USER_MODEL class Category(models.Model): ... users = models.ManyToManyField(User, help_text='Choose Superusers only', blank=True) The questions is:when creating an instance in the admin page, how can I force the form to only display superusers in the multiple select? -
valid view function or pattern name error in django
I am learning django. My URL pattern is like below. path('task-delete/<int:pk>/', DeleteView.as_view(), name="tasks-delete"), I have class based view like below. class DeleteView(DeleteView): model = Task context_object_name = 'task' success_url = reverse_lazy('tasks') HTML code in template is like below. <a href="{% url 'task-delete' task.pk %}">Delete</a> My error is like below. How to fix this error ? -
Django Incorrectly sending image files to React Native frontend
I am coding my first react native project, although I just created one with django/react. In my first project I configured the react side to serve static files. I couldnt get this new project to serve them correctly so I copied word for word what I did in the last one and it is still incorrect. Format I get it in my React Native frontend is profilePicture : "/media/images/beserk.png" but it should be http://localhost:8000/media/images/beserk.png, or atleast thats what it looked like in my other project. Frontend does not display image, but does display local ones so the problem is 100% backend. Below are my relevant configurations: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media') MEDIA_URL = '/media/' (static/media/images is in project directory) urls.py: urlpatterns = [ path('api/', include('backend.urls')), path('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model/serializer class UserProfile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) biography = models.CharField(max_length=255) public_name = models.CharField(max_length=30) user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') friends = models.ManyToManyField('self', blank=True) description_tags = models.ForeignKey('Descriptor', null=True, blank=True, on_delete=models.PROTECT) def __str__(self): return str(self.user) class UserProfileSerializer(ModelSerializer): description_tags = DescriptorSerializer() class Meta: model = UserProfile fields = '__all__' def to_representation(self, instance): if self.context.get('list_view', False): return { 'id': … -
How do I upload data to html from a database?
I have a home project, DRF is deployed in it, the database itself is on postgresql and I learned how to create a page template, BUT without data from the database. That's how I did it.: $ mkdir static $ vim Project1/settings.py $ cat Project1/settings.py ... from pathlib import Path import os ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'portfolio', 'ckeditor', 'ckeditor_uploader', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Project2')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" ... $ mv Project2/css static/ $ ls static/ css $ vim Project2/index.html $ cat Project2/index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Project2</title> </head> <body> <!--SECTIONS--> <!--CARDS--> <section> <div class="container"> <div class="cards"> <div class="card__content" id=""> <h2 class="card_hidden" onclick="card__hidden(this)">Опыт работы</h2> <div style="text-align: left;"> <ul> <li><strong> ' . $row['begin'] . ' - ' . $row['finish'] . ':</strong> ' . … -
Django google oauth2.0, i want to implement profile creation for my web app using build in google ouath2
i want to implement profile creation for my web app using build in google ouath2, i try to override auth.user model and inheritence from there info and create my own columns.But smth i do wrong, can someone help me.I need inheritence auth data from auth.user for CustomUser how to do this. models.py from django.contrib.auth.models import AbstractUser from .choices import STATUS_CHOICES, HOBBY_CHOICES, GENDER_CHOICES from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default='regular') hobby = models.CharField(max_length=200, choices=HOBBY_CHOICES) photo = models.ImageField(upload_to='profile_pics/', blank=True, null=True) city = models.CharField(max_length=100, blank=True) age = models.PositiveIntegerField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True) description = models.TextField(blank=True) groups = models.ManyToManyField( 'auth.Group', related_name='custom_user_groups', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='custom_user_permissions', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', ) def __str__(self): return self.username CustomUserCreationModel.py from django import forms from django.core.exceptions import ValidationError from .models import CustomUser from .choices import HOBBY_CHOICES, GENDER_CHOICES class CustomUserCreationForm(forms.ModelForm): hobby = forms.ChoiceField( choices=HOBBY_CHOICES, widget=forms.Select(attrs={'class': 'custom-dropdown form-control', 'id': 'Hobby'}) ) photo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'})) city = forms.CharField(widget=forms.TextInput(attrs={'class': 'custom-input'})) age = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'custom-input'})) gender = forms.ChoiceField( choices=GENDER_CHOICES, widget=forms.RadioSelect(attrs={'class': 'custom-radio'}) ) description = forms.CharField( widget=forms.Textarea(attrs={'class': 'custom-textarea'}) ) … -
django react project createAction not working
This is my actions.jsx: import { redirect } from "react-router-dom"; const URL = import.meta.env.VITE_BASE_URL; //Create Action export const createAction = async ({ request }) => { const formData = await request.formData(); const newBlog = { subject: formData.get("subject"), details: formData.get("details"), image_url: formData.get("image_url") } await fetch(`${URL}`,{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newBlog) }); return redirect("/"); } export async function updateAction({ request, params }) { const formData = await request.formData(); const id = params.id; const updatedBlog = { subject: formData.get("subject"), details: formData.get("details"), image: formData.get("image_url") } await fetch(`${URL}${id}/`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updatedBlog) }); return redirect(`./`); } //Delete Action export const deleteAction = async ({params}) => { const id = params.id; await fetch(`${URL}${id}/`, { method: "DELETE" }); return redirect("/"); } This is my Index.jsx: import Blog from "../components/Blog" import { Form, useLoaderData } from "react-router-dom" import { useState } from "react" export default function Index(props) { const allBlogs=useLoaderData() const [image, setImage] = useState('app.logomakr.com/3EC6KR') const handleInputChange = (event) => { setImage(event.target.value) } return( <> <h1>Index</h1> <hr/> <h1>Add a Post</h1> <Form action="/create" method="post"> <label htmlFor="subject"> Title: <input type="text" subject="subject" id="subject"/> </label> <label htmlFor="details"> Write your post here: <input type="textarea" name="details" id="details"/> </label> <label htmlFor="image_url"> Image Link: <input type="text" … -
No such file or directory: 'ffmpeg' in Django/Docker
I run my Django code in Docker. I run transcription software that requires ffmpeg to function. However I've been getting the error [Errno 2] No such file or directory: 'ffmpeg' whenever I try to run my code. Here's my views.py: def initiate_transcription(request, session_id): ... with open(file_path, 'rb') as f: path_string = f.name transcript = transcribe_file(path_string,audio_language, output_file_type) ... Here's my Dockerfile: # Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ && apt-get install -y --force-yes \ nano python3-pip gettext chrpath libssl-dev libxft-dev \ libfreetype6 libfreetype6-dev libfontconfig1 libfontconfig1-dev\ && rm -rf /var/lib/apt/lists/* RUN apt-get update && apt-get install -y git RUN apt-get update && apt-get install -y libmagic-dev RUN apt-get -y update && apt-get -y upgrade && apt-get install -y --no-install-recommends ffmpeg # Set working directory for Docker image WORKDIR /code/ RUN apt-get update \ && apt-get -y install libpq-dev gcc # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . I've searched online for possible solutions but have not been … -
Unable to link files with eachother in Django
I was working on something, and I'm stuck. Here is what I'm trying to do - suppose a user enters the order number on the site (named index.html), I would like to check if that order exists in the database. If it does, then it should redirect the user to the shipment page (shipment.html), where all the details are available regarding the same. I'm completely blank and not getting any ideas whatsoever. Please help. here it is what I tried doing, still not working! **here are the source code - ** Index.html - `{% block content %} {% csrf_token %} <button type="submit"> Track </button> </form> {% endblock %} {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %}` **views.py - ** def shipment(request): if request.method == 'POST': order_number = request.POST['order_number'] try: shipment = Shipment.objects.get(order_number=order_number) return redirect('shipment') except Shipment.DoesNotExist: message = f"Order ID {order_number} does not exist in the database." else: message = "" return render(request, 'index.html', {'message': message}) **models.py - ** class Shipment(models.Model): member_id = models.CharField(max_length=100) order_number = models.CharField(max_length=100) tracking_id = models.CharField(max_length=10) priority = models.IntegerField() current_location = models.CharField() destination … -
Django rest framework : unable to login user with correct email and password
I am new to Django. I am trying to build a simple login/registration with MongoDB as database. The user is successfully signing up but unable to login using correct password and email. Here is my serializers.py file class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name', 'password') Here is my models.py file class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_doctor', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_doctor = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def __str__(self): return self.email Here is my views.py for Login @api_view(['POST']) @csrf_exempt def login_view(request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) serializer = UserSerializer(user) return Response(serializer.data) else: return Response({'error': 'Invalid email or password'}, status=status.HTTP_401_UNAUTHORIZED) It is always shows the Invalid email or password. -
Issue with redirecting a user after successfully logging into a Django app
I have a written a django app which requires a user to log in to access certain pages. The login process is working correctly but when they log in they are not been sent to the correct page and a 404 error is being displayed. My URLS.py is path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), My settings.py is """ " import os import posixpath DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True LOGIN_URL = '/api/login/' LOGIN_REDIRECT_URL = '/api/listsystemhazardcontrols/' ALLOWED_HOSTS = [] # Application references # https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-INSTALLED_APPS INSTALLED_APPS = [ 'app', 'rest_framework', 'rest_framework_simplejwt', 'djoser', # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap5', ] # Middleware framework MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'RiskManagementSoftware.urls' # Template configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [], # … -
Trouble inserting modifiers inside kitchenorderitem in Django
I'm currently working on a Django project where I have models for kitchen orders. I'm encountering an issue where I can insert products into the kitchen order, but I'm unable to insert modifiers inside the products. Here's a simplified version of my code: item_id = uuid.uuid4() kitchen_order = KitchenOrderItem.objects.create( id=item_id, kitchen_order=instance, product_id=product.get("product_id"), quantity=product.get("quantity"), note=product.get("note"), ) for modifier in product.get("modifiers"): kitchen_order_items.append(KitchenOrderItem( modifier_id=item_id, product_id=modifier.get("product_id"), quantity=modifier.get("quantity"), note=modifier.get("note"), )) I expect the modifiers to be inserted along with the products, but it seems like only the products are being inserted into the database. Could anyone help me figure out what might be causing this issue? Am I missing something in my code or is there a better approach to achieve inserting both products and modifiers into the kitchen order? -
Celery Worker Doesn't Do Any Writes while Running In Docker
I don't know how to describe the problem but basically, I have a celery task that do some work and write objects to the database. from app.celery import celery_app from some.models import Thing import requests @celery_app.task def my_task_1(): response = requests.get("https://example.com/response1.json") things = [] for data in response.json()['records']: thing, _ = Thing.objects.get_or_create( name=data['name'], data=data['data'], ) things.append(thing) # ... snip ... @celery_app.task def my_task_2(): response = requests.get("https://example.com/response2.json") things = [] for data in response.json()['records']: thing, _ = Thing.objects.get_or_create( name=data['name'], data=data['data'], ) things.append(thing) # ... snip ... Tasks are being scheduled using django-celery-beat with only one worker. The code above works perfectly (or so I think) on my dev machine. however, when I deploy the project using docker I encounter some wired problem. 1- I could see that Thing objects are getting created. but not accessible? 2- The newly created Thing objects are not visible in django-admin. 3- Once I restart my worker the objects will be visible. My docker-compose file looks like this: version: '3' services: db: image: postgres:latest restart: always environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres volumes: - db_data:/var/lib/postgresql/data redis: image: redis:latest restart: always web: build: . restart: always command: /webserver-entrypoint.sh environment: POSTGRES_HOST: db CELERY_BROKER_URL: 'redis://redis:6379/0' CELERY_RESULT_BACKEND: 'redis://redis:6379/0' ports: … -
Docker error: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 2
I've recently cloned my repository to a new device. My repository is run in a docker environment. However, despite having one successful docker image build on this device, whenever I try to build a new Docker image(by running docker build . ) I encounter this error when installing in requirements.txt: Dockerfile:30 -------------------- 28 | # Install dependencies 29 | COPY requirements.txt . 30 | >>> RUN pip install -r requirements.txt 31 | 32 | # Copy project -------------------- ERROR: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 2 I haven't been able to find anything related to error code 2 online. I've restarted Docker and ran the command at least 10 times. I've also increased pip timeout to 2 mins using set PIP_TIMEOUT=120 but it still results in the same error. Here is the full traceback(along with the last package being installed: Collecting nvidia-cudnn-cu11==8.5.0.96 (from torch==2.0.1->-r requirements.txt (line 45)) 179.9 Downloading nvidia_cudnn_cu11-8.5.0.96-2-py3-none-manylinux1_x86_64.whl (557.1 MB) 239.0 ━━━━━━━━━━━━━━━━━╸ 250.1/557.1 MB 1.1 MB/s eta 0:04:38 239.0 ERROR: Exception: 239.0 Traceback (most recent call last): 239.0 File "/usr/local/lib/python3.11/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher 239.0 yield 239.0 File "/usr/local/lib/python3.11/site-packages/pip/_vendor/urllib3/response.py", line 561, in read 239.0 data = self._fp_read(amt) if … -
EOF error occured in Docker compose up (Django)
I have EOF error when python manage.py makemigrations in docker compose up (0.001) SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations"; args=(); alias=default Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 235, in handle changes = autodetector.changes( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 46, in changes changes = self._detect_changes(convert_apps, graph) File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 179, in _detect_changes self.create_renamed_fields() File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 955, in create_renamed_fields if self.questioner.ask_rename( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/questioner.py", line 220, in ask_rename return self._boolean_input( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/questioner.py", line 101, in _boolean_input result = input() EOFError: EOF when reading a line This is my Dockerfile FROM python:3.10.11 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN chmod +x /code/entrypoint.sh ENTRYPOINT ["sh", "-c", "/code/entrypoint.sh"] And it is my docker-compose.yml version: '3.8' services: db: image: postgres:14.10-alpine volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} django: build: . … -
how to redirect "back" button in browser using Django
I am developing a testing system for students using django, the idea is that if a student wants to pass a test, he must enter an access code that the teacher will send him. I faced the problem that when the student finished the test and clicked the send answers button and was transferred to the results page, he can return to the test by clicking the "back" button in the browser. I need that if he clicked this button on the results page, he would be transferred to the main page here is my code: def test(request): unique_code = request.POST.get('accessCode',None) first_name = request.POST.get('first_name',None) last_name = request.POST.get('last_name',None) if unique_code: try: # We get the model with a unique key TestFile = Test.objects.get(unique_code=unique_code) if not os.path.exists(TestFile.file.path): return HttpResponse('File not found') except Test.DoesNotExist: return HttpResponse('File not found') questions = [] answers = [] isQuestion = False with open(TestFile.file.path, "r", encoding="utf-8") as f: for line in f: # Checks if the string is not empty if line != '\n': if not isQuestion: questions.append(line.strip()) isQuestion = True else: tempAnswers = [] tempVal = line.strip() tempAnswers.append(tempVal) for temp_line in f: if temp_line == '\n': break tempAnswers.append(temp_line.strip()) answers.append(tempAnswers) isQuestion = False # We save the data … -
Custom manager isn't accessible via model instances
This is my model: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=News.Status.PUBLISHED) class News(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'پیشنویس' PUBLISHED = 'PB', 'منتشر شده' user = settings.AUTH_USER_MODEL image = FileBrowseField( 'تصویر خبر', max_length=255, directory='news/', extensions=['.png', '.jpg'] ) title = models.TextField('عنوان خبر') slug = models.SlugField( 'نامک', max_length=255, unique=True, help_text=('نامک آدرس لینک خبر در مرورگر است و باید یکتا باشد.'), allow_unicode=True, ) author = models.ForeignKey( user, on_delete=models.CASCADE, related_name='news', verbose_name='نویسنده' ) body = RichTextUploadingField('متن خبر', config_name='extended') publish = models.DateTimeField('تاریخ انتشار', default=timezone.now) created = models.DateTimeField('تاریخ ایجاد', auto_now_add=True) updated = models.DateTimeField('بروزرسانی', auto_now=True) status = models.CharField( max_length=2, choices=Status.choices, default=Status.DRAFT ) objects = models.Manager() published = PublishedManager() class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish'])] verbose_name = 'اخبار' verbose_name_plural = 'اخبار' def __str__(self): return self.title But I get "AttributeError: Manager isn't accessible via News instances. Did you mean: 'publish'?" I've read other posts about this problem. None of them are applicable here? The above code is actually from a book called Django 4 by Example with slight modifications. -
Django formset is valid but returns empty dict list
I'm attempting to render a form that is a table where each row contains a name and a checkbox to allow the user to select players for a game. Googling around I've realized that I need to generate a formset so that each line in the table is a separate form. I finally have the table rendering correctly and posting without errors but what I've found is that while the formset is valid, the cleaned data contains a list of empty dicts. I found some StackOverflow posts that were similiar that said to create your own Formset class and set empty_permitted=True but that did not fix my issue. I can't seem to get passed this issue so any help is appreciated. Code Snippets # forms.py class InvitePlayerForm(forms.Form): """ Form to invite players to the new game """ invited = forms.CheckboxInput() class InvitePlayerFormset(BaseFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False # views.py ef create_game_players(request): """ View to invite players to a game """ context = dict() # if this is a POST request we need to process the form data if request.method == "POST": num_players = request.session["invites"]["num_players"] print(f"num_players: {num_players}") invite_formset = formset_factory(InvitePlayerForm, formset=InvitePlayerFormset, extra=num_players) invite_forms …