Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch row Django serialize query set on jQuery?
Hello I'm trying to load Django Serialize Query set into jQuery Here my view.py def Load_Temp_Data(request): serialize_data = "" data_list = "" if request.method == "GET": count = TempCalculate.objects.filter(create_by = request.user).count() if count: data = TempCalculate.objects.filter(create_by = request.user) serialize_data = serializers.serialize("json",data) #calculation = TempCalculate.objects.filter(create_by = request.user).aggregate(Sum('price')) #conver to list #List = list(calculation.items()) data_list = list(data) return HttpResponse(serialize_data, content_type='application/json') Here my template and jQuery code function Load_data() { var row = "" // table load karo tyre aa pela karo. $.ajax({ url: "{% url 'load_temp_data' %}", success: function (data, status) { console.log(data) if (status) { no = 1 row_data = data for (var i = 0; i < row_data.length; i++) { console.log(i['quantity']) row += "<tr id =" + i + "><td>" + no + "</td><td>" + "<button type='button' id='delet_button' onclick='Delet_Item(" + row_data[i]['id'] + "," + i + ")' class='btn btn-danger'><i class='fa fa-trash'></i></button>" + "</td><td>" + row_data[i]['items__name'] + "</td><td>" + row_data[i]['quantity'] + "</td><td>" + row_data[i]['price'] + "</td><td>" + row_data[i]['total_gst'] + "</td><td>" + row_data[i]['net_amount'] + "</td></tr>" $('#Table_Data').html(row) no = no + 1 } $('#id_sub_total').val(data.total) $('#id_gst_total').val(data.gst_total) $('#id_total').val(data.net_amount) } else { alert("Error !") } } }) } when I'm console.log data set is print but I can't slice data like items_name,quantity etc -
Euro Currency Format (Django)
I have a variable and am trying to format it to following format "100.000,00". I have an amount (integer) and a price (decimal) and try to multiply these things to one total price with: totalprice = price * decimal(amount) I'm using Django and in the end I have to cast it to a string so I can use it in a text field. -
How to set up a django form field to receive data from a request?
For multilang, I store the fields in the database as json fields in this format: {"ru": "some text", "en": "some text"}, add form by itself looks like this input names example: title[ru], title[en] So i don't know how to write my form to get this data as: title: {"ru": "some", "en":"some"} What should i do? How to overwrite form field to get data like this? don’t find answers before that, I decided to completely abandon the forms and collect data with a custom function, but this decision seems to me wrong -
Google authentication MismatchingStateError in django (CSRF Warning - State not equal in request and response)
I have a problem that I have been trying to resolve for the past couple of days. When attempting to handle Google authentication in my Django web app, a MismatchingStateError is encountered at /signup/google/callback/. The issue arises when the Google authentication works correctly upon initial attempts but fails with the mentioned error after multiple tries. Even after logging in and out multiple times, the error persists. This is my first time implementing Google authentication within Django, and I've struggled to find comprehensive guidelines or resources. I'm currently learning about flow handling and recently became aware of potential associated risks. It's important to note that this problem resembles CSRF attacks. It emerges when there's a series of rapid login requests. After this error arises, subsequent logins are blocked. Notably, this issue isn't related to the session ID, as I've attempted to clear it without success. It seems tied to generation, possibly due to how states are managed. See the error here def google_auth(request): # Generate the Google OAuth authorization URL and redirect the user to it authorization_url, state = flow.authorization_url(access_type='offline', include_granted_scopes='true') request.session['oauth_state'] = state return redirect(authorization_url) def google_callback(request): # Exchange the authorization code for a Google OAuth access token. stored_state = … -
Python logging in Django : Filter won't work in logger
I have a logging custom filter class which suppose to ignore Django logs in my logger 'bucket' (I don't want to disable Django logs, just to keep them in separate log): class ExcludeDjangoLogsFilter(logging.Filter): """ Excludes django system logs from logger """ modules_to_exclude = ( "daphne.server", "django", "django.db", "django.server" ) def filter(self, record: logging.LogRecord) -> bool: """ Filters records to exclude from a logging modules with a certain names. """ return not record.name.startswith(self.modules_to_exclude) It works just fine if I pass this filter to handler but It doesn't if I pass this filter to logger. If I use this filter within logger interpreter enters the filter's class but doesn't enter in filter method. My logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, # Filters: "filters": { "info_only": { "()": "logger.logger_filters.InfoOnlyFilter" }, "exclude_django_log": { "()": "logger.logger_filters.ExcludeDjangoLogsFilter" } }, # Formatters' profiles: "formatters": { "base": { "format": "[{asctime}][{levelname}][{name} / {funcName}][{lineno}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" }, "info": { "format": "[{asctime}][{name} / {funcName}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" }, "django_sys_format": { "format": "[{asctime}][{levelname} | {name}] {message}", "datefmt": "%d/%m/%Y %H:%M:%S", "style": "{" } }, # handlers: "handlers": { "important_file": { "level": "WARNING", "class": "logging.FileHandler", "formatter": "base", "filename": BASE_DIR / "logger/logs/important.log" }, "info_file": { … -
uploading an image by url link
can you please tell me how to upload images via the url link through the django admin panel, not from my data warehouse, but via the url link it is possible for me to download only from my storage, but how can I download from a url link ? -
Saving copies in m2m django orm
Inside my code, I am trying to save copies of one object inside m2m, but only one instance is saved. How can I save several of them? def add_to_basket(request): if request.method == 'POST': basket_id = request.session.get('BID') if not basket_id: basket_id = str(uuid.uuid4()) request.session['BID'] = basket_id basket, created = Basket.objects.get_or_create(id=basket_id) if created: basket.save() ticket_id = request.POST.get('ticket_id') count = request.POST.get('count') ticket = Tickets.objects.get(id=int(ticket_id)) if ticket.count - int(count) > 0: for i in range(int(count)): new_ticket = Tickets.objects.get(id=int(ticket_id)) new_ticket.count = new_ticket.count - 1 new_ticket.save() basket.tickets.add(new_ticket) basket.save() return JsonResponse({'status': 'ok'}) else: return JsonResponse({'status': 'not enough tickets'}) else: return JsonResponse({'status': 'not get method'}) class Basket(models.Model): id = models.TextField(verbose_name='ID Корзины', primary_key=True) tickets = models.ManyToManyField(Tickets, verbose_name='Билеты') date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') def to_json(self): return { 'id': self.id, 'tickets': [ticket.to_json() for ticket in self.tickets.all()], 'date': self.date } class Meta: verbose_name = 'Корзина' verbose_name_plural = 'Корзины' I tried to add tickets, in this code I am already creating a separate instance -
Django - two approaches to extending user model wont work together?
I am trying to make my django app require a unique email address when creating the account. When I added (the commented line in the models) the unique email constraint in the model I used to add fields before it just adds another email field instead of altering the original one. So after having found another solution with extending the AbstractUser class unfortunately Im getting 'the model User is not registered' error when im trying to make migrations. Please advice me on what would be a way to go to have both extra fields as well as unique email constraint. Heres how i have extra fields added to the user model: models class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0) #### email = models.EmailField(("email address"), blank=True, null=True, unique=True) profession = models.CharField(max_length=30, blank=True, null=True, choices =[('a', 'a'), ('b', 'b')]) def __str__(self): return self.user.username admin from django.contrib import admin from account.models import Account from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomizedUserAdmin (UserAdmin): inlines = (AccountInline, ) admin.site.unregister(User) admin.site.register(User, CustomizedUserAdmin) It worked until ive added: models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) settings AUTH_USER_MODEL = 'account.CustomUser' -
How to use django_private_chat2
I want to use this package for my localhost website but it show the error: Using the URLconf defined in dimsum.urls, Django tried these URL patterns, in this order: admin/ profiles/ restaurants/ messages/ [name='all_messages_list'] messages/<dialog_with>/ [name='messages_list'] dialogs/ [name='dialogs_list'] self/ [name='self_info'] upload/ [name='fileupload'] I done all the steps in quick start of this package but it not working. Install django_private_chat2: pip install django_private_chat2 Add it to your INSTALLED_APPS: INSTALLED_APPS = ( ... 'django_private_chat2.apps.DjangoPrivateChat2Config', ... ) Add django_private_chat2's URL patterns into my url file: from django.urls import re_path, include urlpatterns = [ ... re_path(r'', include('django_private_chat2.urls', namespace='django_private_chat2')), ... ] Add django_private_chat2's websocket URLs to my asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django_private_chat2 import urls os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dimsum.settings') # application = get_asgi_application() django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter(urls.websocket_urlpatterns) ), }) I all so run this command before run server python manage.py migrate Please tell me what am I missing? -
Encountring Error While installing django dependency "Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error"
I am using this command to install dependencies for django project pip install -r requirements.txt ` Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Collecting yarl==1.7.2 (from -r requirements.txt (line 369)) Using cached yarl-1.7.2-cp38-cp38-macosx_10_9_x86_64.whl (121 kB) Collecting zipp==3.1.0 (from -r requirements.txt (line 371)) Using cached zipp-3.1.0-py3-none-any.whl (4.9 kB) Requirement already satisfied: setuptools>=3.0 in ./kit/lib/python3.8/site-packages (from gunicorn==20.1.0->-r requirements.txt (line 154)) (56.0.0) Building wheels for collected packages: xmlsec, django-rest-hooks Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for xmlsec (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [65 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-cpython-38 creating build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/py.typed -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/tree.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/init.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/constants.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec copying src/xmlsec/template.pyi -> build/lib.macosx-10.9-x86_64-cpython-38/xmlsec running build_ext building 'xmlsec' extension creating build/temp.macosx-10.9-x86_64-cpython-38 creating build/temp.macosx-10.9-x86_64-cpython-38/private creating build/temp.macosx-10.9-x86_64-cpython-38/private/var creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99 creating build/temp.macosx-10.9-x86_64-cpython-38/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99/src gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -D__XMLSEC_FUNCTION__=func -DXMLSEC_NO_FTP=1 -DXMLSEC_NO_MD5=1 -DXMLSEC_NO_GOST=1 -DXMLSEC_NO_GOST2012=1 -DXMLSEC_NO_CRYPTO_DYNAMIC_LOADING=1 -DXMLSEC_CRYPTO_OPENSSL=1 -DMODULE_NAME=xmlsec -DMODULE_VERSION=1.3.12 -I/opt/homebrew/Cellar/libxmlsec1/1.3.1_1/include/xmlsec1 -I/opt/homebrew/opt/openssl@3/include -I/opt/homebrew/opt/openssl@3/include/openssl -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml/includes -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml -I/private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-build-env-5ws1iwun/normal/lib/python3.8/site-packages/lxml/includes/pycache -I/Users/nehanegi/Downloads/analytickit-first/kit/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c /private/var/folders/0f/pwhvtlxn26j0cfry2wrpvb7r0000gn/T/pip-install-y3izz7rd/xmlsec_1b2a1e6a17e447509a7b6137df7d3b99/src/constants.c -o … -
Django connection.queries is not running in server
I am executing following code in views.py file on dev server hosted on AWS EC2 instance and my settings.py file has DEBUG = True configured. from django.db import connection from project.models import MyModel mymodels = MyModel.objects.all() print("My models: ", mymodels) raw_queries = connection.queries print("raw query: ", raw_queries) Output is: My models: [<myModel 1>, <myModel 2>,<myModel 3>] raw query: [] I am not sure, what i am missing. why raw query = []. I tried doing with python3 manage.py shell but same thing happend there too. but same result raw query = [] -
Django: Serpy serializer django model JsonField
I am using serpy to serialize my model, so my model has a JSONField containing list of dict. Here is my model: class Section(models.Model): title = models.CharField(max_length=255, null=False) item_count = models.IntegerField(default=0) # The JSON field contents = models.JSONField(blank=True, null=True) I am trying to use serpy.DictSerializer to serialize the contents field but it results in empty dict {} . This is my serializer: class SectionSerializer(serpy.Serializer): title = serpy.StrField() item_count = serpy.IntField() data = serpy.MethodField() def get_data(self, obj): return serpy.DictSerializer(obj.contents, many=True).data As contents is a list of dicts, I have used many=True, But still it is not helping. -
What does this symbol mean "[...]" in docstrings?
I've seen this multiple times now in different python documents. For example: python code The above is from a website that I just saw today and the rest is code written in Django. I see this symbol being regularly used in different documentations. -
Alpine.js x-bind not applying after an HTMX swap
I have an element that is in the initial page load and updates after form post through an HTMX out of bounds swap. On initial load the x-bind formats as expected. After the swap the values from the swapped element display as expected using x-text. The x-bind always fails to apply the formatting that should trigger when staffCount < shiftNeed. When it should apply it quickly flickers immediately after the swap but then goes away. Same flicker is not present when it should not apply. Element on initial page load <tr x-data="{ shiftNeed: {{ day_need }} }"> <td class="fw-bold">Day</td> <td class="fw-bold text-center" x-text="shiftNeed"></td> {% for i, val in day_list|zip:day_staffing %} <td> <div id="dayCount{{ i }}" x-data="{ staffCount: {{ val }} }" x-text="staffCount" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> </td> {% endfor %} </tr> Partial template swapped in {% include "schedule/components/schedule_shift_button.html" %} <div id="{{ shift.time_of_day_label|lower }}Count{{ shift.day_num }}" class="text-center rounded" hx-swap-oob="true" x-data="{ staffCount: {{ shift.staff_count }}}" x-text="staffCount" x-init="console.log(staffCount < shiftNeed)" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> I added logging statements on the x-init to inspect output, console always displays the expected values of staffCount and shiftNeed and evaluates the criteria used in the x-bind as expected. -
Why when I create an enviroment with anaconda in Visual Studio Code and I try to activate it, shows me an error
I try to activate the env that I already created and everything fine, but when I tried the command "conda activate whynotdata" it shows me this error: PROGRAMACION\Data_base_whynot> conda activate whynotdata usage: conda-script.py [-h] [--no-plugins] [-V] COMMAND ... conda-script.py: error: argument COMMAND: invalid choice: 'activate' (choose from 'clean', 'compare', 'config', 'create', 'info', 'init', 'install', 'list', 'notices', 'package', 'remove', 'uninstall', 'rename', 'run', 'search', 'update', 'upgrade', 'build', 'convert', 'debug', 'develop', 'doctor', 'index', 'inspect', 'metapackage', 'render', 'skeleton', 'verify', 'token', 'pack', 'server', 'env', 'content-trust', 'repo') When I create it with the anaconda prompt everything works fine but in Visual Studio Code I can't complete it, and I want to create my env on the folder that I have on Visual Studio, I am a begginer in the back-end, I am of autodidact learning. Thank you I am trying to create an env on a folder that I create and then install django, I want to use Anaconda to create the project but it didn't work and is rare because on the config of my sistem I added the path to the environments of windows, of the anaconda3 and anaconda3\scripts -
Django cap a DateField value in the database
Sorry I am very new to Django. I have date of birth (DOB) as a field in my model. I use the DOB to calculate the age and get some values from other dataset. class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) dob = models.DateField(blank=True, null=True) The age cannot be higher than 120 years so I raise a ValidationError with the registration and update profile forms whenever they enter a DOB of more than 120 years ago. def clean(self): cleaned_data = super(RegistrationForm, self).clean() dob = self.cleaned_data.get('dob') age = (date.today() - dob).days / 365 if age > 120: raise forms.ValidationError('Sorry but profiles cannot be registered with more than 120 years old due to scientific data unavailability.') elif age < 0: raise forms.ValidationError('Date of birth is in the future. Please enter valid birth date.') However, what if they register as born 119 years ago. In 1 or 2 years, the age would be 121 and my code will fail. Is there a way to always cap the value of the DOB in my database so the DOB is always maximum 120 years old? I checked the documentation for DateField but there is no reference to MinValueValidator as in the case of IntegerField. -
Ingress health check failing on Django GKE Deployemnt
I am deploying a frontend (Nuxt) and a backend (Django) using GKE Autopilot. A CI/CD pipeline has been set up from github to GKE. The frontend gets deployed and easily viewable on xpresstracker.app while the backend spits out server error 501 on backend.xpresstracker.app. Below is the related configurations and error; Error message prodservice.yaml apiVersion: v1 kind: Service metadata: name: prod-xpressbackend-service spec: selector: app: prod-xpressbackend ports: - protocol: TCP port: 8000 targetPort: 8000 type: NodePort prodmanagedcert.yaml apiVersion: networking.gke.io/v1 kind: ManagedCertificate metadata: name: prod-managed-cert spec: domains: - xpresstracker.app - backend.xpresstracker.app prodingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: prod-ingress annotations: kubernetes.io/ingress.global-static-ip-name: xpresstrackerip networking.gke.io/managed-certificates: prod-managed-cert kubernetes.io/ingress.class: "gce" labels: app: prod-xpressbackend spec: rules: - host: xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressfrontend-service port: number: 3000 - host: backend.xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressbackend-service port: number: 8000 Deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: prod-xpressbackend-deployment labels: app: prod-xpressbackend spec: replicas: 1 selector: matchLabels: app: prod-xpressbackend template: metadata: labels: app: prod-xpressbackend spec: containers: - name: prod-xpressbackend-container image: someimage:production imagePullPolicy: Always resources: requests: memory: "200Mi" cpu: "0.2" limits: memory: "512Mi" cpu: "0.5" ports: - containerPort: 8000 env: - name: SECRET_KEY valueFrom: secretKeyRef: name: proddatabasecredentials key: SECRET_KEY - … -
Custom Django Admin Page/View
Basically I'm trying to create a custom admin web page, like a custom a view. Ideally what I want is something where like once you log in to the admin page, there would be a link somewhere like under the list of models that would redirect you to this admin center. I have a somewhat working version currently, but I would like to have it redirect to a new URL like “ /admin/social/edit/ “ instead and not just render context into the template. I’ve done a ton of googling and I just keep coming across things like “custom admin actions” which is not per se what I’m looking to do. Any help is appreciated. Thank you. -
Trying to delete an item from webpage rendered by django results in all items below it to also be deleted
In my project I have a cart application that displays any items the user decided to add to the cart. Template: {% extends '../main.html' %} {% load static %} {% block title %}Cart Summary{% endblock %} {% block content %} <main class = "pt-5"> <div class = "container"> <h1 class = "h5">Shopping Cart</h1> {% for item in cart %} {% with product=item.product %} <div data-index = "{{product.id}}" class = "row g-3 product-item"> <div class = "col-md-5 col-lg-5 order-mg-first"> <img class = "img-fluid mx-auto d-block" width = "200px" alt = "Responsive image" src = "{{ product.image.url }}" /> </div> <div class = "col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">{{ product.price }}€</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select{{product.id}}"> <option selected> {{item.qty}} </option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button type="button" id = "update-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm update-button"> Update </button> <button type="button" id = "delete-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm delete-button"> Delete </button> </div> </div> </div> </div> </div> {% endwith %} {% endfor %} … -
How can I set group permissions that filter pages according to their owners in Wagtail
I am working on a blog with Wagtail and would like to give users access to create their own content in the Wagtail admin. I would like users to be able to log into the Wagtail admin, but only have access to content that they have created themselves. I have tried to generate permissions by group, however there is no default option to limit content by author, so if I give add, edit and publish permissions, a user could edit content created by other users and could unpublish or even delete that content. I would like to know if there is a way to modify the queryset of pages that appear in the Wagtail admin for a specific user. I don't have much experience with Wagtail. So far I have seen some possible solutions but none have seemed viable or adequate. For example, there are some posts here where they propose to create a Parent page for each user, but then you would have to create a group for each user, which doesn't seem like an efficient way to do it. I appreciate any help or suggestions. Here I share some of the relevant code: class BlogIndexPage(Page): max_count = 1 … -
Django: signal doesn't work well with ForeignKey
models.py from django.db import models class Post(models.Model): text = models.TextField() approved = models.BooleanField(default=False) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) from django.conf import settings from django.db import models import os class PostMedia(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='mediafiles') media = models.FileField(upload_to='post_media/', blank=True) absolute_media_path = models.CharField(max_length=255, blank=True) def save(self, *args, **kwargs): self.absolute_media_path = self.get_absolute_media_path() return super().save(*args, **kwargs) def get_absolute_media_path(self): return os.path.join(settings.BASE_DIR, self.media.path) #Post.objects.last().mediafiles.last().absolute_media_path services.py (functions for aiogram bot and django) async def get_post_path(post_id): url = f'http://localhost:8000/api/get_media_urls/{post_id}/' async with aiohttp.ClientSession() as session: async with session.get(url) as response: if response.status == 200: data_list = await response.json() return data_list else: return None async def register_manager(CHAT_ID: str): fake = Faker() username = fake.user_name() password = fake.password() await bot.send_message(CHAT_ID, f'username: {username}\npassword: {password}\nadmin-panel: http://localhost:8000/admin', reply_markup=set_manager_kb()) # async def send_post(instance): # admin_id = '679553167' # await bot.send_message(admin_id, f'{instance}', reply_markup=set_post_kb()) async def send_post(post): message = post.split('\n') user_id = '679553167' post_id = message[0] media = [] media_paths = await get_post_path(post_id) if media_paths: for photo_path in media_paths: if photo_path.lower().endswith(('.jpg', '.jpeg', '.png')): media_type = types.InputMediaPhoto elif photo_path.lower().endswith(('.mp4', '.avi', '.mkv')): media_type = types.InputMediaVideo else: continue photo_file = open(photo_path, 'rb') input_media = media_type(media=types.InputFile(photo_file)) media.append(input_media) media[0]["caption"] = message[1] await bot.send_media_group(chat_id=user_id, media=media, reply_markup=set_post_kb()) photo_file.close() else: await bot.send_message(user_id, message[1], reply_markup=set_post_kb()) signals.py from django.db.models.signals import post_save from django.dispatch import receiver … -
cant create new model object django rest framework
model.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=30) description = models.TextField() deadline = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from django.contrib.auth.models import User from .models import Task from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): tasks = serializers.PrimaryKeyRelatedField( many=True, queryset=Task.objects.all()) class Meta: model = User fields = ['id', 'username', 'email', 'tasks'] class AuthSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'description', 'deadline', 'created_at', 'updated_at'] views class CreateTask(generics.CreateAPIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] queryset = Task.objects.all() serializer_class = TaskSerializer in the command line it says 'null value in column "userid" of relation "srctask" violates not-null constraint', do i have to access the userid by another way and attach it to the model object? -
Django - AttributeError: 'Index' object has no attribute 'constraint_type'
I am using Django 4.2.2 This is a model that is throwing the subject jessage in an error, when I run makemigrations: class AnonymousInteractionMonitor(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') interaction_type = models.PositiveSmallIntegerField(choices=Engagement.ENGAGEMENT_TYPES, null=False) visitor_ip = models.GenericIPAddressField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('visitor_ip', 'content_type', 'interaction_type') constraints = [ models.UniqueConstraint(fields=['visitor_ip', 'content_type', 'interaction_type'], name="idx_visitor_inf" ) ] The constraint is not defined on an Index, so why am I getting this error message, and how do I fix it? -
error during installation of virtual environment
I face with folliowing error when I want to install virtual env: C:\Users\MICROSOFT\Desktop\django_project>virtualenv venv 'virtualenv' is not recognized as an internal or external command, operable program or batch file. How it could be tackled? -
new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252)
I'm trying to test with Django, pytest-django and PostgreSQL on Windows 11. But I got the error below: psycopg2.errors.InvalidParameterValue: new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252) Even though I set English_World.1252 to LC_COLLATE and LC_CTYPE in run_sql() as shown below. *I wrote the code below to connect to PostgreSQL in conftest.py following the doc: # "conftest.py" import pytest from django.db import connections import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def run_sql(sql): conn = psycopg2.connect(database='postgres', user='postgres', password='admin') conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute(sql) conn.close() @pytest.fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'copied_postgres' run_sql('DROP DATABASE IF EXISTS copied_postgres') run_sql(""" CREATE DATABASE copied_postgres LC_COLLATE = 'English_World.1252' # Here LC_CTYPE = 'English_World.1252' # Here TEMPLATE postgres""") yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE copied_postgres') And, this is test_get_username() below in test_ex1.py: # "test_ex1.py" @pytest.mark.django_db def test_get_username(): user = User.objects.create_user("test-user") user.username = "John" assert user.get_username() == "John" So, how can I solve the error?