Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly update the foreign key's property of a Django model?
I have a Django Model named EmailSendingTask. This is the whole model- class EmailSendingTask(models.Model): order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='order') status = EnumChoiceField(SetupStatus, default=SetupStatus.active) time_interval = EnumChoiceField(TimeInterval, default=TimeInterval.five_mins) immediate_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='immediate_email') scheduled_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='scheduled_email') created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'EmailSendingTask' verbose_name_plural = 'EmailSendingTasks' def __str__(self) -> str: return f'EmailSendingTask: Order = {self.order}' The immediate_email and scheduled_email fields are responsible for holding two PeriodicTask objects. I have created a function called disable_scheduled_email, which is responsible for disabling the scheduled_email's periodic task. The detail of the function is here- def disable_scheduled_email(self): print(f'Disabling scheduled email...') self.scheduled_email.enabled = False self.save(update_fields=['scheduled_email']) Now, whenever I call this function and print the value of the self.scheduled_email.enabled, I find it False. But, when I try to look at the Django Admin site, the periodic task's enabled value remains as True. Why is it happening? -
When to make stripe subscription object and assign to user - Django
Tech Stack - Django, Angular I have been implementing stripe subscription model but stuck at some absurd scenario. I am getting Subscription not found by django. Please read the full scenario. Firstly I am successfull in creating stripe session. Code session = stripe.checkout.Session.create( metadata={'price_id':request.data.get('price_id'),'product_id':request.data.get('product_id'),'product_name':request.data.get('product_name')}, client_reference_id=request.user.id, customer=customer.stripe_customer_id, success_url='http://localhost:4200/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://localhost:4200/canceled.html', mode='subscription', line_items=[{ 'price': request.data['price_id'], # For metered billing, do not pass quantity 'quantity': 1, }], ) Webhooks Implementation: checkout.session.completed I am creating customer and subscription model in my db. print(user) customer = RecruiterUserProfile.objects.get(user = user) print(customer) customer.customer_id = session.customer customer.save() stripecustomer = Customer.objects.get(recruiter = customer, checkout_session_id = stripe_session_id) print(stripecustomer) stripecustomer.stripe_customer_id = stripe_customer_id stripecustomer.save() subscription,created = Subscriptions.objects.get_or_create(recruiter = customer, sub_id=stripe_subscription_id,customer_id = stripecustomer,stripe_customer_id = stripe_customer_id, payment_status=stripe_payment_status, amount = stripe_amount, status = stripe_status, product_id = stripe_metadata['product_id'], price_id = stripe_metadata['price_id'], product_name = stripe_metadata['product_name']) invoice.paid Then it triggers Invoice.paid, in which I am getting the subscription model and update others values in it. But since webhooks do not wait for our calls, Sometimes, It doesn't find the subscription. Now if I create subscription and customer in invoice.paid webhook using ger_or_create, How am I supposed to link it to the user. Below are my models: class Customer(models.Model): recruiter = models.OneToOneField(RecruiterUserProfile, on_delete=models.PROTECT) stripe_customer_id = models.CharField(max_length=80, blank=True, null=True) checkout_session_id = … -
How to pass current logged in users pk in django URLs?
So I have this detailview of Profile model (extended from django user model [onetoone]) class ProfileUpdate(UpdateView): model = Profile fields = [ "user", "bio", "fav_music_genre", "fav_Book_genre", "fav_movie_genre", ] success_url ="/home/all" in urls path('ProfileUpdate/<pk>',ProfileUpdate.as_view(),name="ProfileUpdate"), Now I wanna pass current logged in users pk in this path. I tried through template but its taking 1 by default. Is there any way by which I can put the current logged in users pk straight into the path in urls.py ? <a href="{% url 'app:ProfileUpdate' user.pk %}">Change</a> Any idea how can i approach this??? -
django upload image instantly by javascript
I am developing a chat app, working on the chat bubble container background image setting function. @csrf_exempt def chatProfileBackgroundUploadPost(request): if request.is_ajax() and request.method == 'POST': file = request.FILES['file'] try: ct = file.content_type if ct.split('/')[0] != 'image': return JsonResponse({}, status=400) chatProfile = request.user.chatProfile if chatProfile.background: chatProfile.background.delete() chatProfile.background = file chatProfile.save() return JsonResponse({'path': chatProfile.background.url}) except: pass return JsonResponse({}, status=400) window.crud = { backgroundUpload: function( file, success, error, ){ let fd = new FormData(); fd.append('file', file); $.ajax({ type: "POST", url: "{% url 'chat-profile-background-upload' %}", data: fd, processData: false, contentType: false, success: success, error: error, }) }, } chatMain.droppable = true; chatMain.ondragover = e => { e.preventDefault(); } chatMain.ondragenter = e => { chatMain.style.opacity = '0.75'; } chatMain.ondragleave = e => { chatMain.style.opacity = '1'; } chatMain.ondrop = e => { e.preventDefault(); let file = e.dataTransfer.files[0]; window.crud.backgroundUpload( file, res => { chatMain.style.opacity = '1'; setBackground(res.path); }, window.requestError, ) } sorry for the amount of code, the function is pretty straight forward: if a user drag and drop an image to the chat area, it will be set to background. and it works perfectly as I expected. but not friendly for smart phone, therefore, I added an upload button. (there is no form, only a … -
use @property in tow apps in django
app user model `class user(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) @property def full_name(self) return self.name + self.last_name` app wallet model class wallet(models.Model): amount = models.IntegerField() admin wallet ` class UserrInline(admin.TabularInline): list_display = [full_name]---> but i cant use property in app user class walletAdmin(admin.ModelAdmin): inlines = [UserrInline]` admin.site.register(wallet, walletAdmin) i cant use property in tow apps in django -
Django, unable to filter all items under one or more categories attached to it using dynamic bootstrap 5 nav pills using many to many relationship
Given the files below am unable to filter all items relating to one category or more than one category. Example: let items = A, B, C, D categories = 1, 2, 3, 4 items in category 1 = A and B items in category 2 = C and D category 3 and 4 are not having any items attached to them, they should return empty Have a look at the files and kindly guide below models.py class Category(models.Model): name = models.CharField() class Item(models.Model): name = models.CharField() category = models.ManyToManyField(Category) views.py def filter_item(request): template = 'template.html' cat = Category.objects.all() context = {'cat': cat, } return render(request, template, context) template.html <ul class="nav nav-tabs" id="myTab" role="tablist"> {% for c in cat %} <li class="nav-item" role="presentation"> <button class="nav-link {% if c.id == '{{ c.id }}' %} active {% endif %}" id="{{ c.name|slugify }}-tab" data-bs-toggle="tab" data-bs-target="#{{ c.name|slugify }}" type="button" role="tab" aria-controls="{{ c.name|slugify }}" aria-selected="true">{{ c.name }}</button> </li> {% endfor %} </ul> <div class="tab-content" id="myTabContent"> {% for c in cat %} {% for i in c.item_set.all %} <div class="tab-pane fade {% if i.category.id == c.id %} show active {% endif %}" id="{{ i.name|slugify }}" role="tabpanel" aria-labelledby="{{ i.name|slugify }}-tab">{{ i.title }}</div> {% endfor %} {% endfor %} … -
KeyError at 'body' when i send a request with fecth. Django and ReactJs project
i´m doing a project with django (django rest framework) as backend and React js as Front for some reason the 'body' isn´t send to the backend. here the django view: @api_view(['POST']) def crearTarea(request): data = request.data print(data['body']) tarea = Tarea.objects.create( body=data['body'] ) serializer = TareaSerializer(tarea, many=False) return Response(serializer.data) the request in react with fetch: let crear = () =>{ let tarea_json = { "titulo": document.getElementById("titulo").value , "descripcion": tarea.descripcion, "tiempo_tarea": 1, "fk_idUsuario": 1 } fetch('/api/tareas/create', { method: "POST", body: JSON.stringify(tarea_json), headers: { 'Content-Type': 'application/json' } }) } the model: class Tarea(models.Model): titulo = models.CharField(max_length=50) descripcion = models.CharField(max_length=150) tiempo_tarea = models.ForeignKey(Tiempo_tarea, on_delete = models.CASCADE) fk_idUsuario = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["created"] db_table = "Tarea" verbose_name_plural = "Tareas" verbose_name = "Tarea" def __str__(self) -> str: return self.titulo and the error: enter image description here i´m traying to create a new instance with the method POST and fecth but it doesn´t run. I would be grateful if you could help me -
Django file upload returns None, please help me
im trying to learn Python and Django, when i try to upload a file in my form Django detect my file as "None", if someone can help me i would apreciate it a lot, Below is my code. forms.py: from django import forms class FormularioTrabajo(forms.Form): email = forms.EmailField(label="Correo Electrónico:", max_length=254) Currículum = forms.FileField() views.py: In views i want to save the file uploaded in the directory /media/ def trabaja(request): if request.method == 'POST': form = FormularioTrabajo(data=request.POST, files=request.FILES) if form.is_valid(): file = request.FILES.get('file', None) if file is not None: file_name = file.name file_path = '/media/' + file_name with open(file_path, 'wb+') as destination: for chunk in file.chunks: destination.write(chunk) form.save() return HttpResponseRedirect(reverse("miapp:index")) else: return HttpResponse('None') else: form = FormularioTrabajo() return render(request, "web/trabajar.html", {'form':form}) This is my template html: {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} {% bootstrap_messages %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static '/style.css' %}"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script> <title>Trabaja con nosotros</title> </head> <body> <header> <br> <ul> <li><a href="conocernos.html">Conócenos</a></li> <li><a href="login.html">Inicio de Sesión</a></li> <li><a href="signup.html">Registro de usuario</a></li> <li><a href="contacto.html">Contacta con nosotros</a></li> </ul> {% load static %} <a href="index.html"><img src="{% static 'img/logo.PNG'%}" class="logo"></a> </header> <div class="work-box"> … -
How to get the results of a queryset to display as a subsection within a another class-based list view
Need help / advice with Django. I have two apps with models. App1 Player with Model player App2 Competition with models Competition and Team the latter being a through table expanding on the Player table Players can be assigned to multiple Competitions Each competition has a Team via a through table expanding on the Player table Extracts of models below Player and Competition have class based list and detail views In the Competition detail view I would like to list all Players for that particular competition. I can only get as far as proving the principle on the command line >>> comp_one = Competition.objects.get(name="comp one") >>> comp_one.team_members.all() <QuerySet [<Player: Armstrong>, <Player: Smith>, <Player: Jones>]> Then as a novice I’m a bit lost how to perform the queryset on the current competition rather than hard coded competition name where to put the queryset function - views.py or models.py how to get the Team listed in the competition detail template class Player(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) first_name = models.CharField(max_length=50) nick_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=100) class Meta: ordering = ["last_name"] def __str__(self): return self.last_name def get_absolute_url(self): return reverse(“player_detail", args=[str(self.id)]) class Competition(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) … -
How to get the row's whose id' value is used in other rows as parent id value
Id parent id 1. Null 2. Null 3. 1 4. 1 5. 1 6. 2 7. 2 8. 2 9. 2 10. 2 I have this table I want something like this I have one parameter Min parent id count Which means if i set min parent id count 2 I should get row with id 1 and raw with id 2 Cause row with id 1 is used in parent id for 3 times And row with id 2 is used in parent id for 5 times If set min parent id count to 4 I should only get row which has id 2 cause id is used in parent id for 5 times What i want is to check for every row how many times its id value used in as value in parent id For here is 1 is used for 3 times And id 2 is used for 5 times -
how can I display the average rating as stars?
I'm working on my web app and I want to display the average rating to doctors but when I tried the avg and created a function in my model it just showed me the last rate, not the average this is my model class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) def averagreview(self): reviews = Comments.objects.filter( doctor=self).aggregate(average=Avg('rating')) avg = 0 if reviews["average"] is not None: avg = float(reviews["average"]) return avg def countreviews(self): reviews = Comments.objects.filter( doctor=self).aggregate(count=Count('id')) cnt = 0 if reviews["count"] is not None: cnt = int(reviews["count"]) return cnt this the Comments model class Comments(models.Model): doctor = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='comment') created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') # co_email = models.ForeignKey( # User, on_delete=models.CASCADE, related_name='comment') review = models.TextField(max_length=400, verbose_name='التعليق') rating = models.IntegerField(default=0) this is my HTML <div class="rating"> <div class="text"> <span class="rating-star"> <i class="fa fa-star{% if doctor.averagreview < 1%}-o empty checked{% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 2%}-o empty checked {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 3%}-o empty checked{% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 4%}-o empty checked{% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 5%}-o empty checked{% endif %}" … -
Django development Server does not reload in docker container
with cookiecutter-django I use the docker setup in the sync version. Unfortunately, the development server does not restart automatically on any code change. Which means I would need to restart the containers on every change, which is a hassle. Thanks for any help -
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.