Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
calling a synchronous function asynchronously in django-graphene mutation
My mutation contains a function which calls an API to send SMS. Since this function's execution may take some time, and its result doesn't have anything to do with what the mutation returns (It does not have to be send back to the client); I prefer to run it asynchronously. So that the mutation gets executed as fast as possible. Here's my code: class MyMutation(graphene.Mutation): class Arguments: phone = graphene.String(required=True) success = graphene.Boolean() @classmethod def mutate(cls, root, info, phone): ... ... myfunction() #The client should not wait for this function's execution. return MyMutation(success=True) I couldn't find a proper way to do this in django-graphene's docs. -
Django docker-compose: how to handle migrations and collect static
I have a django app that I have been trying to "Dockerize" . I am pretty close but I am facing a small issue. Essentially, I am trying to understand how should I handle the fact that everytime I run docker-compose up I should run python manage.py migrate. Any suggestions? Below my dockerfile and my dockercompose. If they are totally wrong, please le me know as well. # pull official base image FROM python:3.10-alpine # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 0 # install psycopg2 RUN apk update \ && apk add --virtual build-essential libffi-dev gcc python3-dev musl-dev \ && apk add postgresql-dev \ && pip install psycopg2 # install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # add and run as non-root user RUN adduser -D miliu USER miliu # run gunicorn # CMD gunicorn mywebsite.wsgi:application --bind 0.0.0.0:$PORT CMD python ./manage.py collectstatic --noinput version: "3.8" services: web: build: . volumes: - .:/django ports: - 8000:8000 env_file: .env image: miliu container_name: miliu_container command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" depends_on: - db db: image: postgres volumes: … -
how do i save a variable in html file in order to send it to a database through Django?
So I've made a counter on Django using HTML and JS, HTML/JS then used this as a template on django Views.py, now i want to save the counter number to a MySQL database, how would i do this tho? Is it possible with just using a template? Im new to Django so I'm sorry in advanced. Counter -
Django change textfield
Currently am using this textfield for my model #model class NoLoginPsuedoAppointment(models.Model): ... comments = models.TextField(blank=True) #form class NoLoginPsuedoAppointmentForm(forms.ModelForm): comments = forms.Textarea() class Meta: model = NoLoginPsuedoAppointment fields = [ "comments", ] Which comes out looking like this Is there a way to change where the textarea begins so that comments is on top of the textarea or on its top left instead of being on its bottom left? Can this be changed through the django forms? or do I need to change it through css? -
Daphne ModuleNotFoundError: No module named 'app_name'
When I run daphne -b 0.0.0.0 -p 8000 --access-log=daphne.log config.asgi:application I get Daphne ModuleNotFoundError: No module named 'app_name' But when I run python3 manage.py runserver it works normally? When I remove app_1 from INSTALLED_APPS it will show me ModuleNotFoundError: No module named 'app_2' This is my folder structure: project_name │ manage.py │ └───config │ │ __init__.py │ │ asgi.py │ │ celery.py │ │ urls.py │ │ wsgi.py │ │ │ └───settings │ │ │ │ __init__.py │ │ base.py │ │ dev.py │ │ prod.py │ │ └───project_name │ │ __init__.py │ │ │ └───app_1 │ └───app_2 │ └───app_3 │ └───media │ └───static asgi.py: from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from chat import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev') application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) -
Is there a Pythonic way to type a function parameter to a specific django model object?
Let's say I have a model like this: class Foo(): name = models.CharField() And a function like this: def update_foo_name(foo_object): foo_object.name = "New Name" Is there a way to enforce typing on update_foo_name(), so that only a valid object of Foo can be passed here? Ie something like update_foo_name(foo_object: Foo.objects). Apologies if this has already been asked, and thank you in advance for any responses! -
Replit: Why am I getting PR_END_OF_FILE_ERROR for my Django project?
I run a Django repl within Replit. However, I often cannot access the browser preview of my project because of a "PR_END_OF_FILE_ERROR" in Firefox. I also tried using Brave and Chromium, but no luck with them either: they showed an "ERR_CONNECTION_CLOSED" error. When I reached out to Replit Support, they said, "This looks like a problem that someone in our community can help with." Can any of you help? -
Ignore certain fields on update depending on condition
Description: The goal is to update all Spotlight fields on PUT/PATCH (update/partial update) if its status is YELLOW. If status is RED || GREEN, it should update only its status and ignore any other fields. The workaround presented here is kind of smelly and it produces misleading responses when using PUT. Is there any Django way to achieve this better than the presented workaround? Workaround: if instance.state == instance.STATE_YELLOW: custom_data = request.data else: custom_data = {'state': request.data['state']} Full code: from stoplight.filters import StoplightFilter from stoplight.models import Stoplight from stoplight.permissions import ( IsSuperuserOrReadOnly ) from stoplight.serializers import StoplightSerializer from rest_framework import status from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin from rest_framework.response import Response from rest_framework.viewsets import GenericViewSet class StoplightViewSet(GenericViewSet, CreateModelMixin, ListModelMixin, RetrieveModelMixin): """ API endpoint for Stoplights """ queryset = Stoplight.objects.all() serializer_class = StoplightSerializer filter_class = StoplightFilter search_fields = ('name',) permission_classes = (IsSuperuserOrReadOnly,) def update(self, request, *args, **kwargs): """ Updates Stoplight state """ partial = kwargs.pop('partial', False) instance = self.get_object() if instance.state == instance.STATE_YELLOW: custom_data = request.data else: custom_data = {'state': request.data['state']} serializer = self.get_serializer(instance, data=custom_data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on … -
"column does not exist" and "cursor does not exist" for postgres migration (where column clearly exists)
I'm running into some migration problems. I've tried deleting my last migration file, going into psql and dropping all the new tables and deleting the specific migration row in django_migrations. But I'm still getting the following errors for the following model: # my model class Excerpt(models.Model): id = models.UUIDField( default=generate_ulid_as_uuid, primary_key=True, editable=False ) body = models.JSONField(default=None) slug = ArrayField( models.SlugField(max_length=50), unique=True, null=True, blank=True ) Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column app_excerpt.slug does not exist LINE 1: ..."app_excerpt"."chapter_id", "app_excerpt"."body", "app_excer... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column app_excerpt.slug does not exist LINE 1: ..."app_excerpt"."chapter_id", "app_excerpt"."body", "app_excer... ^ During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/code/manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line … -
Exception inside application: 'user' user=self.scope['user'] KeyError: 'user'
I'm trying to set up a custom middleware for my django channels since AuthMiddleWare returns anonymousUser while trying to use self.scope['user] in consumers.py and i'm using token based authentification,but after setting up the custom middleware django keeps throwing this exception: Exception inside application: 'user' Traceback (most recent call last): File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\security\websocket.py", line 37, in __call__ return await self.application(scope, receive, send) File "C:\Users\user\Easylance\chat\token_auth.py", line 29, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\user\Easylance\EasylanceEnv\lib\site-packages\channels\consumer.py", line 73, in dispatch await handler(message) File "C:\Users\user\Easylance\chat\consumers.py", line 13, in websocket_connect user=self.scope['user'] KeyError: 'user' definitely the error means that there's no key for the dict scope named 'user',but in my token_auth.py file where the custom middle ware is situated,i actually assigned a key 'user' the custom middle ware code is below: class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) … -
requirement.txt error in virtual environment
I am running pip freeze > requirements.txt instead of making requirements.txt my virtual environment is making only requirements file which is empty. Any advice? -
Making price range filter in django
Hi guys I have built an ecommerce site using Django. I want to filter the price ranges and I have found the perfect javascript and html tempelate for that. Problem is I don't have javascript knowledge to put that to my advantage. Here are the codes. Javascript var slider = document.getElementById('price-slider'); if (slider) { noUiSlider.create(slider, { start: [1, 999], connect: true, tooltips: [true, true], format: { to: function(value) { return value.toFixed(2) + '$'; }, from: function(value) { return value } }, range: { 'min': 1, 'max': 999 } }); } html code <div class="aside"> <h3 class="aside-title">Filter by Price</h3> <div id="price-slider"></div> </div> Views def category_products(request,id,slug): products = Product.objects.filter(category_id=id) minmaxPrice = products.aggregate(Min('price'), Max('price')) context={'products': products, 'minmaxPrice':minmaxPrice,} return render(request,'category_products.html',context) Now it shows ranges from 1 to 999 as fixed in the javascript code, but I want it to be dynamic based on the range "minmaxPrice" in views, like this "minmaxPrice.price__min" and "minmaxPrice.price__max". Thank you in advance!!! -
The genre system in django
I'm making a genre system on django based on the videos. I came across a problem that when I select a certain genre and click on the find button, I am thrown a link of the type '/filter/?genre=2', but the problem is that the found books are not displayed, I know for sure that they are, the problem is specifically in the template.The genres themselves also disappear from the sidebar, but the header tag and some others remain. I can't figure out what the problem is. views.py class GenreView: def get_genres(self): return Genre.objects.all() class AllBookView(View): def get(self, request): allbook = BookModel.objects.all() view_genres = GenreView.get_genres(self) return render(request, 'bookapp/bookmodel_list.html', context={ 'allbook': allbook, 'viewgenre': view_genres, }) models.py class Genre(models.Model): name = models.CharField('Имя', max_length=100) def __str__(self): return self.name class Meta: verbose_name = "Жанр" verbose_name_plural = "Жанры" class BookModel(models.Model): title = models.CharField(max_length=100, verbose_name='Название') creator = models.CharField(max_length=100, verbose_name='creator', null=True) author = models.CharField(max_length=100, verbose_name='автор') contentbook = models.TextField(verbose_name='Содержание') picture = models.ImageField(upload_to='images/', verbose_name='Обложка') price = models.IntegerField(null=True, verbose_name='Цена') price_rent = models.IntegerField(null=True, verbose_name='Аренда') likes = models.ManyToManyField(User, related_name='book_post', verbose_name='лайкнули') genres = models.ManyToManyField(Genre, verbose_name='жанры') html <header></header> <div></div> (Внутренности этих тегов надеюсь не так важны, но они выводятся) <form action="{% url 'filter' %}" method="get"> <div class="left-side my-4"> <h3 class="sear-head editContent">Жанры</h3> <ul class="w3layouts-box-list" style="list-style-type: none; … -
Django API unittest JWT authentication always 403 Forbidden
I am trying to write unit tests for my Django API that has JWT authentication. But every test gets status code 403 - Forbidden. I did try with force_authenticate too, but it doesn't work. When I work with Postman, everything is fine. Here is the code below, and one of the tests. Thanks for the help if there is any. test_view.py: from rest_framework.test import APIClient, APITestCase from django.urls import reverse from users.models import User class TestViews(APITestCase): def setUp(self): self.client = APIClient() self.register_url = reverse('register') self.login_url = reverse('login') self.user_url = reverse('user') self.logout_url = reverse('logout') self.user1 = User.objects.create( email = "petar@stripe.com", first_name = "Petar", last_name = "Petrovic", password = "petar123" ) self.user1 = User.objects.get(email="petar@stripe.com") self.client.force_authenticate(user=self.user1) self.data_login = { "email": "petar@stripe.com", "password": "petar123" } def test_login_POST(self): response = self.client.post(self.login_url, data=self.data_login, format="json") self.assertEquals(response.status_code, 200) # AssertionError: 403 != 200 self.assertTrue("jwt" in response.data) # AssertionError: False is not true models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) password = models.CharField(max_length=255) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] views.py: from rest_framework.views import APIView from RecipesAPI.constants import HUNTER_API_KEY, CLEARBIT_API_KEY, JWT_KEY import requests from rest_framework.response import Response from … -
Validate parent model foreign key by child class in Django
Let's say I have the following parent models in my Django application: class Location(models.Model): name = models.CharField(max_length=100) class Exit(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="exits") closed = models.BooleanField() And two pairs of corresponding child models: class Submarine(Location): size = models.FloatField() class Hatch(Exit): diameter = models.FloatField() class House(Location): height = models.FloatField() class Door(Exit): width = models.FloatField() height = models.FloatField() In this setup it is possible for a House to have a Hatch as one of its Exits, as well as for a Submarine to have a Door. Is there a way to explicitly prevent this from happening? Ideally, I would like an exception to be thrown on attempt to set an invalid foreign key. Moving the location field from Exit to Hatch and Door is not an option, because I want to be able to use constructions like the following: open_locations = Location.objects.filter(exits__closed=False) and avoid duplication (i.e. writing separate functions for Houses and Submarines). Maybe the limit_choices_to constraint could be helpful, but I didn't manage to figure out how to apply it here. -
CSRF verification fails after having deployed Django on nginx and waitress
I have used the build-in CSRF module in Django, which worked on localhost. After deploying on nginx and waitress on windows server, it gives me the following error: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https://95.18.243.298 does not match any trusted origins. Have tried these setting in settings.py: CSRF_TRUSTED_ORIGINS = ['95.18.243.298'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True Figured it maybe have something to do with having implemented HTTPS. The nginx config looks like this: server { listen 80; server_name DJANGO-WEB; # substitute your machine's IP address or FQDN return 301 https://$host$request_uri; } server { listen 443 ssl; server_name DJANGO-WEB; charset utf-8; ssl_certificate C:/Users/Administrator/Desktop/certifikat.pem; ssl_certificate_key C:/Users/Administrator/Desktop/privateKey.key; # max upload size client_max_body_size 75M; location /static { alias C:/Users/Administrator/itavis-web/static; } location / { proxy_pass http://localhost:8080; # See output from runserver.py proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-Host $host; } } Hope someone can help. -
Add multiple checkout buttons for multiple events on same page Eventbrite
How to add multiple checkout buttons for multiple events on the same page? <script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script> <script type="text/javascript"> var exampleCallback = function () { console.log('Order complete!'); }; var getEventID = function(){ var value = document.getElementById('eventID').value; return value; }; window.EBWidgets.createWidget({ widgetType: 'checkout', eventId: getEventID, modal: true, modalTriggerElementId: 'checkout_btn', onOrderComplete: exampleCallback, }); </script> HTML Here {% for event in data.events %} <form id="form_id"> {% csrf_token%} <div class="center"> <div class="w3-card-4" style="width:100%;"> <header class="w3-container w3-blue" > <h1>{{event.name.text}}</h1> </header> <div class="w3-container" style="background-color: #ddd;"> <p>{{event.description.text}}</p> Event ID: <input type="hidden" id="eventID" name="eventID" value="{{event.id}}"><br> Capcity: {{event.capacity}} <button id="checkout_btn" class="button" type="button">Buy Tickets!</button> </div> </div> </form> {% endfor %} I am showing multiple events in Django and trying to fetch the event id in script code. It works for one event when I provide a hardcoded value. Any help will be appreciated! -
Django | the role of the environment vatiable?
I'm learning Django and I come across something. We use environment variables to keep secrets safe from others or to hide them from other developers who work on the same project. We can export the variables on the server. import os SECRET = os.environ.get("") But then any developer can print this secret and see it. What is the point of using environment variables? -
How to send result of function from Django Server to React Native App?
I am study React Native and Django Development and I create an app which recognize a text from image. I realized POST method from React Native to Django Server but I don't understand how to send the result of recognition back to React. How I can resolve this problem? Django Server: views.py: from .serializers import PostSerializer from .models import Ocr from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status # Create your views here. from django.http.response import JsonResponse # Create your views here. # import pytesseract to convert text in image to string import pytesseract # import summarize to summarize the ocred text from .forms import ImageUpload import os # import Image from PIL to read image from PIL import Image from django.conf import settings # Create your views here. class PostView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): posts = Ocr.objects.all() serializer = PostSerializer(posts, many=True) print(serializer.data) return Response(serializer.data) def post(self, request, *args, **kwargs): posts_serializer = PostSerializer(data=request.data) if posts_serializer.is_valid(): text = "" message = "" posts_serializer.save() try: posts_serializer.save() image = request.FILES['image'] image = image.name path = settings.MEDIA_ROOT pathz = path + "/images/" + image text = pytesseract.image_to_string(Image.open(pathz), lang='rus+eng') os.remove(pathz) except … -
How do I best restrict by user and by data model using Django?
I'm using django-guardian and I encountered some issues with the default mixins. And I want to know if there's a better way to do this. Problem: If I want to limit access at both the model and object levels, using these two mixins (PermissionRequiredMixin, PermissionListMixin) is not a very easy task. Because the permissions_required attribute is overridden. To get around this I had to create a new attr "object_permission" and do the following: Model Looks like: # Create your models here. from django.db import models from localflavor.br import models as localModels from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Customer(models.Model): user: User = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Company(models.Model): user: User = models.OneToOneField(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='comapnies') def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Project(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='projects') class Meta: permissions = (('read_project', 'Read Project'),) def __str__(self): return self.name class House(models.Model): rooms = models.IntegerField() postal_code = localModels.BRPostalCodeField() project = models.ForeignKey(Project, on_delete=models.CASCADE) Here I needed to create a new attribute ("object_permission") to limit object-level access in the View: class ProjectsListView(PermissionRequiredMixin, PermissionListMixin, ListView): template_name = 'home/projects.html' model = models.Project permission_required = ["homepage.view_project"] object_permission = ["read_project"] redirect_field_name = 'next' login_url = 'login/' get_objects_for_user_extra_kwargs = … -
How to add Reactjs code to django app on docker-compose with nginx-proxy acme-companion
I am trying to setup a complete django react webapp via docker-compose on AWS. I went through a tutorial to create a django backend with database and ssl via nginx-proxy and letsencrypt acme-companion. Everything works so far, but I struggle to add reactjs code as the frontend. I created a frontend folder with react-code and a Dockerfile to create the static files: # Dockerfile frontend FROM node:15.13-alpine as build WORKDIR /frontend # add `/app/node_modules/.bin` to $PATH ENV PATH /frontend/node_modules/.bin:$PATH # install app dependencies COPY package.json ./ COPY package-lock.json ./ RUN npm ci --silent COPY . ./ RUN npm run build # The second stage # Copy React static files FROM nginx:stable-alpine COPY --from=build /frontend/build /usr/share/nginx/html I tried to change the default file in nginx/vhost.d/default to access static frontend files as default and the django-backend-app via /api: # nginx/vhost.d/default server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api { try_files $uri @proxy_api; } location /admin { try_files $uri @proxy_api; } location @proxy_api { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://backend:8000; } location /django_static/ { autoindex on; alias /app/backend/server/django_static/; } } Here is … -
TestCase fails but api works fine
Im still learning django but i found a issue i couln't find anything about on the internet. Im was busy with writing my tests for my CBV's but im now running in this weird issue specs: Python 3.10 django 4.0.4 drf 3.13.1 I have a model with 2 foreignkey fields you can see it below. My issue that is when i run the code and test with the drf-yasg swagger it runs without any issues but my test keeps failing. specifically the test_get_good() The traceback says: AttributeError: 'ArticleLocation' object has no attribute 'article_name' but the swagger page does everything without issues and with postman i also did not get the error at all. Could somebody explain to me where it goes wrong as im not seeing it. class Slotting(ICSBaseMixin): # database fields article = models.OneToOneField( "ics_stock.Article", on_delete=models.SET_NULL, related_name="slotting", null=True ) article_location = models.OneToOneField( "ics_stock.ArticleLocation", on_delete=models.SET_NULL, null=True, related_name="slotting" ) def __str__(self): return str(self.record_id) class Meta: db_table = "ICS_Stock_Slotting" verbose_name = "Slotting" verbose_name_plural = "Slottings" # noqa and my serializers are: from rest_framework import serializers from ics_stock.models.slotting import Slotting from ics_stock.models.article import Article from ics_stock.models.article_location import ArticleLocation class SlottingOutputSerializer(serializers.ModelSerializer): class Meta: model = Slotting fields = "__all__" class SlottingArticleOutputSerializer(serializers.ModelSerializer): class Meta: model … -
Running a python script needing typed arguments in the terminal within Django
I am trying to build a website and a component would be a python script that would run internally and needs typed arguments in the terminal to run and produce results. How can I run this script with pre-written arguments within Django? -
Django dumpdata: "Unable to serialize database" error due to a BitFlagField var
I've been trying to create a fixture of a table, but it's always been failing with the following message: CommandError: Unable to serialize database: __str__ returned non-string (type method). The stacktrace was equally unhelpful, pointing to one of the Django files as the culprit. After some fiddling about, I've managed to pinpoint the culprit in the models.py: class UserExtra(model.Models): (...) blocked = BitFlagField( flags=( 'manual', 'system', 'tries', 'expired', 'inactivity', 'nosys_nobypass' ), db_column='ind_block' ) The class is only a list of vars and lacks any sort of function. If I remove that var and run the dumpdata command, it works. How do I serialize this field? -
Django SelectMultiple field with filter
what should I write here to filter participants by event ID 'participants' : forms.SelectMultiple( choices=Participant.objects.filter('event_id'), ), in parentheses was event = event_id but event_id I don't know how to initialize tried it like that def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['participants'] = Participant(queryset=Participant.objects.all()),