Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the method form.is_valid always returns always
I do my own project and I'm stuck on this problem. My form always returns False when calling form.is_valid. This is my code: forms.py: I need to let user to choose the size he need from the list of available sizes, so I retrieve sizes from the database and then make a ChoiceField with variants of these sizes. class CartAddProductForm(ModelForm): class Meta: model = Product fields = ['sizes'] def __init__(self, pk: int, *args, **kwargs) -> None: super(CartAddProductForm, self).__init__(*args, **kwargs) sizes = tuple(Product.objects.get(pk=pk).sizes) sizes_list = [] for item in sizes: sizes_list.append((item, item)) self.fields['sizes'] = forms.ChoiceField(choices=sizes_list) views.py: This func creates the form def product_detail(request: WSGIRequest, product_id: int, product_slug: str) -> HttpResponse: product = get_object_or_404(Product, id=product_id, slug=product_slug, available=True) categories = Category.objects.all() cart_product_form = CartAddProductForm(instance=product, pk=product_id) return render(request, 'shop/product/detail.html', {'product': product, 'categories': categories, 'cart_product_form': cart_product_form}) When user pushes the button 'Add to cart' he is redirected to the other page with details of his cart. So here's the problem: @require_POST def add_to_cart(request: WSGIRequest, product_id: int) -> HttpResponseRedirect: cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(instance=product, pk=product_id) if form.is_valid(): cd = form.cleaned_data print(f'cd = {cd}') cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) else: print(f'form.is_valid = {form.is_valid()}') print(f'request.POST = {request.POST}') print(f'form.errors = {form.errors}') print(f'form.non_field_errors = {form.non_field_errors}') field_errors = … -
How to use wkhtmltopdf in Windows dockerized Django app
I have an invoicing app that I made using Django. So far the invoicing app works fine without docker by specifying the wkhtmltopdf path in my windows as follows '''config = pdfkit.configuration(wkhtmltopdf='C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')''' However, I decided to rebuild the app using Docker for deployment purposes. As a result, I am receiving the following error when I run the same app using docker. " OSError: No wkhtmltopdf executable found: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" I have researched the internet on wkhtmltopdf docker image files but solutions are not made for windows or clear to me. Here Is my Docker file: # Pull base image FROM python:3.10.4-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . Can anyone please help me? which methods that I have to employ so that I can print pdfs from my docker environment? I am novice to Docker. Thanks In Advance -
Wrong Django User Creation
I created Users inside the admin view with my custom User model: class User(AbstractUser): phone_number = models.CharField(max_length=64) department = models.CharField(max_length=128) misc_settings = models.JSONField(null=True, blank=True) RelatedGroup = models.ManyToManyField(Group, related_name='GroupMember') when I created them, they appear there and seem to have everything i wanted, a username and an id/pk: [thats the screenshot of the admin] https://i.stack.imgur.com/RqJEB.jpg) However, when I try to check for them in the shell, they don't seem to exist properly? In [1]: from accounts.models import User In [2]: antoine = User(id=4) In [3]: antoine.id Out[3]: 4 In [4]: b = User(username="antoine") In [5]: b.id In [6]: b.username Out[6]: 'antoine' In [7]: antoine.username Out[7]: '' I need them to have, both a username and an id, how come they dont seem to have it? I'm honestly pretty new to both django and databases, so I dont get why this straight forward approach doesn't work type here -
Tailwind UI components not working in Django templates
I'm trying to use tailwind UI components in my Django project (I use Djang as Fullstack framework, not Django's REST Framework). The components I want to use require Vue.js or React (I went with Vue.js). When I copy & paste the components into my Django templates, the Vue.js code doesn't seem to work. By default, it's loaded in a <script setup> tag, and I tried loading it from a cdn like so: <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type='text/javascript'>...</script> But it still doesn't work. I'm using django-tailwind to run tailwind. Anybody else who set up Tailwind UI Components in Django Templates and can help me with this? -
Django NOT NULL constraint error on imaginary field
I have been getting the following error. django.db.utils.IntegrityError: NOT NULL constraint failed: doctor_owner.doc_name This error primarily arises on when I save the owner information using .save() and the error it gives is on doc_name, which is not present in the model definition of the class Owner. I am clueless why it is giving such an error. My model is attached below: . This is my model description: from django.db import models # Create your models here. from base.models import BaseModel class Owner(BaseModel): owner_id = models.CharField(max_length=50) owner_name = models.CharField(max_length=250) class Pet(BaseModel): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) pet_name = models.CharField(max_length=100) pet_age = models.DecimalField(max_length=3, decimal_places=2, max_digits=50) pet_specie = models.CharField(max_length=250) pet_gender = models.CharField(max_length=1) class Medicine(BaseModel): medicine_name = models.CharField(max_length=250) frequency = models.CharField(max_length=100) duration = models.CharField(max_length=100) class Prescription(BaseModel): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) class Treatment(BaseModel): pet = models.ForeignKey(Pet, on_delete=models.CASCADE) owner = models.ForeignKey(Owner, on_delete=models.CASCADE) doc_name = models.CharField(max_length=250) prescription = models.ForeignKey(Prescription, on_delete=models.CASCADE) -
Quickly switch out external services, or inject mock services, using a factory and import_string, a good pattern?
I wanted a quick way to be able to switch out queue services, and use any one of Kafka, RabbitMQ, etc. or even replace with a Mock queue service. So I set it up using import_string. There is an Abstract Base Class (ABC), queue factory, the implementations and a value in settings.py which says which queue to use. class Producer(ABC): """Abstract producer.""" @abstractmethod def send_message(self, queue_name, message): """Send a message to a queue.""" pass class KafkaProducer(Producer): """Kafka producer.""" def send_message(self, queue_name, message): """Send a message to a Kafka queue.""" send_message_to_kafka(message) class QueueFactory: """Queue factory.""" @staticmethod def get_producer(): """Get configured queue producer.""" return import_string(settings.QUEUE_PRODUCER_CLS)() In settings.py: QUEUE_PRODUCER_CLS = "queues.kafka.KafkaProducer" # set to Kafka queue QUEUE_PRODUCER_CLS = "queues.tests.mock_queue.MockProducer" # set to Mock queue Then you can call it like so: QueueFactory.get_producer().send_message("my-queue", "my message") Not sure if it's the best way, does this make sense? Just feel like it's quite a bit of boilerplate code. -
How can i connect users to add their own recipes?
Im creating a blog-app where users can create an account and i want them to be able to add their recipes to my site. I'm having some trouble to set these up and am currently getting these errors in my browser when clicking the button for "add your own recipes here: TypeError at /create/ Post() got an unexpected keyword argument 'initial' Request Method: GET Request URL: http://localhost:8000/create/ Django Version: 3.2.16 Exception Type: TypeError Exception Value: Post() got an unexpected keyword argument 'initial' Exception Location: /workspace/.pip-modules/lib/python3.8/site-packages/django/db/models/base.py, line 503, in init Python Executable: /home/gitpod/.pyenv/versions/3.8.11/bin/python3 Python Version: 3.8.11 Python Path: ['/workspace/bake-me-a-cake', '/home/gitpod/.pyenv/versions/3.8.11/lib/python38.zip', '/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8', '/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/lib-dynload', '/workspace/.pip-modules/lib/python3.8/site-packages', '/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/site-packages'] Server time: Wed, 30 Nov 2022 15:12:25 +0000 My code is as following (in views.py): from django.shortcuts import render, get_object_or_404, reverse from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic, View from django.http import HttpResponseRedirect from .models import Post, Comment from .forms import CommentForm from django import forms class PostList(generic.ListView): """ View published recipes and how many are viewable per page """ model = Post queryset = Post.objects.filter(status=1).order_by('created_on') template_name = 'index.html' paginate_by = 6 class PostDetail(View): """ view comment and likes information """ def get(self, request, slug, *args, … -
problem with the "@" character in the django template
I'm passing a dictionary in the django view with the context key names come from an external json file mydata = {'@item': 'Kotokeno', '@model: '200', 'price': '320'} context['mydata'] = mydata and in the view I display like this {mydata.@item}} the problem and with the "@" character which is used in the django template engine and it gives me an error Could not parse the remainder: '@item' from 'mydata.@item' how can I either escape in the template this character or maybe in views.py rename the key names (with pop()) or any other solution. thank you -
Nginx/UWSGi/Django Stack "AppRegistryNotReady("Apps aren't loaded yet.")"
I have been racking my brain on this for probably about 32 hours total at this point, and any help is welcome. Currently stuck at an 'Internal Server Error' in browser. Error Message/Traceback: $ python3 manage.py check Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/django/django_venv/lib64/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/home/django/django_venv/lib64/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/django/django_venv/lib64/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/django/django_venv/lib64/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/django/django_venv/django_site/settings.py", line 17, in <module> import urls File "/home/django/django_venv/django_site/urls.py", line 25, in <module> path("/data_sources/", include("data_sources.urls")), File "/home/django/django_venv/lib64/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/django/django_venv/django_site/data_sources/urls.py", line 3, in <module> from . import views File "/home/django/django_venv/django_site/data_sources/views.py", line 2, in <module> from summary.models … -
ERROR: admin.E108 and admin.E116 Django Framework Python
<class 'blog.admin.CommentAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'active', which is not a callable, an attribute of 'CommentAdmin', or an attribute or method on 'blog.Comment'. <class 'blog.admin.CommentAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'active', which does not refer to a Field. I am receiving these two errors. This is my models.py code: from django.contrib.auth.models import User # Create your models here. STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updatedOn = models.DateTimeField(auto_now= True) content = models.TextField() createdOn = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-createdOn'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() createdOn = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=False) class Meta: ordering = ['createdOn'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) This is my admin.py code: from django.contrib import admin from .models import Post, Comment # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status','createdOn') list_filter = ("status", 'createdOn') search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'createdOn', 'active') list_filter = ('active', 'createdOn') search_fields = ('name', 'email', 'body') … -
How can I compare the user's answer in the quizz with the correct answer in the database?
How can I compare the user's answer in the quizz with the correct answer in the database and give a point if the answer is correct? currently i get all answers wrong, after the quiz.I Want, if the user choice the right answer, that he get a point and if the answer wrong than get he 0 points. views.py def math(request): if request.method == 'POST': print(request.POST) questions = QuesModel.objects.filter(kategorie__exact="mathematics") score = 0 wrong = 0 correct = 0 total = 0 for q in questions: total += 1 answer = request.POST.get(q.question) if q.ans == answer: score += 10 correct += 1 else: wrong += 1 percent = score / (total * 10) * 100 context = { 'score': score, 'time': request.POST.get('timer'), 'correct': correct, 'wrong': wrong, 'percent': percent, 'total': total, } return render(request, 'result.html', context) else: questions = QuesModel.objects.all() context = { 'questions': questions } return render(request, 'mathe.html', context) model.py class QuesModel(models.Model): Categorie= ( ("mathematics", "mathematics"), ("Business Administration", "Business Administration"), ) categorie= models.CharField(max_length=400, null=True, choices=Categorie) explaination= models.CharField(max_length=400, null=True) user = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) question = models.CharField(max_length=200, null=True) op1 = models.CharField(max_length=200, null=True) op2 = models.CharField(max_length=200, null=True) op3 = models.CharField(max_length=200, null=True) op4 = models.CharField(max_length=200, null=True) ans = models.CharField(max_length=200, null=True) def __str__(self): return self.question … -
Global Pagination not working on DRF Project
I have written an API on DRF which returns a list of data based on certain conditions, but the data is very large and global pagination is not applying on it. As a result, speed slows down and therefore, data is not shown properly on a single page. I have adding following code in settings.py file: REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10 } This is my API: class TeacherViewSet(ModelViewSet): queryset = Teacher.objects.all() serializer_class = serializers.TeacherSerializer authentication_classes = [TokenAuthentication] def list(self, request, *args, **kwargs): response = [] for teacher in queryset: name = Student.objects.filter(teacher=teacher).values("name") res = {"name": name} response.append(res) return Response(response) Any thing wrong I am doing? -
Django server is not restarting
Im using Django and after commit new edits I need to restart my server to see them But everytime after restart with 'python manage.py runserver' my server is not loading I need to use another port to see my website Im using Pycharm and Debian terminal I tried to reboot my pc and it helped but only for a 1 time, I mean I can start my server by a default port but cant restart him again with the same port -
Django DRF polymorphic serializer
I have a model like this: class MyModel(Model): fieldA = models.CharField() fieldB = models.CharField() fieldC = models.CharField() flag = models.BooleanField() And I had a serializer for this model class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('fieldA', 'fieldB', 'fieldC', 'flag') using case is: qs = MyModel.objects.filter(.....) data = MyModelSerializer(qs, many=True) But now I faced with problem, that I need dynamically serialize only fieldA if flag is False and serialize whole model if flag is True. I know that I can overcome my issue by using SerializerMethodField for every field I want to be optional. But if I have 10+ optional fields, It becomes disgusting. How can I create an Polymorphic serializer, which can conditionally serialize model with one of two ways? -
Plotly + Python: Easiest option to customize a Plotly graph in a Django template
I want to show several Plotly graphs on a Django page. I already have the Python lists with the data that I want to include in the graphs. I found a code that works, but apparently it's old or strange (all the other Plotly code snippets that I see are very different) and I can't really customize it (trying to use lines/concepts from the "official" code snippets doesn't work with this old/strange code). The code that works for me is: from plotly.offline import plot from plotly.graph_objs import Scatter plot_scatter = plot([Scatter(x=x_data, y=y_data, mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') context = { 'plot_scatter' : plot_scatter, OTHER STUFF } return render(request, 'hello/graphs.html', context) That works, but then I want to reduce margins for example, and I find examples such as https://plotly.com/python/setting-graph-size/ where the code is very different to "mine" and I can't adapt it (maybe there is a way, but I tried different options without any luck). And the default code from Plotly (e.g.https://plotly.com/python/figure-structure/) is not designed to be used inside Django and I don't know how to adapt it to Django either. I'm still learning Python, so maybe there is an obvious solution that I'm missing. Any tips, ideas or links would … -
how to color text with condition in django?
I have a django app and I want to color some text, if that text is true in dictionary. So I have this method:views.py def data_compare2(request): template = get_template("main/data_compare.html") dict2 = {"appel": 3962.00, "waspeen": 3304.07, "ananas":24} context = {"dict2": dict2} res = dict((v,k) for k,v in dict2.items()) return HttpResponse(template.render(context, request, res[3962.00])) and this is the template: <body> <div class="container center"> {% for key, value in dict1.items %} {%if {{res}} %} <div style="background-color:'red'"></div> {%endif%} {{ key }} {{value}}<br> {% endfor %} </div> </body> So the text appel": 3962.00 has to appear in red. Question: how to make the founded text in dictionary red? -
Circular import error while trying to implement a new ForeignKey() in Django
I am working on an API project that provides endpoints to front-end. There is a new field must added to related model that is "organization". Firstly, this field must added to "File" model as a foreign key and other related files like populator, renderer and validator. Secondly, 'organizationId" filter must added to /files/ endpoint. Here are my codes: files/models.py # Django from django.db.models import( CharField, ForeignKey, PROTECT, ) # Authic - Common from authic.common.models import Model # Authic - Organization from authic.organizations.models import Organization ALLOWED_EXTENSIONS = [ 'avif', 'gif', 'jpeg', 'jpg', 'mp4', 'png', 'svg', 'webm', 'webp' ] class File(Model): cloudinary_public_id = CharField( blank=True, null=True, default=None, max_length=64 ) extension = CharField( blank=True, null=True, default=None, max_length=4 ) organization = ForeignKey( Organization, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None, ) class Meta: db_table = 'files' organizations/models.py # Django from django.db.models import ( BooleanField, CharField, ForeignKey, PROTECT, TextField ) # Authic - Common from authic.common.models import Model # Authic - Files from authic.files.models import File class Organization(Model): name = CharField( blank=False, null=False, default=None, max_length=256 ) url = CharField( blank=False, null=False, default=None, max_length=2048 ) theme_color = CharField( max_length=7, blank=False, null=False, default=None ) logo = ForeignKey( File, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None ) html_title = CharField( blank=False, null=False, … -
Filter current user products using queryset in DRF returns []
I am trying to filter list of products linked with a user. I want to display only current users product instead of listing all. I tried this class ProductCreateList(generics.ListCreateAPIView): serializer_class = ProductSerializer def get_queryset(self): user = self.request.user return Product.objects.filter(user=user.id) serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'user', 'name', 'imgUrl', 'selling_price', 'actual_price', 'quantity', 'get_profit'] models.py class Product(models.Model): user = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, default=1) name = models.CharField(max_length=100, null=True, blank=True) imgUrl = models.TextField(default='') selling_price = models.FloatField(null=True, blank=True) actual_price = models.FloatField(null=True, blank=True) quantity = models.IntegerField() I got [] object when I tried to execute the endpoint. What's my mistake here? -
How to get specific objects from two list of dictionaries on a specific key value?
As i said I have two lists of dictionaries. Which are following below. timing = [ {"day_name":"sunday"}, {"day_name":"monday"}, {"day_name":"tuesday"}, {"day_name":"wednesday"}, {"day_name":"thursday"}, {"day_name":"friday"}, {"day_name":"saturday"}, ] hours_detail = [ {"day_name":"sunday","peak_hour":False}, {"day_name":"monday","peak_hour":False}, {"day_name":"tuesday","peak_hour":False}, {"day_name":"wednesday","peak_hour":False}, {"day_name":"thursday","peak_hour":False}, {"day_name":"friday","peak_hour":False}, {"day_name":"saturday","peak_hour":False}, {"day_name":"saturday","peak_hour":True}, {"day_name":"friday","peak_hour":True}, {"day_name":"thursday","peak_hour":True} ] now i want to create an other list of dictionaries. that contain values like below. i'm basically combining these two lists and also rearranging according to the day name. final_data_object = [ { "timing" :{"day_name":"saturday"}, "hour_detail":[ {"day_name":"saturday","peak_hour":False}, {"day_name":"saturday","peak_hour":True}, ] }, { "timing" :{"day_name":"friday"}, "hour_detail":[ {"day_name":"friday","peak_hour":False}, {"day_name":"friday","peak_hour":True}, ] }, soon on... ] I have tried this but it didn't work. data = [] for time_instance in timing: obj={ "timing":time_instance } for pricing_instance in pricing: if time_instance["day_name"] == pricing_instance["day_name"]: obj["pricing"] = pricing_instance data.append(obj) return data -
No Module Found, "name of the app", when running django from pipeline
So here is my set up : "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: backend.project.settings "PYTHONPATH": "/opt/python/current/:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: backend.project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:process:default": HealthCheckPath: "/ht/" MatcherHTTPCode: "200" "aws:elasticbeanstalk:environment:proxy:staticfiles": /html: statichtml /static-files: static-files /media: media-files container_commands: 10_deploy_hook_permissions: command: | sudo find /backend/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; sudo find /var/app/staging/backend/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; Which it runs: #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/backend/manage.py makemigrations --noinput python /var/app/current/backend/manage.py migrate --run-syncdb python /var/app/current/backend/manage.py collectstatic --noinput wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.project.settings') application = get_wsgi_application() Logs from web.stdout.log Nov 30 13:50:46 ip-172-31-32-98 web: ModuleNotFoundError: No module named 'category' 'category' is one of the django app or module that contains models, view etc Any help on what's wrong here I can run the app with eb deploy but when trigger from pipeline it does not -
Django first part of accordion open but not the other within for loop
I tried to make an accordion using jquery inside my code but there is a problem when I try to open a section. This first one is working but not the second one. The code is inside a django for loop. **HTML : ** <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(function() { $('#accordeon').on('click', function(){ $(this).next().slideToggle(300); $('.accordeon-content').not($(this).next()).slideUp(300); $(this).toggleClass('active'); $('#accordeon*').not($(this)).removeClass('active'); }); }); </script> <div class="consultations"> <div class="section nosProduits"> <div class="two-blocks"> <div class="content"> <h2>Qu’est-ce que la consultation patrimoniale ?</h2> <p>Vous pensez l’expertise sur mesure d’un CGP expert inaccessible ? Pour feter nos 20 ans, nous avons innové pour vous permettre de bénéficier de l’accompagnement d’une équipe de spécialistes du patrimoine sous la forme d’une consultation de 30 minutes à 120 € TTC. </p> </div> <div class="video"> {% embed 'https://www.youtube.com/watch?v=LqiaOqiLcU4' %} </div> </div> {% for subcategory, products2 in products.items %} <div class="head" id="accordeon"> <h2>{{subcategory}}</h2> </div> <div class="accordeon-content line" style="display: none;"> {% for product in products2 %} <div class="block-consultation"> <div class="titre"> <h3>{{ product.name }}</h3> {% if product.images %} <img src="{{ product.images|first }}" class="categoryImg" alt="Image of {{ product.name }}."> {% endif %} </div> <div class="content"> <div class="description"> <p>{{ product.description }}</p> </div> <div class="options"> <div class="product"> <div> <a href="{% url 'product-purchase' pk=product.djstripe_id %}" class="btn">Souscrire</a> </div> </div> </div> </div> </div> {% … -
need a better way to validate fields in request body django depending on a specific field value
The requirement is to verify body fields in an api request depending on another field. Like: the request data has a field: action If actions is deactivate then no other field should be present in the body data however if the action is anything else we want to allow updating other fields as well such as name. currently we have a validation where we are going through the dictionary keys and comparing like below: expected_keys = ['client_updated', 'updated_by', 'actions'] if key not in expected_keys: raise ValidationError("Deactivation action does not allow {} to be updated".format(key)) Just wanted to know if there is a better way to handle via django or django rest framework, with somewhat less harcoding. -
Why create_superuser manager is not working in custom user model?
When I try to create a superuser in my app I get the next error: Traceback (most recent call last): File "C:\Users\acer\Desktop\prod\DirCom\DirCom\manage.py", line 22, in <module> main() File "C:\Users\acer\Desktop\prod\DirCom\DirCom\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 88, in execute return super().execute(*args, **options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 183, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\base.py", line 561, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 338, in __set__ super().__set__(instance, value) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 235, in __set__ raise ValueError( ValueError: Cannot assign "1": "User.persona" must be a "Persona" instance. Before that createsuperuser step I have a custom script that creates the first Persona of the project, and what I'm trying is to assign the first person created with ID 1 to this superuser. My model looks like this: class Persona(models.Model): """ Clase para generar mi modelo de Persona que es el modelo previo a crear un usuario, en este modelo se guardan todos los datos personales """ DEPENDENCIES_CHOICES = ( ("1", "Rectorado - Gabinete"), ("2", "Vice Rectorado"), ("3", "Rectorado - Secretaria … -
How to Implement Conditional Filter in Django Query set
I am writing a queryset in which I am in need to check the value that exists in the table or not but here is a twist. example: if a value is: "12345, ABVC43F, T5T5YUH/KJUTG678, 1234567890PO-QWERT4567-OIUYT8765-POIUY7890" which I am getting in request and like this lots of values are stored in the table. but the checking is like out of these 4 values (after split from comma we will get 4 values ) if any 3 or more than 3 gets matched with any of the records in the table then this queryset will return that complete string value from the table to which it matches. key_in_request = "12345, ABVC43F, T5T5YUH/KJUTG678, 1234567890PO-QWERT4567-OIUYT8765-POIUY7890" req_key_array = key_in_request.split(',') for getting more clarity i have a example of sql query for what i need but unable to write queryset: SQL query is here: select if((key_value is having req_key_array[0]), 1, 0) + if((key_value is having req_key_array[1]), 1, 0) as Result; here it will sum then all the 1 and 0 if conditions will be false or true, it's not a exact query but near to that. It's my first try to post question hope you will understand, if any issue please comment. -
How to test if a function gets called when another function executes in django test?
I've a method inside a manager, this method calls a function imported from different module now I'm trying to write a test that make sure the function gets called, when the manager method executes. I've tried some methods by it didn't work here is the code example. hint: I'm using pytest as testrunner from unittest import mock # Customer Manager class class ItemsManager(models.Manager): def bulk_update(self, *args, **kwargs): result = super().bulk_update(*args, **kwargs) items_bulk_updated(*args, **kwargs) return result # signals.py file def items_bulk_updated(*args, **kwargs): print("items bulk updated") # test file # Base TestCase Inherits from APITestCase class TestItems(BaseTestCase): @mock.patch("items.signals.items_bulk_updated",autospec=True) def test_bulk_update_items_triggers_signal(self, mock_function): items_qs = Items.objects.all() result = Items.objects.bulk_update(items_qs, ['item_name']) mock_function.assert_called()