Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, what's the difference between verbose_name as a field parameter, and verbose_name in a Meta inner class?
Consider this class: class Product(models.Model): name = models.Charfield(verbose_name="Product Name", max_length=255) class Meta: verbose_name = "Product Name" I looked at the Django docs and it says: For verbose_name in a field declaration: "A human-readable name for the field." For verbose_name in a Meta declaration: "A human-readable name for the object, singular". When would I see either verbose_name manifest at runtime? In a form render? In Django admin? -
401 Client Error: Unauthorized for url [mozilla-django-oidc - Keycloack]
I'm integrating keycloak authentication in my django app After i am logged in into keycloak server i am facing error in the login callback HTTPError at /oidc/callback/ 401 Client Error: Unauthorized for url: http://keycloak:8080/realms/SquadStack/protocol/openid-connect/userinfo here is my docker-compose.yml services: db: image: postgres:13 environment: - POSTGRES_DB=squadrun - POSTGRES_USER=postgres - POSTGRES_PASSWORD=123456 volumes: - ~/.siq/pg_data:/var/lib/postgresql/data ports: - "5432:5432" networks: - local-keycloak redis: image: redis expose: - 6379 networks: - local-keycloak celery: build: context: . dockerfile: Dockerfile command: celery --app=squadrun worker -Q voice_make_ivr_india_queue,voice_send_email_india_queue,voice_send_email_india_upstox_queue,voice_send_sms_india_queue,voice_workflow_india_queue,celery_voice,ivr_queue,voice_analytics_and_metrics_queue,voice_fsm_india_queue,dnd_queue,voice_bulk_sync,voice_dnd_and_compliance_actions_queue,voice_notifications_queue,voice_make_ivr_india_queue,voice_send_email_india_queue,voice_send_email_india_upstox_queue,voice_send_sms_india_queue,voice_sync_ivr_details_india_queue,voice_workflow_india_queue,voice_sync_sms_details_india_queue,voice_send_sms_india_upstox_queue,voice_dnd_and_compliance_actions_upstox_queue,voice_imports_queue --concurrency=3 --without-heartbeat --without-gossip -n celery.%%h --loglevel=INFO container_name: celery working_dir: /home/docker/code volumes: - .:/home/docker/code depends_on: - db - redis networks: - local-keycloak web: build: context: . dockerfile: Dockerfile command: python -Wignore manage.py runserver 0.0.0.0:8001 container_name: django_web3 volumes: - .:/home/docker/code ports: - "8001:8001" depends_on: - db - redis networks: - local-keycloak keycloak: image: quay.io/keycloak/keycloak:20.0.2 command: start-dev container_name: keycloak ports: - "8080:8080" environment: - KEYCLOAK_ADMIN=admin - KEYCLOAK_ADMIN_PASSWORD=admin networks: - local-keycloak networks: local-keycloak: driver: bridge here is my setting.py AUTHENTICATION_BACKENDS = [ 'apps.voice.voice_auth.auth.KeycloakOIDCAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] OIDC_RP_CLIENT_ID = "voice-dashboard" OIDC_RP_CLIENT_SECRET = "rnX0eo0R43xnZficrZTkQQseyBip4V7t" OIDC_RP_SIGN_ALGO = "RS256" OIDC_OP_JWKS_ENDPOINT = "http://keycloak:8080/realms/SquadStack/protocol/openid-connect/certs" OIDC_OP_AUTHORIZATION_ENDPOINT = "http://172.20.0.3:8080/realms/SquadStack/protocol/openid-connect/auth" OIDC_OP_TOKEN_ENDPOINT = "http://keycloak:8080/realms/SquadStack/protocol/openid-connect/token" OIDC_OP_USER_ENDPOINT = "http://keycloak:8080/realms/SquadStack/protocol/openid-connect/userinfo" LOGIN_REDIRECT_URL = "/voice/dashboard/index/" LOGOUT_REDIRECT_URL = "/voice/dashboard/index/" here is auth.py class KeycloakOIDCAuthenticationBackend(OIDCAuthenticationBackend): def create_user(self, claims): """ Overrides Authentication Backend so … -
How can I run the for loop once on html (Django)
enter image description hereHow can I run the for loop once? when I run {% for q in questions|slice:':1'%} I have the problem that other questions in the database are not executed. I would like only one question per page to be displayed and after I click on next the next question will be loaded. I don't know how to solve the problem. See picture how two questions loaded in database on one page instead of just one. I hope someone have solution <form method="POST" action=""> {% for q in questions%} {% csrf_token %} {% if q.kategorie == category and q.flaag == True and forloop.first %} <br/> <div class="flex-containe"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next_question" value="{{q.question}}" class="neuefragenladen_button">Nächste Frage!</button></div> <div class="game_options"> <span> <input type="subit" id="option1" name="option1" class="radio" value="option1"/> <label for="option1" class="option" id="option1_label">{{q.op1}}</label> </span> <span> <input type="subit" id="option2" name="option2" class="radio" value="option2"/> <label for="option2" class="option" id="option2_label">{{q.op2}}</label> </span> <div class="game_question"> <h1 id="display_question">{{q.question}}</h1> </div> <span> <input type="subit" id="option3" name="option3" class="radio" value="option3"/> <label for="option3" class="option" id="option3_label">{{q.op3}}</label> </span> <span> <input type="subit" id="option4" name="option4" class="radio" value="option4"/> <label for="option4" class="option" id="option4_label">{{q.op4}}</label> </span> </div> </div> </div> <footer class="bottom-area"> <a class="information" href="https://www.google.at/?hl=de.">Impressum |</a> <a class="information" href="https://www.google.at/?hl=de.">Datenschutz |</a> <a class="information" href="https://www.google.at/?hl=de.">Support</a> </footer> ..... views.py def quiz(request): global globalCategory global globalQuestions global empty … -
Serializer for nested objects on POST query
Im new to DRF and i have problem with a nested serializer. I cannot save/create the list of ingredients in recipe. I'll start with model.Recipe that has a attribute ingredients ingredients = models.ManyToManyField(Ingredient, through='IngredientInRecipe', blank=True) model.IngredientInRecipe has the following attributes (i need through='IngredientInRecipe' because of the "amount" field) class IngredientInRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.SET_NULL, null=True) amount = models.DecimalField(max_digits=6, decimal_places=1, validators=[MinValueValidator(1)] ) When sending a POST query to /recipes/ with data, i get the following errror { "ingredients": [ { "id": 1, "amount": 10 } ], "tags": [ 1, 2 ], "name": "Recipe 1", "text": "Recipe 1", "cooking_time": 1 } TypeError at /api/recipes/ Field 'id' expected a number but got (<IngredientInRecipe: IngredientInRecipe object (14)>, True). the RecipeSerializer looks like below and debug show that the problem is in recipe_instance.ingredients.add(ingredient_in_recipe_instance) class RecipeSerializer(serializers.ModelSerializer): """Serializer for recipe objects""" author = UserSerializer(required=False) name = serializers.CharField(max_length=200, required=True) image = serializers.ImageField(required=False) ingredients = IngredientInRecipeSerializer(many=True) tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) def create(self, validated_data): tags_data = validated_data.pop('tags') ingredients_data = validated_data.pop('ingredients') recipe_instance = Recipe.objects.create(author=self.context['request'].user, **validated_data) for tag in tags_data: recipe_instance.tags.add(tag.id) for ingredient in ingredients_data: ingredient_instance = get_object_or_404(Ingredient,id=ingredient['id']) ingredient_in_recipe_instance = IngredientInRecipe.objects.get_or_create(ingredient=ingredient_instance, amount=ingredient['amount'], recipe = recipe_instance) recipe_instance.ingredients.add(ingredient_in_recipe_instance) return recipe_instance IngredientInRecipeSerializer - any thoughts would be greate class … -
Spider in Django views
I want to use scrapy spider in Django views and I tried using CrawlRunner and CrawlProcess but there are problems, views are synced and further crawler does not return a response directly I tried a few ways: # Core imports. from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings # Third-party imports. from rest_framework.views import APIView from rest_framework.response import Response # Local imports. from lrn_scrap.spiders.google import GoogleSpider class ForFunAPIView(APIView): def get(self, \*args, \*\*kwargs): process = CrawlerProcess(get_project_settings()) process.crawl(GoogleSpider) process.start() return Response('ok') is there any solution to handle that and run spider directly in other scripts or projects without using DjangoItem pipeline? -
How can I do authentication on the site and the built-in Users model and my own Employer Django
Happy New Year! I ran into a problem I am making a job search site on Django, I have the following logic: Authorization and authentication of ordinary job seekers using Django's built-in model - User Also separate authorization and authentication for users who provide work, i.e. employers, which are placed in my own model Employer Here is my Employer model class Employer(AbstractUser): full_name = models.CharField(max_length=150, verbose_name="Ім'я") main_office_city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name='Місто головного офісу') phone_number = models.ForeignKey(Phone, on_delete=models.CASCADE) email = models.CharField(max_length=50, unique=True, verbose_name='Email') hashed_password = models.CharField(max_length=120, default='') date_joined = models.DateTimeField(verbose_name='Дата реєстрації', default=timezone.now) def __str__(self): return self.full_name class Meta: verbose_name = 'Роботодавець' verbose_name_plural = 'Роботодавці' I read in the documentation that to create your own authentication system you can use the imitation from the AbstractUser class But in my case this is not the best choice, because AbstractModel adds its own fields by default. That is, I think that I need to either somehow make it so that the AbstractUser class does not add its fields, or think of some other authentication logic using another technology Maybe someone has some ideas how it can be done? -
in a django pass a value from a function to the get_context_data method in a view
I am trying to pass a value from a function to the get_context_data method in a view if i just try simple pass value from def to another def in python it works def function_1(): color = "red" size ="xxl" return color,size def function_2(): color,size = function_1() print(f"{color} {size} ") function_2() but when i try to apply it in django from custom def to get_context data it doesn't work def customDef(): color = "red" size ="xxl" return color,size def get_context_data(self,*arg,**kwargs): context = super(Myview,self).get_context_data(*arg,**kwargs) query = self.request.GET.get('item') color,size = customDef() context['posts'] = Mymodels.objects.filter(Q(name__startswith=query) ) if i try to add a parameter to get_context_data like this def get_context_data(self,customDef,*arg,**kwargs): I have an error message "missing 1 required positional argument" thank for help and happy new year -
I'm trying to reset the admin password I'm the admin panel
I'm using the django admin panel with jazzmin theme, I have created a link to reset the admin password after the reset is complete and trying to login in again. I got redirect to this path /account/profile/ There is no current url with this path I,m expecting to be redirect to the admin panel -
How do I get all candidate in a position
Am trying to query every candidate that belong to a specific position and loop through it using the django template in my html. If I have just one position/poll all candidate will display in my frontend, but once i add another position/poll then the list of the candidate will not display again def index(request): context = {} instruction = "" positions = Position.objects.order_by('priority').all() for position in positions: candidates = Candidate.objects.filter(position=position) for candidate in candidates: votes = Votes.objects.filter(candidate=candidate).count() if position.max_vote > 1: instruction = "You may select up to " + str(position.max_vote) + " candidates" else: instruction = "Select only one candidate" context = { 'positions': positions, 'candidates': candidates, 'votes': votes, 'instruction': instruction } return render(request, 'poll/index.html', context) {% block content %} <div class="row"> <div class="mt-5"> {% for p in positions %} {{ instruction }} <h1>{{ p.name }}</h1> <p>{{ p.description }}</p> {% for c in candidates %} <h1>{{ candidate.fullname }}</h1> {% endfor %} {% endfor %} </div> </div> {% endblock %} -
File upload not working, nothing is uploaded to media root
Here's the model class Document(models.Model): file = models.FileField() The template {% extends 'another-form.html' %} {% block content %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% bootstrap_field form.files %} <button class="btn btn-success col">Upload</button> </form> {% endblock %} Form class and view: from django import forms from django.urls import reverse_lazy from django.views.generic import FormView class UploadDocumentForm(forms.Form): files = forms.FileField(widget=forms.FileInput(attrs={'multiple': True}), label='') class UploadDocumentView(FormView): template_name = 'upload-document.html' form_class = UploadDocumentForm success_url = reverse_lazy('index') def form_valid(self, form): Document.objects.bulk_create([Document(file=f) for f in self.request.FILES]) return super().form_valid(form) when the form is submitted, I get these responses: [02/Jan/2023 14:43:13] "POST /upload-document/ HTTP/1.1" 302 0 [02/Jan/2023 14:43:14] "GET /upload-document/ HTTP/1.1" 200 70636 [02/Jan/2023 14:43:17] "GET /upload-document/ HTTP/1.1" 200 70635 and nothing is uploaded to settings.MEDIA_ROOT which is specified in settings.py and works for models.ImageField. I also tried file = models.FileField(upload_to=settings.MEDIA_ROOT) which is useless, included for confirmation, also: class UploadDocumentForm(forms.Form): files = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), label='' ) -
Creating a django form dynamically from a database model
I am trying do dynamically build a Questionnaire with its Questions and answers based on the information stored in a database. Database model: class Questionnaire(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) sequence = models.PositiveSmallIntegerField() text = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.text class QuestionAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=200) points = models.PositiveSmallIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.text I am trying to get a Form, that - based on a Questionnaire id passed to a view would render all Questions with their Questionanswers (as radio buttons). I started to design a Form that displays all the answers for a specific Question, if the question_id gets handed to a form: class QAForm(forms.Form): answer = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=QuestionAnswer.objects.none()) def __init__(self, *args, question_id=None, **kwargs): super().__init__(*args, **kwargs) if question_id is not None: print(question_id) self.fields['answer'].queryset = QuestionAnswer.objects.filter(question=question_id) This works, but I struggle to build a formset of QAForms that would cycle through the question_ids and show their answers for the user. I found https://forum.djangoproject.com/t/pass-different-parameters-to-each-form-in-formset/4040/2 - which seems to handle dynamic parameters to the formset forms. At this time though, i am starting to think that such solution is … -
getting error: subprocess-exited-with-error when dockerizing my project for the package reportlab, but this is not added in my requirements.txt
getting the following error when dockerizing my project this is the error message Collecting reportlab>=3.3.0 Downloading reportlab-3.6.12.tar.gz (4.5 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.5/4.5 MB 3.1 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] ##### setup-python-3.10.6-linux-x86_64: ================================================ ##### setup-python-3.10.6-linux-x86_64: Attempting build of _rl_accel ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/rl_accel' ##### setup-python-3.10.6-linux-x86_64: ================================================ ##### setup-python-3.10.6-linux-x86_64: =================================================== ##### setup-python-3.10.6-linux-x86_64: Attempting build of _renderPM ##### setup-python-3.10.6-linux-x86_64: extensions from 'src/rl_addons/renderPM' ##### setup-python-3.10.6-linux-x86_64: =================================================== ##### setup-python-3.10.6-linux-x86_64: will use package libart 2.3.21 !!!!! cannot find ft2build.h [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 ERROR: Service 'demo_project' failed to build : Build failed this is my requirements.txt file' celery==5.2.7 channels==3.0.4 Django==3.2.11 django-celery-beat==2.2.1 django-celery-results==2.3.1 django-environ==0.9.0 django-filter==21.1 Pillow==9.0.1 psycopg2-binary==2.9.3 pyotp==2.6.0 razorpay==1.3.0 redis==4.4.0 xhtml2pdf==0.2.5 and this is my dockerfile FROM python:3.10.6-alpine ENV PYTHONUNBUFFERED 1 … -
How to capture Django CSFR Cookie in Postman?
I am trying to send my first POST request that isn't handled inside Django to my Django server. I read in several tutorials from 3 years ago that I should somehow see the CSFR token value in the cookie, eg.: https://hackernoon.com/automatically-set-csrf-token-in-postman-django-tips-c9ec8eb9eb5b I cannot achieve that and I have problems finding tutorials on how to capture that cookie to use it later. Please help. -
Does't work django-admin startproject mfdw_site
I installed Python,and then Django.I checked that Django is installed with --version command.I installed VENV. Now I want to start a Project,but django-admin startproject my_site does't work. I'm working with VScode. What can I do? -
Appropriate Framework or Library in python for agent based or actor model algorithm service
Which Framework or Library in python suitable for agent based or actor model algorithm service? I've worked on develop new algorithmic trading platform which tend to active 24/7 for multiple crypto markets. I use django as a platform's framework but I don't know which framework or library are suitable for design agent-based or actor-based services. I used to django framework as a my framework to develop my algorithmic trading platform. But for scale up project I faced some problems to choose right framework -
selected option is not unselected while clicking on the element twice
select2 ajax select elements clicking once and unselect element clicking twice. This is by default .but in my case element is selecting by one click but not unselecting clicking twice. what is the problem here views.py def search(request): query=request.GET.get("q") print(query) vid=Video.objects.filter(tags__name__icontains=query).order_by("name").distinct() print(vid) vid_list=\[{'id':k.id,"name":k.name,"tags":','.join(k.tags.names())} for k in vid\] print(type(vid_list)) return JsonResponse(vid_list,safe=False) home.html <div class="form-group"> <label>Example of multiple select</label> <select class="form-control" multiple placeholder="Choose skills" id="some" required> </select> </div> scripts <script> $("p").click(function(){ $.ajax({ url:"{%url 'home' %}", success:function(data){ alert("this is a ajax alert") } }) }) $("#some").select2({ ajax:{ url:"{% url 'search'%}", data: function(params){ return{ "q":params.term } }, processResults:function(data){ console.log(data) return{ results:data.map(function(item){ return{id:item.id,name:item.name,tags:item.tags} }) } }, delay:250, cache:true, }, minimumInputLength:1, closeOnSelect: false, allowClear:true, multiple:true, placeholder: "Search Video", templateResult:function(repo){ console.log(repo) if (repo.loading) return repo.name; if (repo && !repo.selected){ return` <span> ${repo.name}(${repo.tags}) </span> ` } }, templateSelection:function(data){ return` <span > ${data.name} </span> ` }, escapeMarkup: function (markup) { return markup; }, }) </script> Now i want to know what is the reason behind this .i mean why option is not unselecting when i click second time on the option -
How to include a select2 multiselect box in a OpenStreetMap widget for Django Admin?
I have the following model, which contains a MultiPolygonField: class MyArea(models.Model): polygon = models.MultiPolygonField( _("Polygon"), null=False, blank=False, ) I have this model registered in Django Admin: @admin.register(MyArea) class MyAreaAdmin(admin.GISModelAdmin): # --> GISModelAdmin to render an OSM map for `polygon` pass Which renders the map, as desired: But now, I would like to include a select2 multiselect box on top of this map, where the user would be able to search another model in our database that contains polygons for administrative regions. class Locality(models.Model): polygon = models.MultiPolygonField( _("Locality Polygon"), null=False, blank=False, ) So the user would still be able to draw manual polygons if he wants too. But he could also search and select Locality objects that already contain complex administrative regions (polygons). Once a Locality object is selected the map should be refreshed to include the new region. How should I go about this? I have tried to create custom templates and custom forms, but did not got anywhere close to the solution -
Chart in javascript doesn't change color
I have a problem in javascript with building financial candlestick charts. I made a chart with apex.js and it displays the correct data where it should be but the color of the chart doesn't change, when the stock price is going up candlestick should be green when it goes down it should be red but on some stocks candlestick in always red and on some stocks it works fine. Here are the images, both charts use the same code but different data because it's different stock but that doesn't mean it should be displayed like this. Here is code for chart: <div id="chart"> </div> <script> var options = { series: [{ name: 'OHLC', data: [ {% for stock in stocks %} { x: new Date("{{stock.date}}"), y: [Number("{{stock.open}}"), Number("{{stock.high}}"), Number("{{stock.low}}"), Number("{{stock.price}}")], }, {% endfor %} ] }, ], chart: { type: 'candlestick', }, title: { text: '{{ticker}} Stock ', align: 'center' }, yaxis: { tooltip: { enabled: true } } }; var chart = new ApexCharts(document.querySelector("#chart"), options); chart.render(); </script> I am using Django in the backend so here is a function that returns chart data: @login_required(login_url='stock:login') def chart(request, ticker): stocks = Stock.objects.filter(ticker = ticker).order_by('date') context = {'stocks':stocks, 'ticker':ticker} return render(request, 'stock_app/chart.html', … -
2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the form
I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning. Views.py def Client_Update(request, Client_id): ClientUpdate = TestModel.objects.get(pk=Client_id) ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate) if request.method == 'POST': if ClientUpdates.is_valid(): ClientUpdates.save() return redirect('/Client_Details') return render(request, 'GymApp/ClientUpdate.html', {'ClientUpdate':ClientUpdate, 'ClientUpdates':ClientUpdates}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.Home, name='Home'), path('ClientList/', views.Client_list, name='Client_list'), path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'), path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'), path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'), path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'), path('Search/', views.Search, name='Search'), ] HTML Page {% extends 'GymApp/Layout.html' %} {% block content %} <h1>Updating status</h1> <form action="" method="POST"> {% csrf_token %} <div class="mb-3"> <input type="text" class="form-control" name="Name" placeholder="Client's Name"><br> <input type="text" class="form-control" name="Surname"placeholder="Client's Surname"><br> <select name="Gender" class="form-control"> <option selected disabled> Open this select menu </option> <option value="Male">Male</option><br> <option value="Female">Female</option> </select> </div> <div class="mb-3"> <input type="text" class="form-control" name="Weight" id="Weight" placeholder="Client's Weight"><br><br> <input type="text" class="form-control" name="Height" id="Height" placeholder="Client's Height"><br><br> <button type="button" onclick="calculation()">Calculation update</button> <br> </div> <br> <div class="mb-3"> <input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br> <select name="Activity_log" class="form-control"><br> <option selected disabled>Open this select menu</option> <option value="Not Active">Not Active</option><br> <option value="Active">Active</option> </select> <br> <button type="submit">Finalising update!</button> </div> </form> <script> function calculation(){ … -
Django-kafka. Distributed requests to an endpoint to handle millions of requests
Can anyone share some source to read. I have an api (django app), lots of people use it, i want this api handle millions requests. How can i make it distributed so this api can handle many requests. Should i make producer and consumer in one file? -
usage of require_POST in django
I wanna know is there a usage or security tip to use required-post or require-get decorators in django? from django.views.decorators.http import require_GET, require_POST -
Django: Webp conversion fails and creates empty picture element while all debugging efforts fail
I'm trying to create an upload form to upload multiple images that need to be converted to webp. Everything worked fine until i added the webp conversion bits. I tried adding exceptions and print statements to track down the issue but it just doesn't print any exceptions. Instead it shows all signs of success and creates an empty "picture" element in the database. I`m using the django cookiecutter project with pillow. models.py def upload_gallery_image(instance, filename): # Print a message to indicate that the function was called print(instance, filename) return f'galleries/{instance.facility.id}/{filename}' class Picture(models.Model): picture = models.ImageField(upload_to=upload_gallery_image) class Gallery(models.Model): facility = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='tourphotos') pictures = models.ManyToManyField(Picture, related_name='galleries') views.py class GalleryView(APIView): parser_class = (FileUploadParser,) def post(self, request): # Extract the facility ID and list of pictures from the request print('post method called') facility_id = request.data.get('facility') pictures = request.data.getlist('pictures') print(facility_id, pictures) facility = get_object_or_404(Facility, id=facility_id) try: gallery = Gallery.objects.get(facility=facility) except Gallery.DoesNotExist: gallery = Gallery.objects.create(facility=facility) for picture in pictures: print('for loop executing') try: webp_image = BytesIO() image = Image.open(picture) image.save(webp_image, format='webp', quality=75) print(webp_image) file_object = ContentFile(webp_image.getvalue()) print(file_object) picture_obj = Picture.objects.create(picture=file_object) print(picture_obj) gallery.pictures.add(picture_obj) print(gallery) except Exception as e: print(type(e)) continue webp_image.close() serializer = GallerySerializer(gallery) return Response(serializer.data, status=201) serializers.py class PictureSerializer(serializers.ModelSerializer): class Meta: model = Picture … -
DRF .as_viewset on {'post': 'list'} return attribute error?
I am trying to send some text: example: "Hello World" to DRF end-point. This endpoint on receiving this text is to send me a e-mail with the text. When I hit the end-point with Postman, I get the error: Internal Server Error: /api/errors Traceback (most recent call last): File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sid/eb-virt/lib/python3.8/site-packages/rest_framework/viewsets.py", line 117, in view handler = getattr(self, action) AttributeError: 'ErrorMsgViewSet' object has no attribute 'list' To test this out: urls.py from django.urls import path from .api import * urlpatterns = [ path('api/errors', ErrorMsgViewSet.as_view({'post': 'list'}), name='errors'), ] # I tried .as_view(), which gave me an error to change to the above format # i tried using router.register() and got errors on using generic.GenericAPIview api.py from rest_framework import viewsets from email_alerts.serializers import ErrorsSerializer class ErrorMsgViewSet(viewsets.GenericViewSet): serializer_class = ErrorsSerializer permission_classes = [ ] def post(self, request, *args, **kwargs): print(request.data) models.py from django.db import models # Create your models here. class ErrorsModel(models.Model): error_msg = models.CharField(max_length=5000, blank=True, null=True) serializers.py from rest_framework import serializers from email_alerts.models import ErrorsModel class ErrorsSerializer(serializers.ModelSerializer): error_msg = serializers.CharField( required=False, allow_null=True, allow_blank=True) class … -
Django: How to show a message in a custom admin action with a download?
I'm defining a custom admin action called Download CSV. In this action I want to download a .csv file and show a message to the user. I have not been able to make both happen. I tried this way: @admin.action(description=gettext_lazy("Download CSV")) def download_csv(self, request, queryset): self.message_user(request=request, message=gettext_lazy("Downloaded")) return self.create_csv() @staticmethod def create_csv() -> HttpResponse: headers = {'Content-Disposition': f'attachment; filename="download.csv"'} response = HttpResponse(content_type='text/csv', headers=headers) response.write(codecs.BOM_UTF8) csv.writer(response).writerows([['example']]) return response actions = [download_csv] Does anyone know how to do it correctly? Thanks. -
My celery-beat works locally but not in production?
my task: @shared_task def my_test(): # Executes every 2 minutes UserStatisticStatus.objects.filter(id=1).update(loot_boxes=+234) print('Hello from celery') app.conf.beat_schedule = { 'my-task-every-1-minutes': { 'task': 'user_statistic_status.tasks.my_test', 'schedule': crontab(minute='*/1'), }, } my settings: if 'RDS_DB_NAME' in os.environ: CELERY_BROKER_URL = 'redis://<myurl>/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-central-1', 'polling_interval': 20, } CELERY_RESULT_BACKEND = 'redis://<myurl>/1' CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_TASK_ROUTES = { 'my_test': {'queue': 'default'}, } my celery.py : import os from celery import Celery from project import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('celery_app') app.conf.task_routes = { 'my_test': {'queue': 'default'}, } app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) The worker connects and shows the tasks correctly and the beat starts too but nothing happening. I've tested it with the local redis server and everything works fine. Any help will be much appreciated Thank you