Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a custom display in Django admin UI for user with only "view" permission?
If I want to change how an object is added or changed in the Django admin UI, I can simply override the form (docs). For a user with only "view" permission (no add, no change, no delete), that form doesn't even show up. If I want to change how an object is displayed in the admin UI for a user with only "view" permission on the "detail page", what do I do? P.S. When I say "detail page" I mean the page rendered when you click on the object in the list view. The URL ends in "change", but nothing can be changed for a user without change permission. EDIT: Maybe change_form_template? EDIT 2: A related way to ask this might be: how are read-only fields shown on the change form, and how do I customize a read-only field display? I think if you don't have "change" permission, it's rendering the fields as read-only. EDIT 3: This answer says you can't customize read-only fields. So maybe this is not possible? -
Django static don't read bootstrap javascripts file
When I import bootstrap css and js to django as static, css file connected and works, but js file show me error: "GET /static/bootstrap/js/bootstrap.min.js HTTP/1.1" 404 179. My 'main.html' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> {% load static %} <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <!-- DataTables --> <!-- Bootstrap JS --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}" /> <!-- DataTables JS--> <!-- DataTable Scripts --> </head> <body> {% include 'navbar.html' %} <main> <div class="container"> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}}">{{message}}</div> {% endfor %} {% endif %} {% block context %} {% endblock context %} <footer class="footer"> <div class="container"> <p>© Copyright {% now "Y" %} by <a href=""></a></p> </div> </footer> </div> </main> </body> </html> My 'setting.py' STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "static", ] My project folder structure: I need import css and js files as static, but django don't see js files, I don't understand what I'm doing wrong. -
How to redirect django to Google directly with Allauth
I don't have a code problem but a little aesthetic, I'm trying to make a simple login to an app with Django and be able to enter with Google and when I put the label to enter I would like it to direct the user directly to Google as it usually is, but the label sends them to an intermediate Allaut interface and then press another button and go, I would like to skip that interface but I've tried and it always directs me there Urls of proyect: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include("allauth.urls")), path('', include("pagina.urls")) ] Urls of app: from django.urls import path from . import views urlpatterns = [ path("", views.home), path("logout", views.logout_view) ] And the button's code: {% load socialaccount %} <h1>Google Login</h1> <a href="{% provider_login_url 'google' %}?next=/">Login with Google</a> -
Very slow queries in Django view for model with a lot of nested relationships
We have a dynamic endpoint that has a huge amount of nested aggregation before fetching all of the records. We've tried indexing the keys, but it didn't seem to make a difference on the speed. We looked at a few different methods of caching things, but because of the scale of the data, it's changing very frequently at a low level. Are there any other options or suggestions that we can try to do to optimize the aggregation of the records? For reference, we have a Job model with a bunch of data about that job. There are a few 1-to-many relationships between Job and some other models such as JobTask. There is also some data we need that has a 1-to-many relationship with JobTask. This means that there is a lot of essentially nested data we need for each job. As the database has grown, this query is getting noticeably slower for the users and we are trying to see if there is anything we can do to optimize it. We tried using the Prefetch() class in all of these prefetch_related() calls but that wasn't any help. Below are the views for the job and job list, which is … -
Considerations when replacing a Mixin with abstract Model subclass?
I have multiple Models that all need some shared functionality. My existing code uses a Mixin class: class MyMixing: some_class_variable = None @classmethod def get_headers(cls): return [field.name for field in cls._meta.fields] # ... and my models look like: class Something(models.Model): name = models.CharField(max_length=50) The above code shows an example, where my IDE shows error, because MyMixin doesn't have _meta. And there are multiple such issues, especially as I'm trying to add some more common functionality So I'm thinking it might be better to replace MyMixin with MyModel: class MyModel(models.Model): class Meta: abstract = True some_class_variable = None @classmethod def get_headers(cls): return [field.name for field in cls._meta.fields] then my models will look like: class Something(MyModel): name = models.CharField(max_length=50) Could this mess up my existing data? Other than database (and, of course, silly typos), is there anything else that might go wrong with that change? -
Server error 500 trying to change password with django-allauth
I have an application (in production) with django 4.2 + postgresql, and I'm using django-allauth==0.54.0 for user control. All this on a ubuntu linux 22.04 server with gunicorn and nginx (with https) When executing the password recovery process, where the user clicks on the login form, on the "forgot my password" option When entering the screen, an email is requested, and after clicking ok, an email is sent that has the following format: Here is an important fact, and it is that the URL that is correctly formed in its fixed part (https://xxxxxxxxxx.cl/accounts/password/reset/key) also has 2 parameters. On the one hand, the uidb36 (which is 1 in this case) and the key (which is brl752-f9faf0b526a88e51cdf550d14048eb8f). So far everything is OK. The problem occurs when the user clicks on the link, and is redirected to the indicated URL, a server error 500 appears. According to the system log that is in /var/log/syslog, the error would be that they are not being receiving the parameters correctly when trying to render the webscrap/templates/account/password_reset_from_key.html file that contains the html code to present the user with the new password entry specifically in: <form action="{% url 'account_reset_password_from_key' uidb36=uidb36 key=key %}" method="post"> This is the error that … -
How can I parse a part of the GET request in Django's function-based view
I am passing to Django's function-based view this URL: <hostname>/display_listing/1 The number 1 in the above URL is an ID field in a database. I would like my function-based view that is triggered with the above URL to parse the ID from the URL (number 1 in this case) so I can use it later to get an entry from the database. My question is how I can parse this ID from the URL? My function_based view currently looks like this: def display_listing(request): print(f"request: {request}\n") ... <more code to come here>... return render(request, 'auctions/test.html', {"id": "id"}) Output: request: <WSGIRequest: GET '/display_listing/1'> The above output tells me that that the view did receive the right ID (number 1), now I need to somehow put it into a variable. I am new to Django, will appreciate any hint. I googled for a solution, did not find it so far. -
Synchronization issue between the Django admin and the RESTful API endpoints
The users I created in the Django admin interface are not showing in the /users/ endpoint and vice versa. Is there any potential synchronization issue between the Django admin and the RESTful API endpoints? Or will it be like this because of serialization? I verified the User Model. Model is correctly saved and migrated to the database. Update #2 Model: class User(models.Model): username = models.CharField(max_length=150, unique=True) email = models.EmailField(unique=True) def __str__(self): return self.username Views for user: @api_view(['GET', 'POST']) def user_list_create_view(request): if request.method == 'GET': users = User.objects.all() print("Users:", users) # Add this debug print serializer = UserSerializer(users, many=True) print("Serialized Data:", serializer.data) # Add this debug print return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @api_view(['GET', 'PUT', 'DELETE']) def user_retrieve_update_delete_view(request, pk): user = get_object_or_404(User, pk=pk) if request.method == 'GET': serializer = UserSerializer(user) return JsonResponse(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': user.delete() return JsonResponse({'message': 'User deleted successfully.'}, status=204) Serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email'] -
413 request etity too large and server error 500
I deploayed my django website and evrything is fine but whent I tried to upload a profile picture I got 413 request entity too larg nginx 1.18.0(ubuntu) this error apear after I turned DEBUG = True DEBUG_PROPAGATE_EXCEPTIONS = True Then after that I ried to solve that by specifying this first I opned nano /etc/nginx/nginx.conf seconde I put this in the http client_max_body_size 100M; and last I restart the nginx by using systemctl restart nginx this actually fixed that 413 error but I faced an other one which is server error (500) I really don't know what should I do with this I tried a lot of things but it didn't work please someone coz I'm stuck here -
Django template not recognizing getattr
I´m want to display dinamically a table in a html template. In the view I have: def get_object( request ): objects = MyObject.objects.all() return render(request, 'table.html', { 'myObjects':objects, 'fields':ObjectAdmin.list_display}) then in 'table.html' <thead class="tables-success"> <tr> {% for field in fields %} <th>{{ field }}</th> {% endfor %} </tr> </thead> {% for row in myObjects %} <tr> {% for field in fields %} <td>{{ getattr(row, field) }}</td> <!--<td>{{ row|getattr:field }}</td>--> {% endfor %} </tr> {% endfor %} and in admin.py class MyObjectAdmin(admin.ModelAdmin): list_display = [ 'name']# list_per_page = 8 search_fields = [ 'name'] admin.site.register( Object, MyObjectAdmin ) but I m receiving the below error: Could not parse the remainder: '(row, field)' from 'getattr(row, field)' or Exception Value: Invalid filter: 'getattr' if I use {{ row|getattr:field }} -
Forbidden (CSRF token missing.)
I am working in a Django project and when I run the code below I get this error in the VSCode console: Forbidden (CSRF token missing.): /edit_post/33 [19/Jul/2023 11:12:20] "POST /edit_post/33 HTTP/1.1" 403 2506 Please find below the basics of my code: edit_post.html {% extends "network/layout.html" %} {% block body %} <h2>Edit Post</h2> <form id="edit-post-form" action="{% url 'edit_post' post.id %}" method="post" data-post-id="{{ post.id }}"> {% csrf_token %} <div class="form-group"> <textarea class="form-control" name="content" rows="3">{{ post.content }}</textarea> </div> <button class="btn btn-primary" type="submit">Save Changes</button> </form> <!-- Javascript code for saving the post --> <script> document.getElementById('edit-post-form').addEventListener('submit', function (event) { event.preventDefault(); // Prevent form submission var form = event.target; var postId = form.getAttribute('data-post-id'); var content = form.elements['content'].value; var csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value; var xhr = new XMLHttpRequest(); xhr.open('POST', form.action, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('X-CSRFToken', csrfToken); xhr.onload = function () { if (xhr.status === 200) { var response = JSON.parse(xhr.responseText); if (response.success) { // Post updated successfully, redirect to index page window.location.replace('/'); } else { // Handle error response (if applicable) console.error(response.message); } } else { // Handle non-200 status codes (if applicable) console.error('Error saving post'); } }; xhr.onerror = function () { // Handle request error (if applicable) console.error('Error saving post'); }; var requestData = 'content=' + … -
How Django fills Model instance?
It's interesting how Django fills Model instance with values from database? Let's imagine we have model: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") When I did some research on Django source code I met descriptor DeferredAttribute in model fields https://github.com/django/django/blob/68912e4f6f84f21322f92a2c7b6c77f68f91b9c9/django/db/models/query_utils.py#L155. I can see there is __get__ magic method. But no __set__. Does Django fills directly __dict__ of Model instance or how? Could you please explain the process from request (q = Question.objects.get(id=1)) to instance manipulation like print(q.question_text)? -
Dockerfile in Python for Playwright Chromium, installing error
I am trying to add playwright with chromium to a django project. I modify my docker to include the installation of playwright with chromium. When i use docker-compose up --build and then execute the function that use playwright i get the following error: playwright._impl._api_types.Error: Executable doesn't exist at /usr/bin/chromium-1067/chrome-linux/chrome ╔════════════════════════════════════════════════════════════╗ ║ Looks like Playwright was just installed or updated. ║ ║ Please run the following command to download new browsers: ║ ║ ║ ║ playwright install ║ ║ ║ ║ <3 Playwright Team ║ ╚════════════════════════════════════════════════════════════╝ I checked the files inside my docker and in the path /usr/bin/ i found chromium-1071 installed. I dont know how playwright is checking for the specific path chromium-1067 and i also dont know why it installed chromium-1071. I need help with the correct implementation of playwright in my django project. This is my Dockerfile FROM public.ecr.aws/docker/library/python:3.9 ARG ENVIRONMENT=default ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apt-get update && apt-get install -y supervisor curl wget gnupg unzip RUN pip install playwright ENV PLAYWRIGHT_BROWSERS_PATH=/usr/bin RUN playwright install-deps chromium RUN playwright install chromium COPY start-container.sh /usr/local/bin/start-container.sh COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf RUN chmod +x /usr/local/bin/start-container.sh COPY requirements.txt /app/ RUN pip install --upgrade pip RUN pip install "setuptools<58.0.0" RUN pip install … -
template does not recognize base and does not display content
{% load menu %} <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> {% block title %} {% endblock %} </title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <nav class="max-w-4xl mx-auto py-4 px-6 flex itens-center justify-between bg-blue-400 mt-1"> <div class="logo"> <a href="/" class="text-2xl text-white">Pedido Easy</a> </div> <div class="menu flex space-x-4"> {% menu %} </div> </nav> <div class="max-w-4xl mx-auto py-4 px-6"> {% block content %} {% endblock %} </div> </body> </html> O código acima mostra o arquivo "base.html" que é usado como template padrão para que as outras páginas possam ser feitas puxando o código dessa. Já o código abaixo mostra o arquivo "vendor_detaisl" que é a página de exibição do fornecedor do produto e seus produtos, o erro acontece quando é tentado mostrar os produtos que o fornecedor cadastrou,onde é mostrado apenas o nome do forncedor (usuário que cadastrou os produtos): {% extends 'core/base.html' %} {% block title %} {% firstof user.get_full_name user.username %} {% endblock %} {% block content %} <h1 class="text-2xl"> {% firstof user.get_full_name user.username %} </h1> <div class="flex flex-wrap"> {% for product in user.products.all %} <div class="product w-1/3 p-2"> <div class="p-4 bg-gray-100"> <a href="{% url 'product_details' product.category.slug product.slug %}"> {% if product.image%} <div class="image" mb-4> <img src="{{product.image.url}}" height="400" … -
Why is my form data not saved in database?
When I fill out the form in Django 4.2.3 the data is not saved in database (sqlite3). I didn't use {{ form }} because option to hide fields based on selected options is not working. models.py: from django.db import models opciones_entrega = [ (0, "Retiro en Tienda"), (1, "Reparto a domicilio") ] opcion_retiro = [ (2, "Retiro Local"), (3, "Retiro bodega") ] class Reparto(models.Model): opcion_entrega = models.CharField(max_length=1, choices=opciones_entrega, default="0") num_venta = models.IntegerField() fecha_venta = models.DateField() nombre_cliente = models.CharField(max_length=60) direccion = models.CharField(max_length=150) telefono = models.IntegerField() articulos = models.TextField(max_length=300) fecha_entrega = models.DateField() fecha_retiro = models.DateField() opcion_retiro = models.CharField(max_length=1, choices=opcion_retiro, default="2") observacion = models.TextField(max_length=200) def __str__(self): return self.nombre_cliente forms.py: from django import forms from .models import Reparto class RepartoForm(forms.ModelForm): opciones_entrega = [ (0, "Retiro en Tienda"), (1, "Reparto a domicilio") ] opcion_retiro = [ (2, "Retiro Local"), (3, "Retiro bodega") ] opcion_entrega = forms.ChoiceField(choices=opciones_entrega, widget=forms.RadioSelect) opcion_retiro = forms.ChoiceField(choices=opcion_retiro, widget=forms.RadioSelect) class Meta: model = Reparto fields = '__all__' widgets = { 'fecha_venta': forms.DateInput(attrs={'type': 'date'}), 'fecha_entrega': forms.DateInput(attrs={'type': 'date'}), 'fecha_retiro': forms.DateInput(attrs={'type': 'date'}), } views.py: from django.shortcuts import redirect, render from .models import Reparto from .forms import RepartoForm from django.http import HttpResponse, HttpResponseRedirect def home(request): if request.method == 'POST': form = RepartoForm(request.POST) if form.is_valid(): form.save() return redirect('vista') … -
Prefetching or Selecting a single model from a ManyToMany field for use in a Serializer
We have a model with a ManyToMany through table like such class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through="Membership", through_fields=("group", "person"), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) On our Group view we would like to create a single-model access to the Membership model based on request.user so that our serializer can access fields of the pivot table like class GroupSerializer(serializers.ModelSerializer): user_name = serializer.CharField(source='memberships.user.name') I have tried a query such as Group.objects.filter(user=request.user).annotate( request_user_membership=Subquery(Membership.objects.filter(group_id=OuterRef('id'), user_id=request.user.id)) ) so that I might be able to reference the single object like class GroupSerializer(serializers.ModelSerializer): user_name = serializer.CharField(source='request_user_membership.user.name') however it does not seem that you can use subqueries like this. This seems like a common problem so I was hoping you all might have some ideas. Any help is greatly appreciate -
why am I getting TypeError: string indices must be integers, not 'str' on Django Deserialization?
I'm trying out using AJAX to implement tags for Book Blog posts. I want to use TDD to check and make sure that they filter properly but am running into issues. Mainly when I try and Deserialize the JSONResponse content, it throws an error when I try and iter through it. error message: File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\python.py", line 111, in Deserializer Model = _get_model(d["model"]) ~^^^^^^^^^ TypeError: string indices must be integers, not 'str' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\04_projects\01_Python\10_book_blog\posts\tests\test_views.py", line 103, in test_returns_filtered_posts for obj in decereal: File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError test case that makes the error: def test_returns_filtered_posts(self): # makes one post with a tag and one post without t1 = Tag.objects.create(tag_name='test', group_name='general') p1 = Post.objects.create(book_title='test_book') p2 = Post.objects.create(book_title='test_book2') p1.tags.add(t1) # simulates clicking the 'test' tag response = self.client.post(reverse('ajax_post'), {'tag[]': ['test', 'general']}) # decerealizes the data decereal = deserialize('json', response.content) # print for debugging for obj in decereal: print(obj) # bad test case but not getting this far self.assertNotIn(p2, decereal) The view that is called: def ajax_call(request): data = serializers.serialize('json', Post.objects.all()) # … -
Django: how select items that do not have referencies from other items?
Assume, we have a model: class Critters(models.Model): name = models.CharField() parent = models.ForeignKey(Critters, blank=True, null=True, on_delete=models.CASCADE) In begin was some critters: id Name Parent == ======== ======== 0 Critter1 1 Critter2 2 Critter3 And then, some critters made a children: id Name Parent == ======== ====== 0 Critter1 1 Critter2 2 Critter3 3 Child1 0 4 Child2 1 I wand make a request for select all parents without childrens (i.e. no creatures with parents, and no parents with existing childrens): id Name Parent == ======== ====== 2 Critter3 I think it can be done with annotate and exact django's directives, but i'm dubt in stick how exactly i can make this... UPDATE1 Ofcourse, critter and child in field Name just for example, we can't filter table by Name. -
Image file not being uploaded to media file
I'm trying to display an input type="file" that accepts image files. When i upload the file through Django Admin, everything works (its uploaded to my media folder, and its successfully displayed on html) but when i do it through my html page, it doesnt go to media, and i can't display it. So i'm assuming the problem isnt with django but my settings.py or something with my html HELP create.html (to upload image) <label for="imgpreview" class="imglabel">Choose Image</label> <input accept="image/*" type='file' id="imgpreview" name="imgpreview" class="image-form" onchange="previewImage(event);"/> index.html (to display image) <div class="banner-image"><img id="model-img-display" src="{{item.image.url}}"></div> views.py (to save model) def create(request): if request.method == 'POST': title = request.POST['title'] image = request.POST['imgpreview'] category = request.POST['category'] brand = request.POST['brand'] color = request.POST['color'] clothes = Clothes(title=title, image=image, category=category, brand=brand, color=color) clothes.save() return render(request, "wardrobe/create.html") models.py class Clothes(models.Model): title = models.CharField(max_length=50) image = models.ImageField(default='', upload_to='wardrobe/') #wardrobe= media subfolder category = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) color = models.CharField(max_length=200, null=True, blank=True) deleted = models.BooleanField(default=False) settings.py MEDIA_URL='/media/' MEDIA_ROOT= BASE_DIR/'project5'/'wardrobe'/'media' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('wardrobe.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) EDIT: i changed my views.py following https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html instructions and now everything works! -
No reverse match with comments
I want to display my comment form in my page. However, every time i enter the page i get no reverse match error. Maybe there is something to do with form action, but honestly I have no idea what to do. Please help! views.py def single_blog(request, pk): news = News.objects.filter(pk=pk) comment_form = CommentForm() context = { 'title': 'Новость', 'news': news, 'comment_form': comment_form } return render(request, 'blog/single-blog.html', context) def save_comment(request, pk, new_pk): form = CommentForm(request.POST) if form.is_valid(): form.instance.new_id = new_pk comment = form.save() return redirect('single-blog', pk) models.py class Comments(models.Model): post = models.ForeignKey(News, on_delete=models.CASCADE) author = models.CharField(max_length=255, verbose_name='Автор') text = models.TextField(max_length=255, verbose_name='Текст') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') urls.py path('single-blog/<int:pk>', single_blog, name='single-blog'), path('save_comment/<int:pk>', save_comment, name='save_comment') html Leave a Reply <form class="form-contact comment_form" action="{% url 'save_comment' new_pk %}" id="commentForm"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ comment_form.author }} </div> </div> <div class="col-12"> <div class="form-group"> {{ comment_form.text }} </div> </div> </div> -
VSCode debugpy with dockerized django app
I'm trying to use debugpy with a dockerized django app - it connects momentarily then disconnects - I'm not sure why docker-compose.backend.yml: (the uplifty service below is the django server I want to attach to from vscode) version: '3' services: db: image: postgres platform: linux/amd64 container_name: uplifty-db environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" uplifty: build: context: . dockerfile: ./docker/Docker.server/Dockerfile image: uplifty env_file: .env container_name: uplifty volumes: - .:/code ports: - "8000:8000" - "5678:5678" depends_on: - db links: - db:postgres Dockerfile: FROM python:3.11.3 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ sudo && apt-get install -y \ git \ nginx \ postgresql-client \ supervisor RUN mkdir /code ADD docker /code RUN rm /etc/supervisor/supervisord.conf && \ ln -s /code/docker/Docker.server/supervisord.conf /etc/supervisor/supervisord.conf && \ rm /etc/nginx/nginx.conf && \ ln -s /code/docker/Docker.server/nginx.conf /etc/nginx/nginx.conf && \ mkdir -p /var/log/supervisor && \ mkdir -p /var/log/gunicorn && \ mkdir -p /code/logs/supervisord RUN groupadd -r app -g 1000 && \ useradd -u 1000 -r -g app -d /code -s /bin/bash -c "Docker image user" app RUN chown -R app:app /code && \ chown -R app:app /var/run && \ chown -R app:app /var/log/gunicorn RUN pip install psycopg2 RUN pip install poetry RUN pip install gunicorn ADD server/pyproject.toml … -
Django 4 Running some python codes/files outside views for specific request and returning the parameters as context before rendering template
I am relatively new to Django, while I am fine with loading static pages etc, I have an issue with complex dynamic content. I am designing a quiz, when a user answers a question, I would like to log some parameters into the database (correct or wrong, time taken for the response, etc). When the user clicks next, I want to analyse the data from the answer to the previous question, apply an algorithm and select the question and its parameters as context to the template so that the next question is loaded. So far, I have created a config.py that lets me take the parameters (context) from quiz.py and use them in views.py. Both config.py and quiz.py are in the main folder of the Quiz App. The problem I have is how to read and analyse the user session and data in my quiz.py so that I could apply the algorithm based on the user's previous answers and performance on the database. I have looked at many forums, videos, etc but not even sure if I am on the right path. I have looked at Middleware, Threading, using Celery, etc and I cannot get the user data from "request" … -
Django Define serializer for Model in relation using Foreign Key
I am having 3 models, Site which basically contains Site Details, Comments which contains the the comments and replies to a particular site and Files which contains all the attachments. I wanted to get all the necessary fields from Comments and Files Model, for which I am trying to use a Serializer in Site Details Models. Below is my models.py - **Site:** site = models.CharField(max_length=30, blank=False, null=False) approver = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="design_site_approver", blank=True, null=True) submitter = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="design_site_submitter", blank=True, null=True) **Files** site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='site_name') **Comment** user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_name_comment') timestamp = models.DateTimeField(default=datetime.datetime.now) remarks = models.TextField(null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies') site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='site_name_comment') My Serializer.py file are: **Comment** class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' **Files** class FileSerializer(serializers.ModelSerializer): class Meta: model = Files fields = '__all__' **Site** class SiteSerializer(serializers.ModelSerializer): remarks = CommentSerializer(many=True,read_only=True) attachment = FileSerializer(many=True,read_only=True) class Meta: model = Site fileds = '__all__' I am unable to get the Values of Files and Comment object, but I am not getting any error as well. What is the solution for this -
How to move django models from one app to another
So we have a django backend already in production with a reasonable amount of data.During the initial stages, we had a small team of two and we were also working with deadlines. I would also admit we were beginners and didn't follow best practices.Because of this,all our models were defined in one app.Now the project is messy and I also learnt it is not a good practice to have many models in one app.Now my question is,how can we move some of this models to new different apps in our project without running into migration issues or worse loosing the data? Our models also have a lot of relationships.Just for reference,we are using postgres databases. I have reasearched the internet for solution but haven't found a comprehensive approach to doing it.Most of the answers here also seems outdated.Some people also recommend to use south which is deprecated. -
I cannot get a list of CSV files and their headers at the same time
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from .models import CSVFile from .serializers import CSVFileSerializer import csv ... class CSVFileListView(APIView): def get(self, request, format=None): files = CSVFile.objects.all() file_data = [] for file in files: columns = self.extract_columns(file) # Извлекаем информацию о колонках file_data.append({ 'id': file.id, 'filename': file.file.name, 'uploaded_at': file.uploaded_at, 'columns': columns # Добавляем информацию о колонках в список файлов }) return Response(file_data, status=status.HTTP_200_OK) def extract_columns(self, file): with open(file.file.path, 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file) columns = next(csv_reader, []) # Извлекаем первую строку, содержащую заголовки колонок return columns class CSVFileDetailView(APIView): def get(self, request, file_id, format=None): try: file = CSVFile.objects.get(id=file_id) with open(file.file.path, 'r', encoding='utf-8') as csv_file: dialect = csv.Sniffer().sniff(csv_file.read(1024)) csv_file.seek(0) csv_data = list(csv.reader(csv_file, dialect=dialect)) columns = csv_data[0] data = csv_data[1:] response_data = { 'columns': columns, 'data': data } return Response(response_data, status=status.HTTP_200_OK) except CSVFile.DoesNotExist: return Response({'error': 'File not found'}, status=status.HTTP_404_NOT_FOUND) Error occurred while getting the list of all files using GET: UnicodeDecodeError at /api/v1/csv/files/ 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/csv/files/ Django Version: 4.1.5 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte Exception Location: , line 322, …