Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
codigo de favoritos en django
tengo una laguna mental y no se que estoy haciendo mal, me gustaria saber sus opiniones, estoy intentando crear un sistema de favoritos en django, y llamo al modelo en las template y todo bien, la cuestion es cuando quiero crear el boton para agregar a favoritos, me gustaria verificar si el producto existe dentro de los productos favoritos para poder pintar un boton u otro, dejo el codigo html {%for producto in productos%} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <a href="{{ producto.redireccionar }}"><img src="{{ producto.imagenes.url}}"></a> </div> <!-- img-wrap.// --> <figcaption class="info-wrap"> <div class="fix-height"> <a href="{{ producto.redireccionar }}" class="title">{{producto.nombre_producto}}</a> <!--<div class="price-wrap mt-2"> <span class="price">{{producto.precio}}</span> </div> price-wrap.// --> </div> <a href="{% url 'add_cart' producto.id %}" class="btn btn-block btn-success"> Preguntar Disponibilidad </a> {% if producto.id in favoritos.product.id%} {{favorito.product.nombre_producto}} {%endif%} </figcaption> </figure> </div> <!-- col.// --> {%endfor%} </div><!-- row end.// --> ``` estoy colocando {% if producto.id in favoritos.product.id%} pero no funciona, funciona si le coloco un for pero se pinta mas de un boton, se pinta botones igual a la cantidad de productos en favoritos existentes, alguna sugerencia? espero haberme explicado bien -
djangoFilterBackend not filtering when using __in with ListAPIView and one of the filters is empty
I'm using DjangoFilterBackend to filter some input. The URL is written in javascript. It can be something like this: https://myApp/?se_ID__in=1,2&se_PR_ID__in=3 The thing is that not all the filters are always necesary. If all the filters are used there is no problem at all. But if some of them is not in the URL the filter is not working, it behaves as if this unused filter had a null value instead taking into account all the posible values of that field (skip the filter). I am doing some aggregations at the end of the view, after filtering. But as I said if one the posible filters is not used I get an empty JSON. Here my django files: serializers.py class FiltroSerializer(serializers.Serializer): se_ID = serializers.CharField(required=False, default='all', help_text='Sender ID') se_PR_ID = serializers.CharField(required=False, default='all', help_text='Sender pr ID') rc_ID = serializers.CharField(required=False, default='all', help_text='Receiver ID') cr_PR_ID = serializers.CharField(required=False, default='all', help_text='Receiver pr ID') class Meta: model = Data models.py from django.utils.translation import gettext_lazy as _ class Data(models.Model): shSeCustomerName1 = models.CharField(max_length=300, verbose_name=_('shSeCustomerName1')) shRcCustomerName1 = models.CharField(max_length=300, verbose_name=_('shRcCustomerName1')) se_ID = models.CharField(max_length=300, verbose_name=_('SenderID'), blank=True, null=True) se_DESC = models.CharField(max_length=300, verbose_name=_('SenderDESC'), blank=True, null=True) se_PR_ID = models.CharField(max_length=300, verbose_name=_('SenderProcessID'), blank=True, null=True) se_PR_DESC = models.CharField(max_length=300, verbose_name=_('SenderProcessDESC'), blank=True, null=True) rc_ID = models.CharField(max_length=300, verbose_name=_('ReceiverID'), blank=True, null=True) rc_DESC = … -
Django filters with APIVIew return the complete queryset
I'm trying to use django filter with APIVIew like I saw in this post and I'm geting an unexpected behavior: If the word passed on filter doesn't exists, it return nothing - OK If the word passed on filter exists, it return the complete queryset. I tried to use filters with ModelViewSet before and it works, but I have no success with APIView. I'm using the following code: views: from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from core.models import Profile from core.serializers import ProfileSerializer from django_filters.rest_framework import DjangoFilterBackend class ProfileFilter(DjangoFilterBackend): def filter_queryset(self, request, queryset, view): filter_class = self.get_filter_class(view, queryset) if filter_class: return filter_class(request.query_params, queryset=queryset, request=request).qs return queryset class ListProfileView(APIView): serializer_class = ProfileSerializer filter_fields = ('nome', 'link') queryset = Profile.objects.all() def get(self, request, format=None): queryset = Profile.objects.all() ff = ProfileFilter() filtered_queryset = ff.filter_queryset(request, queryset, self) if filtered_queryset.exists(): serializer = self.serializer_class(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response([], status=status.HTTP_200_OK) def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) model: from django.db import models class Profile(models.Model): nome = models.CharField(max_length=200, null=False, blank=False) link = models.CharField(max_length=200, null=False, blank=False) serializers: from rest_framework.serializers import ModelSerializer from core.models import Profile class ProfileSerializer(ModelSerializer): class Meta: model = … -
Django contact form with class based views
Can anyone explain me how to make send email form on page. So my forms.py class ContactForm(forms.Form): name = forms.CharField(required=True) last_name = forms.CharField() adults = forms.IntegerField() children = forms.IntegerField() email = forms.EmailField(required=True) message = forms.CharField(widget=forms.Textarea) views.py class TourDetailView(DetailView): model = models.Tour template_name = 'tours/tour-detail.html' form_class = forms.ContactForm success_url = 'tours.html' As far as i understand i need to get from request data , but i dont know how to do it. There are a lot of information in function based views, but i didnt get how to do it in class based views. And it would be nice of you to explain where should i put send_mail function. Any help will be appreciated. -
RelatedObjectDoesNotExist: User has no customer
I am following a Django youtube E-comerce tutorial by Dennis Ivy. I follow the tutorial line by line. from the initial i use to run the program and view all the output but alone the way i start getting this error message "RelatedObjectDoesNotExist: User has no customer". Am confuse because i keep repeating the video to see where i was wrong but could not trace it. please what is the solution? I realise the last time i tried, it open on its own using 'internet explorer' it display. when i open in 'chrome', it show the same erro. but when i deleted a customer from database it start showing the same erro again in 'internet explorer'. I dont want to give up on the tutorial cos i need it. please someone should assist me. Thanks from multiprocessing import context from django.shortcuts import render from .models import * from django.contrib.auth.models import User from django.http import JsonResponse import json # Create your views here. def store(request): if request.user.is_authenticated: customer = request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete =False) items =order.orderitem_set.all() cartItems=order.get_cart_items else: items=[] order = {'get_cart_total':0, 'get_cart_items':0} cartItems=order['get_cart_items'] products = Product.objects.all() context = { 'products':products, 'cartItems':cartItems, } return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: … -
Calculate Input Fields while user is filling data in form - Django Model Form
I have a user form through which I can save data to the database. I want certain fields to be auto calculated while I am filling the the form. For e.g. Net Weight = Gross Weight - Tier Weight and stuff like that. I also want to add RADIO BUTTONS for fields like LOADING, UNLOADING, DEDUCTION, etc. where values will be calculated when user selects one of the option given. I am also attaching a design of the type of form I want, I just don't know how to make that using Django.enter image description here I am using Django Model Form. Kindly Guide me. Models.py class PaddyPurchase(models.Model): ref_no = models.IntegerField(primary_key='true') token_no = models.CharField(max_length=20, unique='true') agent_name = models.CharField(max_length=20) trip_no = models.IntegerField() date = models.DateField() vehicle_no = models.CharField(max_length=10) bora = models.IntegerField() katta = models.IntegerField() plastic = models.IntegerField() farmer_name = models.CharField(max_length=30) farmer_address = models.CharField(max_length=40) farm_mob = models.CharField(max_length=10) gross_weight = models.IntegerField() tier_weight = models.IntegerField() net_weight = models.IntegerField() bora_weight = models.IntegerField() suddh_weight = models.FloatField() loading = models.IntegerField() unloading = models.IntegerField() unloading_point = models.CharField(max_length=20) dharamkanta_man = models.CharField(max_length=10) rate = models.IntegerField() bardana = models.CharField(max_length=7) gross_total = models.IntegerField() deduction = models.IntegerField() kanta = models.IntegerField() hemali = models.IntegerField() our_vehicle_rent = models.IntegerField() agent_commission = models.IntegerField() other_amt = models.IntegerField() other_remarks … -
How to send an image from React-Native app to the Django server using Expo ImagePicker?
const [image, setImage] = useState(null); const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result.uri); if (!result.cancelled) { setImage(result); } }; I study React-Native and Django and I know about FormData, but I don't understand how put into my code. -
Conditional field in Django (Admin)
I've been using the Django ORM to model my database/objects, and Django Admin to render my admin pages (including nested admin pages). I've been meaning to implement the following, but without success: I have a 'project' model. Then I have 'file' model, with a ForeignKey relationship to 'project'. The file model has a 'filetype' field. SUPPORTED_FILE_TYPES = ( ('csv', 'csv'), ('xls', 'xls'), ) class Project(models.Model): name = models.CharField(max_length=200) class File(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) filetype = models.CharField( max_length=20, choices=SUPPORTED_FILE_TYPES, default=SUPPORTED_FILE_TYPES[0], ) Then in Django admin, I just nestedAdmin to make sure I can add files right from the project view. class FileInline(nested_admin.NestedStackedInline): model = File extra = 0 inlines = [ColumnInline] class ProjectAdmin(nested_admin.NestedModelAdmin): inlines = [FileInline] formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } Now a 'file' can be either a excel or a csv file. Each has different attributes (e.g. an excel file has 'sheets', whereas a csv has a 'delimiter' and 'thousand_seperator' fields). I want that, when I add a file and select which filetype it is, to have form fields appear that belong to the filetype I selected. I've been struggling with how to implement this. Several options crossed my mind: Using GenericForeignKeys, but I didn't manage to … -
TemplateDoesNotExist at / new.html
i'm trying to connect the html file with my views.py although everything seem correct but still after running the server it shows TemplateDoesNotExist kindly check my directories order and code i will appreciate your assistance. This is the folder order i couldnt paste it in image i dont know why views.url from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'new.html') -
When i create a user from admin page , i can't login
In django i am building a user db but i have a problem with this . When i try python3 manage.py createsuperuser this works fine but when i try creating user with admin page i can create user but user's password is not hashing and in login template i can't login . Django version 4.0 login views.py : def loginacc(request): if request.method == "POST": tcNo = request.POST.get("tcNo") password = request.POST.get("password") user = authenticate(request, tcNo=tcNo, password=password) if user is not None: login(request, user) return render(request, "home/home.html") else: return render(request, "accounts/accounts.html", {"error": "Name or password is wrong . "}) return render(request, 'accounts/accounts.html') student models.py : class Student(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) tcNo = models.IntegerField(unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) nickname = models.CharField(max_length=255, blank=True, null=True) objects = StudentBaseUserManager() USERNAME_FIELD = 'tcNo' REQUIRED_FIELDS = ['first_name', 'last_name', 'email', "nickname"] def save(self, *args, **kwargs): self.nickname = self.first_name + "-" + self.last_name return super(Student, self).save(*args, **kwargs) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def __str__(self): return self.email class StudentBaseUserManager(BaseUserManager): def create_user(self, tcNo, first_name, nickname, last_name, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, tcNo=tcNo, ) … -
Can i use haproxy for hosting django channels ASGI application instead of daphne?
I was curious to know can i host a ASGI django channels applications with haproxy instead of daphne as i heared it had some security issues. -
Djoser "Password Changed Confirmation" Email Not Sending
Good day, I have successfully overwriting 3 of the default Djoser templates and can receive those emails, but I can't get the "Password Changed Confirmation" email to send. According to djoser/conf.py, djoser/email.py, and djoser/templates/email it appears I am doing everything correctly. But it's not obvious why this one isn't sending as there are no errors being raised. The project directory has these relevant files and paths: project - core - email.py - settings.py - templates - email - activation.html # works - confirmation.html # works - password_changed_confirmation.html # does not work - password_reset.html # works settings.py was set as per the Djoser docs. DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', # I set this to True as per the docs: 'PASSWORD_CHANGED_EMAIL_CONFIRMATION:': True, 'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': True, 'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True, 'SERIALIZERS': { 'user_create': 'users.serializers.UserCreateSerializer', 'user': 'users.serializers.UserCreateSerializer', }, 'EMAIL': { # These 3 templates send: 'activation': 'core.email.ActivationEmail', 'confirmation': 'core.email.ConfirmationEmail', 'password_reset': 'core.email.PasswordResetEmail', # This one does not: 'password_changed_confirmation': 'core.email.PasswordChangedConfirmationEmail', } } In email.py I create my custom class to reference the template. The print statements don't even fire so I don't think this is even getting called. from djoser import email # Override the default Djoser … -
How do I use the ability to add another ingredient that is available in admin?
I have a recipe database web app that allows users to add recipes to it. At the moment, it only allows users to enter up to three ingredients. In the admin page, there is an option to add another ingredient. Am I able to use this to allow users to choose to add another? Also, why is delete showing up? And is there a way to remove it? Thanks for any advice you can offer. # models.py class Ingredient(models.Model): #TODO allergies, more data on ingredient, looking towards APIs now name = models.CharField(max_length=20, unique=True) quantity = models.PositiveIntegerField() unit = models.CharField(max_length=50, validators=[validate_unit_of_measure], blank=True, null=True) unit_price = models.PositiveIntegerField() recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="ingredients") def __str__(self): return self.name # forms.py class IngredientForm(forms.ModelForm): class Meta: model = Ingredient fields = ['name', 'quantity', 'unit', 'unit_price',] exclude = ('recipe',) -
How do I use a select2 multiple select in a django crispy form?
I have an existing crispy form. I want to use django-select2 to replace an existing multi-select with a Select2 field with a maximum of two selections. I know from this post that I need to include 'data-maximum-selection-length' as a widget attribute. Here is the field code I am adding: forms.ModelMultipleChoiceField( required=True, queryset=MyModel.objects.all(), widget=s2forms.Select2MultipleWidget(attrs={'data-maximum-selection-length': 2})) I have included {{ form.media.css }} in the head of my template and {{ form.media.js }} before the tag. Edit: I have path('select2/', include('django_select2.urls')), included on my urls.py. The field is not formatted to appear as a select2 dropdown, it looks like a standard multiselect field. This is what I'm hoping to obtain: ... this is how it looks: I'd be appreciative of any ideas! References: django-select2 docs django ModelMultipleChoiceField docs django crispy forms docs -
Original exception text was: 'Category' object has no attribute 'answer'
Please check the error.Much appreciate if you can help: error: Got AttributeError when attempting to get a value for field answer on serializer CategorySerializer. The serializer field might be named incorrectly and not match any attribute or key on the Category instance. Original exception text was: 'Category' object has no attribute 'answer'. model.py: class Question(models.Model): question_text = models.CharField(max_length=200) question_type = models.CharField(max_length=200) def __str__(self): return f'{self.id}-{self.question_text}' class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE,related_name='questions_answer') answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text class Category(models.Model): category_text = models.CharField(max_length=200) def __str__(self): return self.category_text serializer.py: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class AnswerSerializer(serializers.ModelSerializer): ques=QuestionSerializer(source='questions',read_only=True) class Meta: model = Answer fields = '__all__' class CategorySerializer(serializers.ModelSerializer): # question=QuestionSerializer(read_only=True,source='question.question') answer=AnswerSerializer(many=True) class Meta: model = Category fields = ['id','category_text','answer'] def create(self, validated_data): answer_data = validated_data.pop('answer') category = Category.objects.create(**validated_data) for answer_data in answer_data: Answer.objects.create(**answer_data) return category views.py class QestionAnswer(generics.CreateAPIView): serializer_class = CategorySerializer def perform_create(self,serializer): serializer.save() -
django.db.migrations.exceptions.InconsistentMigrationHistory error
In my django project I am getting always this error after makemigrations and migrate (both of them).How can I fix that? raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration auth.0001_initial is applied before its dependency contenttypes.0001_initial on database 'default'. -
Problem with passing images from Django REST Framework to React
I'm trying to display an image for a product category in React. Added the following lines to the settings: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Then set up URLs to serve media files during development: router = routers.SimpleRouter() # some routes here urlpatterns = [ path('', include(router.urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The category model looks like this: class Category(models.Model): title = models.CharField(max_length=100, null=False) slug = models.SlugField(max_length=100, unique=True) poster = models.ImageField(upload_to="categories/") Serializer for it: class CategorySerializer(ModelSerializer): class Meta: model = Category fields = '__all__' On the home page in React I display a list of CategoryCards: import React, {useEffect} from "react"; import * as API from "../apis/API"; import CategoryCard from "./CategoryCard"; import Loader from "./Loader/Loader"; export default function Home() { const [categories, setCategories] = React.useState([]); const [loading, setLoading] = React.useState(true); useEffect(() => { API.list('categories') .then(p => setCategories(p)) .then(_ => setLoading(false)); }, []); return ( <div> <label>Popular categories</label> {loading && <Loader/>} {categories.length ? ( <div> {categories.map(c => <CategoryCard key={c.id} product={c}/>)} </div> ) : ( loading ? null : <p>No categories</p> )} </div> ); } And React component to display category title and image: import React from 'react'; import {A} from 'hookrouter'; export default function CategoryCard({product}) { return ( … -
Django Queryset datetime filtering
I have a set of study sessions that have date and time details and I was wondering how I could go about filtering to just show users upcoming study sessions that are occurring either today or after today in my html file? Here is the model for the session. class Appointment(models.Model): date = models.DateTimeField() -
Languages to learn to develop a website and mobile app
Is it possible for me to use the same set of programming languages to create both a website and a mobile app ( IOS and Android ) and if so, what are they? Some of the features that I would like this project to have are as follows: The website and application can store and share data between the website / IOS and Android apps There are some animations (for example an interactive book that can open, close and flip pages) Has a store feature If I can not use the same languages for the entire project what languages would I need to learn to complete this project. If possible please provide me with some resources that I can reference while doing this project. -
NoReverseMatch at /info/1
I've been trying to fix this error all day, but nothing. NoReverseMatch at /info/1 Reverse for 'like_book' with arguments '(None,)' not found. 1 pattern(s) tried: ['like/(?P[0-9]+)\Z'] views.py def LikeView(request, pk): book = get_object_or_404(BookModel, id=request.POST.get('book_id')) book.likes.add(request.user) return redirect('more_info', pk=pk) html <form action="{% url 'like_book' book.pk %}" method='POST'> {% csrf_token %} <button type="submit" name="book_id" value="{{ book.id }}" class="btn btn-danger btn-sm">Like</button> </form> urls.py urlpatterns = [ path('', index, name='index'), path('allbook', AllBookView.as_view(), name='allbook'), path('addbook', AddBookView.as_view(), name='addbook'), path('register', RegisterView.as_view(), name='reg'), path('login', LoginView.as_view(), name='login'), path('logout', LogoutView.as_view(), name='logout'), path('info/<int:id>', MoreInfoView.as_view(), name='more_info'), path('profile', profileview, name='profile'), path('password-change', ChangePasswordView.as_view(), name='change_pass'), path('like/<int:pk>', LikeView, name='like_book') ] -
Django: session_key is an empty string
I'm using an analytics platform to track user interactions, and want to associate events by session id so I can track individual users' behaviors. So, I am using request.session.session_key as the user id I'm passing the event logging function. I don't use the session for anything else, and am not saving or modifying variables. I did set up middleware correctly, so far so good. However, when I check the analytics platform, I see that the id is often (but not always) blank. I looked up some answers, and thought I could solve this by running request.session.save() before accessing the session_key. However, I can't run .save() because I'm not actually modifying any session variables, so Django throws an error. What do I need to do to make sure the session always has an id? Some code from my very simple get view: def get(self, req: HttpRequest): form = self.form_class(None) # this is where I tried req.session.save() mixpanel.track( req.session.session_key, "Form Page Displayed", {"path": req.path, "route": req.method}, ) return render(req, self.template_name, {"form": form}) -
Add multiple people to one form dynamically. Python and Django
I want to make a form for a case entry. This form should be able to take one or more people associated with it dynamically. Basically, start with one person, and if another person is needed to click a button to say "add a person". This should populate all the fields for a person to be associated with the same case entry without submitting until every person that needs to be entered is entered. I know how to do this with just one person but am at a complete loss for adding multiple people dynamically to the same form. So I have no code to show because I have no idea how to implement this or start. -
Django PWA extention, Icons for pwa website not showing up in F12 menu by manifest in chrome
I am making a PWA website on top of django and the website icons ar not showing up when in the devoloper menu in Chrome as seen in the picture. Manifest in Chrome This is the code i use for the manifest. Manifest code There are no error in the web-console or webserver the images all have a good connection code 200. -
How can I access the created instance by a serializer in a view?
So I have a modelserializer that creates a new model instance in case of post requests to an endpoint. How can I grab the newly created instance in the view for further processing? (I need the id of the new instance for a related model). # serializers.py class OfferList(APIView): """ List all Offers or create a new Offer related to the authenticated user """ def get(self, request): offers = Offer.objects.filter(company__userprofile__user=request.user) serializer = OfferSerializer(offers, many=True) return Response(serializer.data) def post(self, request): serializer = OfferSerializer(data=request.data) if serializer.is_valid(): # Get the related company instance company = get_object_or_404(Company, userprofile__user=request.user) # Pass the related instance to the serializer instance to save the new Offer instance serializer.save(company=company) # Create Payment instances - returns a dict payments = create_payments( serializer.data.get('start_salary'), serializer.data.get('months'), serializer.data.get('start_date'), serializer.data.get('interest_type'), serializer.data.get('interest_interval'), serializer.data.get('interest_raise') ) # Loop the dict and generate instances for key, value in payments.items(): Payment.objects.create( offer= , # how to access the id of the created instance by the serializer above? month=key, amount=value ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # models.py class Payment(models.Model): """ A table to store all payments derived from an offer. """ # Each monthly payment relates to an offer offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.DateField() amount = models.PositiveIntegerField() -
Run Dash plotly after click button
let's say I have a dashboard that contains many information and plots. I have a dropdown list that generates Plots and another dropdown list named Wells. I have a plot that I created with dash and it works very fine but with a fixed input! and also dash plots this plot at starting the page :( ! My question is how to prevent dash to plot directly and execute after I press a button that takes the selected item from the Wells list and callback the function and replots. so this is my HTML page : <div class="col-md-3" > <select class="custom-select mb-4" name="Wells" hx-get="{% url 'addplotly' %}" hx-trigger="change" hx-target="#plotly_production" hx-include="[name='Toggle']"> <option selected>Select Well</option> {% for well in TFTWells %} <option value="{{well.WellID}}">{{well.WellID}}</option> {% endfor %} </select> </div> and this is my dash script: app = DjangoDash('Pressure_guage', external_stylesheets=external_stylesheets) app.layout = html.Div( id="dark-light-theme", children=[ html.Div([html.H3("Pressure Control", style={"textAlign": "center"}),], className="row"), html.Div([ html.Div( daq.Gauge( #size=150, color={"gradient":True,"ranges":{"green":[0,the_maxCSG/3],"yellow":[the_maxCSG/3,the_maxCSG*6/7],"red":[the_maxCSG*6/7,the_maxCSG]}}, id="my-daq-gauge1", min=0, max=the_maxCSG, value=PRES_CSG, label="CSG "+str(PRES_CSG)+" bar",style={'display': 'inline-block'} ), className="three columns", ), html.Div( daq.Gauge( #size=150, color={"gradient":True,"ranges":{"green":[0,the_max/3],"yellow":[the_max/3,the_max*6/7],"red":[the_max*6/7,the_max]}}, id="my-daq-gauge2", min=0, max=the_max, value=PRES_TBG, label="TBG "+str(PRES_TBG)+" bar",style={'display': 'inline-block'} ), className="three columns", ), html.Div( daq.Gauge( #size=150, color={"gradient":True,"ranges":{"green":[0,the_maxAVD/3],"yellow":[the_maxAVD/3,the_maxAVD*6/7],"red":[the_maxAVD*6/7,the_maxAVD]}}, id="my-daq-gauge3", min=0, max=the_maxAVD, value=PRES_AVD, label="AVD",style={'display': 'inline-block'} ), className="three columns", ), html.Div( daq.Gauge( color={"gradient":True,"ranges":{"green":[0,the_maxGL/3],"yellow":[the_maxGL/3,the_maxGL*6/7],"red":[the_maxGL*6/7,the_maxGL]}}, id="my-daq-gauge4", min=0, max=the_maxGL, value=RESEAU_GL, …