Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting this Error PermissionError: [Errno 13] Permission denied: '/app/manage.py' in Docker
I am encountering a PermissionError when trying to run the docker compose run command for creating a Django project within a Docker container. The error message is as follows :- docker compose run --rm app sh -c "django-admin startproject myproject ." [+] Building 0.0s (0/0) docker:desktop-linux [+] Building 0.0s (0/0) docker:desktop-linux Traceback (most recent call last): File "/py/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/py/lib/python3.9/site-packages/django/core/management/commands/startproject.py", line 21, in handle super().handle("project", project_name, target, **options) File "/py/lib/python3.9/site-packages/django/core/management/templates.py", line 205, in handle with open(new_path, "w", encoding="utf-8") as new_file: PermissionError: [Errno 13] Permission denied: '/app/manage.py' . . . And this is my Dockerfile :- FROM python:3.9-slim ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home app ENV PATH="/py/bin:$PATH" USER app . . and this is my docker-compose.yml file :- services: app: build: context: . image: my-django-image ports: - 8000:8000 volumes: - ./app:/app command: > i tried … -
DJANGO Models based on MYSQL tables... :(
I have been working a bit with DJANGO, and I've encountered a somewhat serious issue. I'll start by saying that I'm trying to connect my MYSQL database to DJANGO, but when creating the models in PYTHON, well, they haven't turned out quite right. I'm new to this, so I don't really know how to handle M:N relationships in DJANGO. I tried some things, but when accessing from the ADMIN, it gives me an error, for example: OperationalError at /admin/Core/capctinstr/ (1054, "Unknown column 'CAPCT_INSTR.id' in 'field list'") I would greatly appreciate it if someone could help me with this. :( `-- -------------------------------------------------------------------------- -- -- Tabla: PUESTO CREATE TABLE PUESTO ( Codigo CHAR(4) PRIMARY KEY, Nombre VARCHAR(40) NOT NULL, Descripcion VARCHAR(320) NOT NULL ); -- Tabla: DEPARTAMENTO CREATE TABLE DEPARTAMENTO ( Codigo CHAR(4) PRIMARY KEY, Nombre VARCHAR(40) NOT NULL, Descripcion VARCHAR(320) NOT NULL, NumExtension VARCHAR(4) NOT NULL UNIQUE, FechaCreacion DATE DEFAULT(CURRENT_DATE) ); -- Tabla: PUESTO_DEPTO`your text` CREATE TABLE PUESTO_DEPTO ( Puesto CHAR(4), Departamento CHAR(4), PRIMARY KEY (Puesto, Departamento), FOREIGN KEY(Puesto) REFERENCES PUESTO(Codigo), FOREIGN KEY(Departamento) REFERENCES DEPARTAMENTO(Codigo) ); -- Tabla: EMPLEADO CREATE TABLE EMPLEADO ( Numero INT PRIMARY KEY AUTO_INCREMENT, NombrePila VARCHAR(60) NOT NULL, ApPaterno VARCHAR(60), ApMaterno VARCHAR(60), NumTel VARCHAR(15), Puesto CHAR(4), Departamento … -
I am creating a Django budgeting website and my changing status is not working, can anyone help me?
view-bills-admin.html {% extends "base/room_home.html" %} {% block content %} <div class="container d-flex align-items-center justify-content-center" style="min-height: 100vh;"> <div class="text-center"> <h1>{{ room_bills.title }}</h1> <p>Due: {{ room_bills.due }}</p> <div class="col-3"> <h3>Paid Members: </h3> <ul> {% for submission in submissions %} <li> <a href="proof/{{ submission.user.id }}" target="_blank">{{ submission.user.username }} {{ submission.text }}</a> <form> <label for="status">Status:</label> <select name="status" id="{{ submission.id }}" onblur="postStatus('{{ submission.id }}')"> <option value="P">Pending</option> <option value="A">Accepted</option> <option value="R">Rejected</option> </select> </form> </li> {% endfor %} </ul> </div> <div class="col-3"> <h3>Did not pay members: </h3> <ul> {% for user in did_not_submit %} <li>{{ user.username }}</li> {% endfor %} </ul> </div> </div> </div> <script> // Move the function outside the DOMContentLoaded event listener function postStatus(submissionId) { const selectElement = document.getElementById(submissionId); const status = selectElement.value; fetch(`/room/{{ room.join_code }}/bills/{{ bills.slug }}/status/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "submissionId": submissionId, "status": status }) }); } </script> {% endblock %} views.py @csrf_exempt def remark_proof_api(request, room_id, bills_slug): if request.method == "POST": data = json.loads(request.body.decode("utf-8")) submission_id = data["submission_id"] status = data["status"] sub = Submission.objects.get(id=int(submission_id)) sub.status = status sub.save() return JsonResponse({"success": True}) urls.py path('room/<str:room_id>/bills/<str:bills_slug>/status/', views.remark_proof_api, name='remark-proof'), I want the status to be changed but it doesnt work, everytime i refresh it keeps on going back to pending which is … -
Django load static tag not showing image
Tried viewing image on my browers but all i can see is the image placeholder. Here is the template code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST" style="background-color: rgb(201, 201, 24); padding: 10px;"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit"> </form> {% load static %} <img src="{% static 'myapp/mini.jpg}" alt="My image"/> </body> </html> in the settings i have: STATIC_URL = 'static/' STATICFILES_DIRS = [ 'myapp/static', ] STATIC_ROOT = 'static/' What can be the issue? I have tried renaming the folders and rearranging the image location but non helped. -
AddPage function in django making a new page but not redirecting to it - NoReverseMatch error
I'm trying to create a function that will make a new entry in a wikipedia website. So far the code I have will make the entry (i.e. if you go through the form to make the page, it will show up in the list of pages on the home screen) but instead of bringing you to the page when you hit submit, it shows me a NoReverseMatch error. It's saying "reverse for 'entry' not found. 'entry' is not a valid view function or pattern name." All I need it to do is redirect to the new page, but I can't figure out why it's saying entry isn't a valid view function? I have a function titled entry to hold the previous entries, but I'm having trouble connecting the issue. VIEWS.PY def entry(request, title): html_content = convert_md_to_html(title) if html_content == None: return render(request, "encyclopedia/error.html", { "message": "This entry does not exist." }) else: return render(request, "encyclopedia/entry.html", { "title": title, "content": html_content }) class AddPageForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", })) def add_page(request): form = AddPageForm() # <- called at GET request if request.method == "POST": form = AddPageForm(request.POST) # <- called at POST request if form.is_valid(): title … -
Django Form(Formset) is not working - id is missing?
My template form does not save the objects. here is my view: class FeatureDeliveryEditView( LoginRequiredMixin, PermissionRequiredMixin, SingleObjectMixin, FormView ): permission_required = "auth.can_access_supervising_sections" model = FeatureFilm template_name = "project/project_update/feature/update_featurefilm_delivery.html" def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def get_form(self, form_class=None): return FeatureDeliveryFormSet(**self.get_form_kwargs(), instance=self.object) def form_valid(self, form): form.save() messages.success(self.request, "Delivery erfolgreich gespeichert") return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): messages.error( self.request, f"Delivery nicht gespeichert: {form.errors}" ) return super().form_invalid(form) def get_success_url(self): return ( reverse("feature-detail-deliveries-half", kwargs={"pk": self.object.pk}) + "#content-start-under-cards" ) def handle_no_permission(self): return redirect("access-denied") and here is my form and formset: class FeatureDeliveryForm(ModelForm): class Meta: model = Delivery exclude = ( "feature_id", "tv_movie_id", "tv_serie_block_id", "restoration_id", "source_material", "scan_info", "usage_version", "orderer_id", "receiver_1_id", "receiver_2_id", "receiver_3_id", ) widgets = { 'trade_mark_brand': forms.Textarea(attrs={'rows': 1}), 'audio_channel_assignment': forms.Textarea(attrs={'rows': 1}), 'notes': forms.Textarea(attrs={'rows': 1}), # ... Andere Widgets hier } FeatureDeliveryFormSet = inlineformset_factory( FeatureFilm, Delivery, form=FeatureDeliveryForm, can_delete=True, ) if i used this template the form will be saved and all is working: {% extends "_base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row py-5"> <h3 class="text-center">{{ object }} - Delivery hinzufügen/editieren</h3> </div> <div class="row"> <form method="post" enctype="multipart/form-data"> {% for hidden_field in form.hidden_fields %} {{ … -
How to make django not send a `Content-Disposition` header?
I am trying to serve a static svg file on my local Django server. The file is quite large so I don't want to put it directly into my HTML. It shows This XML file does not appear to have any style information associated with it. The document tree is shown below. And then my svg. I have tried adding the following code in case Django couldn't identify svgs: import mimetypes mimetypes.add_type("image/svg+xml", ".svg", True) mimetypes.add_type("image/svg+xml", ".svgz", True) but it didn't help. It just served with the correct mime type. I believe the problem is in the Content-Disposition header, because compare the two responses: curl -i https://www.google.com/chrome/static/images/chrome-logo-m100.svg: HTTP/2 200 accept-ranges: bytes vary: Accept-Encoding, Sec-Ch-Ua-Full-Version-List, Sec-Ch-Ua-Platform, Sec-Ch-Ua-Platform-Version, Sec-CH-Prefers-Reduced-Motion content-type: image/svg+xml content-security-policy-report-only: require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/uxe-owners-acl/chrome cross-origin-resource-policy: cross-origin cross-origin-opener-policy-report-only: same-origin; report-to="uxe-owners-acl/chrome" report-to: {"group":"uxe-owners-acl/chrome","max_age":2592000,"endpoints":[{"url":"https://csp.withgoogle.com/csp/report-to/uxe-owners-acl/chrome"}]} content-length: 2303 date: Sun, 26 Nov 2023 20:19:47 GMT expires: Sun, 26 Nov 2023 20:19:47 GMT cache-control: private, max-age=31536000 last-modified: Wed, 02 Mar 2022 19:00:00 GMT x-content-type-options: nosniff accept-ch: Sec-Ch-Ua-Full-Version-List, Sec-Ch-Ua-Platform, Sec-Ch-Ua-Platform-Version, Sec-CH-Prefers-Reduced-Motion critical-ch: Sec-Ch-Ua-Full-Version-List, Sec-Ch-Ua-Platform, Sec-Ch-Ua-Platform-Version, Sec-CH-Prefers-Reduced-Motion server: sffe x-xss-protection: 0 alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000 <svg fill="none" height="63" viewBox="0 0 63 63" width="63" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><linearGradient id="a" gradientUnits="userSpaceOnUse" x1="34.9087" x2="7.63224" y1="61.029" y2="13.7847"><stop offset="0" stop-color="#1e8e3e"/><stop offset="1" stop-color="#34a853"/></linearGradient><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="26.9043" x2="54.1808" … -
Wagtail, change allowed extensions for WagtailImageField
I'm trying to add extra extensions wagtail.images.fields.WagtailImageField How it can be done? I've tried https://docs.wagtail.org/en/stable/reference/settings.html#wagtailimages-extensions , but seems like this is not the correct option -
Dynamic data for test with model_bakery
How to orginize dynamic data for a test using model_bakery? route_application_requester = Recipe( ApplicationRequester, form_applicant=cycle(FormChoices.values), inn=gen_inn, ) I need gen_inn to get the value from form_applicant, which can be entity or entrepreneur, and generate 10 or 12 digits depending on it. -
Am having errors anytime i want to carry out an installation with pip, i cant even install virtual environment
Been trying to carry out installations with pip but have been having errors, with virtual environment it keeps showing me could not find a version that satisfied the requirement vitualenv. I tried solving it with YouTube videos, i was instructed to add path to system environment but is still did not work -
I am trying to build a social app, where users can post, join groups, add groups etc. but im stuck with an error
I am trying to make a user to be able to see the group details whenever they click on the group name from the group lists, just like facebook. but the slug isn't working i am getting this error.** Reverse for 'single_group' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['group/posts(?P<slug>[\w-]+)/$']** group models.py from django.db import models from django.urls import reverse from django.utils.text import slugify from django import template from django.contrib.auth import get_user_model register = template User = get_user_model() class Group(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(unique=True) description = models.TextField(max_length=300, blank=True, default= '') description_html = models.TextField(editable=False, default= '', blank=True) members_field = models.ManyToManyField(User, through= 'Group_member') def get_absolute_url(self): kwargs = {'slug':self.slug} return reverse('single-group', kwargs=kwargs) class Meta: ordering = ['name'] class Group_member(models.Model): group = models.ForeignKey(Group, related_name='membership', on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_group', on_delete= models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = ('group', 'user') group views.py i made use of Class base view for this project from typing import Any from django.shortcuts import render from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from . import models from django.urls import reverse from django.contrib import messages from django.shortcuts import get_object_or_404 from django.db import IntegrityError class Create_group(generic.CreateView, LoginRequiredMixin): model = models.Group fields = ('name', … -
How can I change the header color and language in django-import-export?
I have a resource to export class RequestResource(resources.ModelResource): class Meta: model = Request fields = ("service__name","user_name","user_address","user_number","user_email","region__name","tariff__name",'status','employee','comment','creation_date','type','connection_status') How do I export the names that are specified in verbose_name? Is it also possible to change colors in excel? -
django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query') in my remote web app
I have been working on a django chatting application. The link to the site is https://aniconnect.org so you can check it out if you want to see the error in action. So I am using django-channels for websockets and the websocket connection is being opened and closed instantly. I just checked it out in my console logs. The following is the consumers.py file: from channels.generic.websocket import AsyncWebsocketConsumer import json from django.contrib.auth.models import User from .models import ChatRoom, Message, Profile from asgiref.sync import sync_to_async @sync_to_async def save_message_to_database(chatroom_name, username, message): try: chatroom = ChatRoom.objects.get(name=chatroom_name) user = User.objects.get(username=username) user_profile = Profile.objects.get(user=user) new_message = Message.objects.create(chat_room=chatroom, sender=user_profile, content=message) print("Message saved to DB:", new_message) except ChatRoom.DoesNotExist: print(f"Chatroom with name '{chatroom_name}' does not exist.") except Profile.DoesNotExist: print(f"User profile with username '{username}' does not exist.") except Exception as e: print(f"Error occurred while saving the message: {e}") @sync_to_async def get_chatroom_by_name(name): try: return ChatRoom.objects.get(name=name) except ChatRoom.DoesNotExist: return None @sync_to_async def get_messages_for_chatroom(chatroom): return list(Message.objects.filter(chat_room=chatroom).order_by('timestamp')) class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() print(f"WebSocket connection opened for room: {self.room_name}") chatroom = await get_chatroom_by_name(self.room_name) if chatroom: print(f"Chatroom: {chatroom.name}") else: print(f"Chatroom '{self.room_name}' not found.") messages = await get_messages_for_chatroom(chatroom) for message in messages: … -
Recursive Query with Django-CTE
I have a Tree model that i need to prefetch all the childs and user of the comments all at once: class AnalysisComment(MPTTModel, TimeStampMixin): parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE, help_text=_("User who created the blog."), related_name="analyses_comments", ) text = models.TextField(_("Text")) analysis = models.ForeignKey( Analysis, verbose_name=_("Analysis"), related_name="comments", on_delete=models.CASCADE, ) objects = CTEManager() now this is how I'm getting the analyses with comments: def recursive_comments(cte): return ( AnalysisComment.objects.filter(level=0) .union( cte.join(AnalysisComment, parent=cte.col.id), all=True, ) ) cte = With.recursive(recursive_comments) comments = cte.join(AnalysisComment, id=cte.col.id).with_cte(cte) qs = Analysis.objects.prefetch_related( "tags", "playlists", Prefetch("comments", queryset=comments, to_attr="parent_comments"), ) and i call the childs with obj.child.all() in my serializers. now there are a lot of duplicate objects in the response. and also calls a query for each comment: -
django.urls.reverse() matching URL pattern instead of name
I am coding a Django project for a Wikipedia-like site (CS50W project 1). I have one app inside the project called encyclopedia. Inside my views.py file for this app, I have a redirect, for which I use the django.urls.reverse() function. The link to the documentation for this function can be found here. Now for the problem: If the user visits /wiki/file where file is not a valid page, then the markdown file will not be found in the entry view. And, as you can see, it is supposed to redirect you to the not found page. However, the code return HttpResponseRedirect(reverse("notfound")) loops the user back to the entry view indefinitely, instead of the user being redirected to the not found page. I have found two solutions so far: One can reorder the URL patterns so that the notfound pattern appears before the entry pattern, or a slash can be added to either of the aforementioned URL patterns. I am, however, looking for the cause of the problem. I am currently considering the possibility that the reverse() function is using the URL pattern instead of the name for some reason. urls.py file for encyclopedia: from django.urls import path from . import … -
Django usage and plugins ecosystem
Why there is a drop in use of django in the world? New plugins count, maintain of existing plugins are lacking more and more. Django is very user friendly. This is crazy, stackoverflow.com says it needs at least 220 characters. Can't a question be small than 220 characters? Crazy stuff. -
How can I make a content based movie recommendation system with Django real-time data?
I am working on a project for my school. I have a Django program where I keep information about 1 million movies in Model Movie with features like title, genre and actors. models.py class Genre(models.Model): title = models.CharField(max_length=255) class Actor(models.Model): name = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) genre = models.ManyToManyField(Genre) actors = models.ManyToManyField(Actors) I am trying to create a celery function to train my model once in a day at 12 AM. tasks.py @shared_task def train_and_save_video(): movie_data = Movie.objects.all().exclude(actors__isnull=True, genre__isnull=True) features = movie_data.values_list('id', 'title', 'actors__name', 'genre__title') # over to you, I think we can go with TfidfVectorizer, RandomForestClassifier using pipeline # or cosine_similarity using CountVectorizer and csr_matrix but I don't think so that, this is a good approach. I want the program to learn a little bit each time I add a new movie (concatenate a new movie object to the trained model), without making it learn from scratch with all the movies every time. Can someone explain how to do this? May be we can achieve this using signals.py or admin.py -
Running own conftest for every application
I have several applications in my project each application has its own tests: app/tests/test_block1.py test_block2.py ... And every tests folder has its own conftest.py I want to drop database for every app. I use this fixture: @pytest.fixture(scope="package") def django_db(django_db_blocker): with django_db_blocker.unblock(): call_command("sqlflush") with django_db_blocker.unblock(): call_command("migrate", "--noinput") yield None Scope function and class does not fits for me. I tried module scope and all tests outside a single file fails. I tried package scope and all tests outside a single folder fails. I tried session scope and behaviour was the same. What will be the good variant in my case? Is there any variant except writting one big conftest file instead of different conftest files for every application? -
Multiple NoReverseMatch errors at password reset Django
I'm working on Django project, still new at Django. I'm trying to follow instructions from this book but there are some changes in my project. I'm trying to create login/registration with Django, but I'm stuck with reset password section. I know that my problem is related to name spacing but cannot figure out why is that and why isn't redirecting to pages mentioned in errors. I have two errors: Error 1: NoReverseMatch at /password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. Error 2: NoReverseMatch at /reset/MQ/set-password/ Reverse for 'password_reset_complete' not found. 'password_reset_complete' is not a valid view function or pattern name. urls.py from django.urls import path, include from . import views from .feeds import LatestLessonsFeed from django.contrib.auth import views as auth_views app_name = 'learning_app' urlpatterns = [ #lessons path('', views.lesson_list, name='lesson_list'), path('<int:year>/<int:month>/<int:day>/<slug:lesson>/', views.lesson_detail, name='lesson_detail'), #tags path('tag/<slug:tag_slug>/', views.lesson_list, name='lesson_list_by_tag'), #feed path('feed/', LatestLessonsFeed(), name='post_feed'), # previous login view # path('login/', views.user_login, name='login'), # login / logout urls #path('login/', auth_views.LoginView.as_view(), name='login'), #path('logout/', auth_views.LogoutView.as_view(), name='logout'), # change password urls #path('password-change/', auth_views.PasswordChangeView.as_view(), name='password_change'), #path('password-change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), # reset password urls #path('password-reset/', auth_views.PasswordResetView.as_view(), name='password_reset'), #path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), #path('password-reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), #path('password-reset/complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), #dashboard path('dashboard/', views.dashboard, name='dashboard'), #django … -
How to sort data from django serializer
Here is my code: class PackageMetaSerializer(ParameterBaseSerializer): expired_delta = serializers.SerializerMethodField(method_name='calculate_delta', read_only=True) package = platforms_serializers.PackageSerializer( parameters=("uuid", "id", "name", "platform", "type", "period") ) expire_date_datetime = serializers.DateField("%Y/%m/%d") class Meta: model = account_models.UserToPackageMeta fields = "__all__" depth = 4 def calculate_delta(self, instance): today = datetime.date.today() last_package = instance.expire_date_datetime return (last_package - today).days class UserSerializer(ParameterBaseSerializer): packages = PackageMetaSerializer( read_only=True, many=True, source="package_metas", parameters=("id", "token", "created_date", "package", 'expired_delta'), ) last_package = serializers.SerializerMethodField( method_name="get_last_package", read_only=True ) has_active_package = serializers.SerializerMethodField( "check_user_activity", read_only=True ) is_profile_completed = serializers.SerializerMethodField( "check_profile_completed") has_unread_notification = serializers.BooleanField(read_only=True) birth_date = PersianDateField(format="%Y/%m/%d", required=False) class Meta: model = account_models.User fields = "__all__" extra_kwargs = {"password": {"write_only": True}} depth = 4 Whenever I use the UserSerializer, I want the data to be sorted by the expired_delta I got from the other serializer. How can I do that from the serializer side? Sort data by expried date -
Django models.CheckConstraint causing "TypeError: 'staticmethod' object is not callable"
I have a model named Therapist written as follows: from django.contrib.auth.models import User from django.core.exceptions import ValidationError class Therapist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Also a model named **Appointment ** with some constraints. class Appointment(models.Model): therapist = models.ForeignKey(Therapist, on_delete=models.CASCADE) client = models.ForeignKey(User, on_delete=models.CASCADE) slot = models.DateTimeField() def validate_not_match_therapist_client(self): if self.therapist.user == self.client: raise ValidationError('Therapist and client cannot be the same user.') def clean(self): self.validate_not_match_therapist_client() class Meta: constraints = [ # Same client booking multiple appointments at the same slot (different therapists) models.UniqueConstraint( fields=['client', 'slot'], name='multiple_same_date_time_appointment' ), # therapist booking his/her own appointment models.CheckConstraint( check=~models.Q(therapist__user=models.F('client')), name='therapist_client_are_same' ) ] In this project, **Therapist **objects can also book appointments but I wanted to restrict them from booking any appointments with itself. So, I wrote the second constraint like this: # therapist booking his/her own appointment models.CheckConstraint( check=~models.Q(therapist__user=models.F('client')), name='therapist_client_are_same' ) It works fine when I run **makemigrations **, but when I run **migrate **it throws this following error: Traceback (most recent call last): File "/home/user/project/manage.py", line 22, in <module> main() File "/home/user/project//manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/base.py", line412, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/project/virtualenv/project/3.9/lib/python3.9/site-packages/django/core/management/base.py", line458, in execute output = … -
Django orm filling out 3 interrelated forms on one page and passing each other last inserted id. Issue if form 2 o 3 fail. Form 1 stays fatherless
I have come across an interesting issue (probably because of my lack of knowledge): I have 3 tables (3 forms) that are interrelated. Address, property and photos. The first table or form is Address, it is populated by using a select list. So, on clicking the submit button, that first form will populate a row in Address table. Then I obtain that last id in order to pass it to form 2, properties and the properties will pass the last id inserted to photos, so the three are related by Foreign Keys. What happens in this scheme? If the Property form fails because someone enters bad input in a text field, the model will reject it and will return the user back to the form. BUT, notice that the row in table address was already inserted and it will stay there. Yes, you may say that I could include a line of code in the processing of form Properties, that if it fails, it should delete the recently address row inserted but that doesn't help me because the id sequence will not be reset in the table, it will leap to the next one leaving a gap in the id … -
Shopify Python API Pagination
I am trying to implement pagination using the Shopify API in a Django App but I am not sure how to do so. I read the documentation and have to know that we can get the link of the next and previous page of a resource endpoint through the API but cannot figure out how to implement it in a Django App. My view looks like this: import shopify from shopify_app.decorators import shop_login_required @shop_login_required def index(request): orders = shopify.Order.find(status='any') return render(request, 'home/index.html', {'orders': orders}) index.html: {% extends "base.html" %} {% load template_tags %} {% block content %} <div id="orders"> <div style="display: flex;"> <h2 style="width: 50%;">Your recent orders</h2> </div> {% if orders %} <div class="order-list"> <p id="page-toggle"> <a href="#"> <span id="prev-page">&lt; <b>PREV PAGE</b> </span> </a> <a href=""> <span id="next-page"> <b>NEXT PAGE</b>&gt; </span> </a> </p> {% for order in orders %} <div class="order box"> <div class="wrapper"> <a style='width: 25%; color: black;' href="https://{{ current_shop.domain }}/admin/orders/{{ order.id }}" target="_blank">{{ order.name }}</a> <span style='width: 25%;'>{{ order.created_at | convert_str_date }}</span> <span style='width: 25%;'>{{ order.total_price }} {{ order.currency }}</span> <span style='width: 25%;'>From: {{ order.billing_address.name }}</span> </div> <a href="#" class="download-button"> <button>DOWNLOAD</button> </a> </div> {% endfor %} </div> {% else %} <em class="note">There are no orders in your store.</em> … -
django constance localize language
I use django-constance CONSTANCE_CONFIG = { 'MESSAGE_ROSETTE_DISCONNECT': ('Device {device_name} disconnected from the rosette', 'Message that device disconnection from the rosette'), 'MESSAGE_ROSETTE_CONNECT': ('Device {device_name} connected to the rosette', 'Message that device connection to the rosette'), ... } I want set the different text for different languages. Is it possible? Something like this CONSTANCE_CONFIG = { 'MESSAGE_ROSETTE_DISCONNECT': { 'en': ('Device {device_name} disconnected from the rosette', 'Message that device disconnection from the rosette'), 'it': ('Same about {device_name} in Italian language', 'Italian text'), } ... } What is the best way to implement it? And how to call the constanse? Now its like this: text = config.MESSAGE_BATTERY_LEVEL.format(device_name=self.device.name) -
How to store a loaded PIL image or just the Blob Binary Data in a Django SQLite Database temporarily?
My Django backend views.py looks something like this where I have successfully received a blob data and read the image using PIL def predictor(request): blob = request.FILES['image'].read() thumb = Image.open(BytesIO(blob)) rgb_im = thumb.convert('RGB') # thumb.show() # successfully displays the image in imageviewer image_io = BytesIO() rgb_im.save(image_io, format='jpeg') # save to model form = FaceImage(name="random", image=ContentFile(image_io.getvalue())) form.save() print("Image Successfully saved") return And my models.py is shown below: class FaceImage(models.Model): name = models.CharField(max_length=50) image = models.ImageField(upload_to='images/') def __str__(self): return self.name The output of my code successfully prints the line "Image Successfully saved" but when I view the database in django the ImageField seems to be empty only the name is saved not the image itself. Is there anyway I can save the image in imagefield or rather save a blob data in the database because I just want to save the image temporarily where I would delete the image after doing some image processing stuff so I do not care about the database being bloated by any data. I have viewed several instructions on how to save a pil image in django database but couldnt quite make it work.