Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not updating static css file design in browser when I run collect static command
I wrote css file and then save it all changes happen and when I run collect static command and then I again change css files no changes displayed on browser nothing happen at all. -
Django is deleting my image when i am saving the object app in admin pannel
This is the code that i have used to delete image when i will change the image : def auto_delete_file_on_change(sender, instance, **kwargs): if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).file except sender.DoesNotExist: return False new_file = instance.file if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path)` -
Django invalid password format for Modeform PasswordInput
I have seen a lot of SO answers and official docs for this issue but find no solution yet. forms.py from django import forms from .models import * from django.contrib.auth.models import User class Userform(forms.ModelForm): username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'joeschmoe', 'name': 'username'})) email = forms.CharField(widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'joeschmoe@xyz.com', 'name': 'email'})) password = forms.CharField(widget=forms.PasswordInput( attrs={'name': 'password'})) repassword = forms.CharField(widget=forms.PasswordInput( attrs={'name': 'repassword'})) class Meta: model = User fields = ['username', 'email', 'password', 'repassword'] View.py def register(request): if request.method == 'POST': form = Userform(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] repassword = form.cleaned_data['repassword'] form.save() return render(request, 'base/index.html') else: form = Userform() return render(request, 'base/register.html', {'form': form}) This form is successfully registering but showing Invalid password format or unknown hashing algorithm. Any help will be appreciated -
How to edit the design of admin user permission template in django?
I simply want to take out group editing section from the user permission from the screen. how can i eliminate this part?enter image description here -
Unable to post data using axios to django url
First of all, I am fetching the data from an API and rendering the products. After that, if a user clicks the Add to cart button, I want to post the id of that product to a Django URL, but it's giving me an error saying FORBIDDEN. Here is the image of the error Here is the code import React, { useEffect, useState } from "react"; import "./CSS/Home.css"; import axios from "axios"; function Home() { const [ApiData, setApiData] = useState([]); useEffect(() => { async function getData() { const data = await axios.get("http://127.0.0.1:8000/?format=json"); console.log(data.data); setApiData(data.data.Product); return data; } getData(); }, []); function buttonClicked(id) { axios.post("http://127.0.0.1:8000/update_item/", { id: `${id}` } return ( <> <div className="container"> {ApiData.map((obj, index) => { let x; for (x in obj) { return ( <div className="card"> <div className="top-half"> <img className="store-img" src={obj.image} alt="shoes-images" /> </div> <div className="store-info"> <span className="txt-style">{obj.name}</span> <span className="txt-style">${obj.price}</span> </div> <div className="buttons"> <button className="btn-style" style={{}}> View </button> <button className="btn-style" onClick={() => buttonClicked(obj.id)} > Add to Cart </button> </div> </div> ); } })} </div> </> ); } export default Home; -
How to allow users to submit a get request to a class View and order item?
<form action=""> Sort By: <select name="ordering"> <option value="price">Price:Highest to Lowest</option> <option value="-price">Price:Lowest to Highest</option> </select> <button type="submit">submit</button> <form> trying to submit these values in a get request. Tried doing a get_ordering function on a class List View: class GarageListView(ListView): model = Vehicles template_name = 'garage/garage.html' context_object_name = 'cars' ordering = ['-price'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = VehicleFilter( self.request.GET, queryset=self.get_queryset()) return context def get_ordering(self): self.ordering = self.request.GET.get('ordering','-price') return self.ordering When users select and submit any sort option, it should refresh the page and sort by value -
Django use StrIndex to get the last instance of a character for an annotation
I have a model with a key that's value is a file path, ie /src/code/foo. I need the file name so I want to get the sub string of foo for my annotation value. The logical way I was aiming to go about it was to get the index of the last / character. I was trying to do this via StrIndex & Substr but StrIndex only gives me the first index. Is there a way I can get the last index instead? MyModel.objects.all().annotate( # this would give me `src/code/foo` but I want just `foo` name=Cast(Substr("file_path", StrIndex("file_path", V("/"))), TextField()) ) -
How do I use formset data as initial data in my forms? Error is ' The inline value did not match the parent instance.'
I have a formset that I use to collect some data. I also want to use that same data as the initial data to a different formset. In order to do this, I have a form that looks like... def __init__(self, *args, **kwargs,): dropdown = kwargs.pop('dropdown', None) super(TeamFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(team_pk=dropdown) After a bunch of searching and massaging....I've gotten this to work exactly how I want. The challenge I'm having now is when I'm loading this form, I am getting an error that says The inline value did not match the parent instance. I've done some research on the querysets and formsets and I understand django knows how this data was created originally, but I am trying to essentially use the values as a starting point for this form. I have seen that get_initial might be available for formsets. Is there some other way I should be getting the data rather than the way I am going about it above? The data is dynamic, and since I've already captured it in another part of the system, I can't see why I shouldn't be able to use the values at a minimum as a starting point for a different … -
Django: best way to produce a 70+ page form
I'm trying to create a quiz web app on Django, where each quiz has 75 multi-choice questions, and each question is displayed on its own page (see screenshot for an example of what one question page would look like). The user should be able to navigate backwards and forwards between each 'page' of questions, so answers for each question must persist once they have been entered. Each question will have four radio button answer choices. At the end of the quiz, the user will submit answers and they will be stored in a database. What is the best way to go about implementing this in Django? I have done some research and found two options, although I'm not sure which is best in terms of efficiency since each quiz is going to be quite large and will require a lot of individual pages. form wizard: https://django-formtools.readthedocs.io/en/latest/wizard.html JS steps: https://www.w3schools.com/howto/howto_js_form_steps.asp? Open to other methods, advice greatly appreciated. -
null value in column "x" violates not-null constraint
I making a feature where one user can follow another. I had this working momentarily but then it broke again (I got some assistance from a mentor). I am trying to trouble shoot it myself but can't figure out what is happening even though the error is pretty clear what is going wrong, I can't fix it. Error: null value in column "followed_id" violates not-null constraint DETAIL: Failing row contains (46, null, null). The model is: class UserConnections(models.Model): follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) The serializer is: class UserConnectionListSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = ['follower','followed'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' depth = 2 My view is: class UserConnectionsViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): if request.method == "POST": data = {'follower': request.DATA.get('follower_id'), 'followed': request.DATA.get('followed_id')} serializer = UserConnectionListSerializer(data=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) FWIW I am passing the Ids to the view view an AJAX call and it is definitely passing through two integers. Thanks for the help! -
Django query for model with a single DateField used for tracking state changes
I have searched all over StackOverflow, but can't seem to find anything like this. Assuming we have the following model (purposely simplified): class X(models.Model): related_object = models.ForeignKey(Y) start_date = models.DateField(unique=True) is_rented = models.BooleanField() Where model X is tracking state changes of an instance of model Y. It could be tracking something like the state of cars at a car rental agency that may be rented out. A new instance of the model is created each time the state of each car changes. The resulting objects might look something like this: {"id" : 1, "related_object" : 2, "start_date" : "2021-03-03", "is_rented" : False}, {"id" : 2, "related_object" : 2, "start_date" : "2021-03-06", "is_rented" : False}, {"id" : 3, "related_object" : 2, "start_date" : "2021-03-10", "is_rented" : True}, {"id" : 4, "related_object" : 2, "start_date" : "2021-03-15", "is_rented" : False}, {"id" : 5, "related_object" : 2, "start_date" : "2021-03-16", "is_rented" : True}, {"id" : 6, "related_object" : 4, "start_date" : "2021-03-16", "is_rented" : False}, {"id" : 7, "related_object" : 2, "start_date" : "2021-03-17", "is_rented" : False}, {"id" : 8, "related_object" : 4, "start_date" : "2021-03-22", "is_rented" : True}, I want to be able to perform the following queries: For a provided date, … -
Django get file url
I want to show the URL, filename and size of the uploaded file on my site. I tried object.file.url but it didn't work. models.py: file = models.FileField(upload_to="media/",null=True,blank=True, verbose_name="Files", validators=[ FileExtensionValidator(allowed_extensions=['pdf', 'docx', 'doc', 'xlsx', 'xls', 'png','jpg','jpeg'])]) And tried this but not working: in models.py: @property def file_url(self): if self.file and hasattr(self.file, 'url'): return self.file.url -
Docker-Kubernets can't find manage.py
I built an API in Django and I used docker-compose to orchestrate redis and celery services. Now, I would like to move the API to a Kubernetes cluster (AKS). However, I get the error python can't find manage.py when I run it into the cluster. I used Kompose tool to write the kubernets manifest.yaml. This is my Dockerfile, docker-compose.yml and kubernets.yaml files # docker-compose.yml version: '3' services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python3 ./manage.py makemigrations && python3 ./manage.py migrate && python3 ./manage.py runserver 0.0.0.0:8000" The Dockerfile # Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app COPY ./app /app WORKDIR /app And the kubernets manifest apiVersion: v1 items: - apiVersion: v1 kind: Service metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml -o kb_manifests.yaml kompose.version: 1.22.0 (955b78124) creationTimestamp: null labels: io.kompose.service: app name: app spec: ports: - name: "8000" port: 8000 targetPort: 8000 selector: io.kompose.service: app status: loadBalancer: {} - apiVersion: apps/v1 kind: Deployment metadata: annotations: kompose.cmd: kompose convert -f docker-compose.yml -o kb_manifests.yaml kompose.version: 1.22.0 (955b78124) creationTimestamp: null labels: io.kompose.service: app name: app spec: replicas: 1 selector: matchLabels: io.kompose.service: app strategy: type: Recreate template: metadata: … -
MultiValueDIctKeyError when I try to create a new listing
I am attempting to create an auction listing with categories that are linked to it. The listing is its own model while the category is a model which i foreign key to as shown here class Categories(models.Model): category = models.CharField(max_length=32) def __str__(self): return self.category class Listings(models.Model): owner = models.CharField(max_length = 20) title = models.CharField(max_length = 20) description = models.CharField(max_length = 200, null = True) categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name="type") image = models.URLField(max_length = 1000, null = True) bid = models.PositiveIntegerField() the problem that I run into is when i try to save the new listing in my views.py @login_required(login_url= "login") def createlisting(request): if request.method == "POST": listing = Listings( title = request.POST['title'], description = request.POST['description'], image = request.POST['image'], bid = request.POST['startingbid'], owner = request.user.username, categories=Categories.objects.get(category=request.POST["category"]) ) listing.save() return HttpResponseRedirect(reverse('index')) return render(request, "auctions/createlisting.html", { 'categories': Categories.objects.all() }) When i try to save the listing I get a MultiValueDictKeyError and this is the traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create Django Version: 2.2.12 Python Version: 3.8.5 Installed Applications: ['auctions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/lib/python3/dist-packages/django/utils/datastructures.py" in getitem 78. list_ = super().getitem(key) During handling of the above exception ('category'), another … -
How do I solve 'Model' object has no attribute 'object' for UpdateView for formset handling?
I am currently trying to get past numerous problems I've encountered with formset handling. Here is my latest code...In other issues it would seem that there might be an issue with formset and form_invalid(). I am trying to simply edit formset data that I have saved from a CreateView. It seems as if the data is presenting fine in the view after I save it from CreateView, but then I am not able to use this data or save it without changing anything. My View.... class UpdateTeamView(LoginRequiredMixin,UpdateView): model = Team form_class = UpdateTeamForm template_name = 'update_team.html' def get_context_data(self, **kwargs): context = super(TeamView, self).get_context_data(**kwargs) if self.request.POST: context['player_form'] = PlayerFormSet(self.request.POST) else: context['player_form'] = PlayerFormSet() return context def get_form_kwargs(self): kwargs = super(UpdateTeamView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_object(self, queryset=None): return get_object_or_404(Team, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown is not None: if Team.objects.all().distinct(): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) else: raise Http404 else: messages.add_message(self.request, messages.INFO, 'Team is required.') return HttpResponseRedirect(reverse('Company:update_team_by_name')) def form_valid(self, form): instance = form.save() return super(UpdateTeamView, self).form_valid(form) def form_invalid(self, form): return self.render_to_response( self.get_context_data(form=form, player_form=player_form, )) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if "cancel" in request.POST: return HttpResponseRedirect(reverse('Company:company_main_menu')) else: team_form = … -
Annotating with the count of a subquery filtering by jsonb fields in Django
I have a single model with a jsonb field. There is a value inside this jsonb field that can be shared amongst other rows. I am trying to get the count of a subquery while filtering by this jsonb field. Some pseudo code of what I have been attempting borrowing examples from this post. alpha_qs = MyModel.objects.filter(class_id="ALPHA") # unnest jsonb field so I can leverage it via OuterRef alpha_qs = alpha_qs.annotate(nested_value_id=KeyTextTransform("nested_value_id", "a_jsonb_field")) related_beta_subquery = MyModel.objects.filter(class_id="BETA", a_jsonb_field__nested_value_id=OuterRef("nested_value_id")) related_beta_subquery_count = related_beta_subquery.annotate(count=Count("*")).values("count") alpha_qs = alpha_qs.annotate(related_beta_count=Subquery(related_beta_subquery)) Using this example data I would expect the top instance to have a related_beta_count of 2 because there are two associated betas with the same nested_value_id. { "class_id": "ALPHA", "a_jsonb_field": { "nested_value_id": 'abc' } } { "class_id": "BETA", "a_jsonb_field": { "nested_value_id": 'abc' } } { "class_id": "BETA", "a_jsonb_field": { "nested_value_id": 'abc' } } { "class_id": "BETA", "a_jsonb_field": { "nested_value_id": 'zyz' } } I've been getting an error below but haven't been able to resolve it. ProgrammingError: operator does not exist: jsonb = text LINE 1: ...d AND (U0."a_jsonb_field" -> 'nested_value_id') = ("my_model... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. -
creating a hyperlink that collects data based on the id of the object Django
I am making an application where when you open the file it comes up with a catalogue of fruit and what needs to happen is when you click on 'more details' it opens the data stored in teh create_fruits in the views.py file relative to that fruit based on its ID that I have assigned. HOwever I am struggling to create a hyperlink that will allow me to do this here is the code: (this is for views.py) ef home(request): return HttpResponse('Home Page') def fruit_catalogue(request): page_data = {'fruit_list': create_fruits()} return render(request, 'templates/index.html', page_data) def create_fruits(): catalogue_items = [] catalogue_items.append(Fruit(1, 'Pink Lady Apple', '$4.00', 'Rosaceae', 'Australian Sourced', 'Pink Lady® apples were developed by a man named John Cripps of Western Australia’s Department of Agriculture. They are the result of a cross between Lady Williams and Golden Delicious apples.')) catalogue_items.append(Fruit(2, 'Banana Cavendish', '$3.20', 'AAA', 'Chinese sourced', 'Cavendish bananas are the fruits of one of a number of banana cultivars belonging to the Cavendish subgroup of the AAA banana cultivar group.')) catalogue_items.append(Fruit(3, 'Pomegranate', '$14.00', 'Lythraceae', 'Indian Sourced', 'The name pomegranate derives from medieval Latin pōmum meaning apple and grānātum meaning seeded')) catalogue_items.append(Fruit(4, 'Dragon Fruit (white)', '$12.30', 'Cactaceae', 'Indonesian Sourced', 'White dragon fruit contains … -
Export/Download csv from React frontend from Django
I want to download a csv file from React frontend. The data is coming from Django. I have the views.py updated but i don't know how to send this data on the React side I am using Axios for Get requests but can't seem to figure out what to add to React side for it to fetch this data and then download it. Please advise. views.py from django.http import HttpResponse from rest_framework import viewsets, generics from rest_framework.decorators import api_view from .models import ExportData import csv @api_view(['GET']) def export_csv(request): response = HttpResponse(content_type='text/csv') csv_headers = ['Column 1','Column 2','Column 3'] writer = csv.writer(response) writer.writerow(csv_headers) for row in ExportData.Objects.all().values_list('column_1','column_2','column_3'): writer.writerow(row) response['Content-Disposition'] = 'attachment; filename="Test.csv"' return response -
Django Combine Window Functions with Standard annotations
I have a Django Model I'm trying to implement a Windows Function and a standard Annotation on. Ideally I want to return a ranking of rows and get an aggregation of another column in the same queryset. As an example mapped below: queryset = ProductData.objects.values('date','sku) .annotate(row_number=ExpressionWrapper(Window(expression=RowNumber(), partition_by=[F('sku')], order_by=F('date').asc()), output_field=FloatField())) .annotate(units_sold=ExpressionWrapper(Sum(F('units_sold')), output_field=FloatField())) .order_by('date','sku') The resulting posted query is: SELECT product_data.SKU, DATE_FORMAT(product_data.date, '%Y-%m-%d') AS date, ROW_NUMBER() OVER (PARTITION BY product_data.SKU ORDER BY product_data.DATE ASC) AS row_number, SUM(product_data.Units_Sold) AS Units_Sold FROM product_data GROUP BY product_data.SKU, DATE_FORMAT(product_data.date, '%Y-%m-%d'), ROW_NUMBER() OVER (PARTITION BY product_data.SKU ORDER BY product_data.DATE ASC) ORDER BY date ASC, product_data.SKU ASC ** When running this method I get the following error: Error Code: 3593. You cannot use the window function 'row_number' in this context.' The query needs to be: SELECT product_data.SKU, DATE_FORMAT(product_data.date, '%Y-%m-%d') AS date, ROW_NUMBER() OVER (PARTITION BY product_data.SKU ORDER BY product_data.DATE ASC) AS row_number, SUM(product_data.Units_Sold) AS Units_Sold FROM product_data GROUP BY product_data.SKU, DATE_FORMAT(product_data.date, '%Y-%m-%d') ORDER BY date ASC, product_data.SKU ASC The problem is that the first annotation defined by the Windows Function creates a new "value Column". So in django by defualt when I call the second annotation it performs a group by on all the Value fields. In django … -
How to create a "sort by" dropdown input with django?
Trying build a webapp using django but having a challenge finding how to create a dropdown input for users to sort items on the page. Have the filter form: <form> {{filter.form|crispy}} <button type="submit">submit</button> </form> is there something similar like? <form> {{sort.form}} </form> -
What is the proper way to create draft page programatically in the Wagtail?
Just to save page I do: parent_page = Page.objects.get(title="parent") page = Page(title="child", owner=request.user) parent_page.add_child(instance=page) page.save() # not sure if this required What if I need to save Draft Page? This code seems to be working but I am not sure if it's correct: parent_page = Page.objects.get(title="parent") page = Page(title="child", live=False, owner=request.user) parent_page.add_child(instance=page) page.save_revision() page.save() Do I need call page.save() after page.save_revision()? With this code everything works ok in my case but I have noticed that PageRevision.user_id is empty. How it can affect my code in future? From wagtail code I see that I can save revision with user parameter: page.save_revision(user=request.user, log_action=True) I have saved revisions without user and don't see any side effect. How this field is critical? Do I need to fill user_id field for all existing revisions? P.S. looks like it would be better to wrap this code in transaction because when it fails due to validation error manage.py fixtree show me error Incorrect numchild value. -
Display defferent usernames in django EmailMultiAlternatives template
How to show different username in template if i send emai via EmailMultiAlternatives I have several emails with django Here is my code: models.py: class User(AbstractUser): category = models.ForeignKey('news.Category', on_delete=models.CASCADE, related_name='subscribers', null=True) class Category(models.Model): category = models.CharField(unique=True, max_length=255) class Post(models.Model): NEWS = 'NEWS' POST = 'POST' type_choice = [(NEWS, 'Nowost'), (POST, 'Post')] author = models.ForeignKey('accounts.Author', on_delete=models.CASCADE) date_of_creation = models.DateTimeField(auto_now_add=True) text_content = models.TextField() rating = models.IntegerField(default=0) header = models.CharField(max_length=255) category = models.ManyToManyField(Category, through='PostCategory') type_of_content = models.CharField(max_length=4, choices=type_choice, default=NEWS) signals.py @receiver(m2m_changed, sender=Post.category.through) def notify_subscribers(sender, instance, action,**kwargs): if action == 'post_add': email_of_subscribers = list(instance.category.all().values_list('subscribers__email', flat=True)) html_content = render_to_string( r'mails_forms/post_created.html', {'single_news': instance } ) msg = EmailMultiAlternatives( subject=instance.header, body=instance.text_content, to=email_of_subscribers ) msg.attach_alternative(html_content, 'text/html') msg.send() template mails_forms/post_created.html Hello, **{{ username }}**. New post in your favorite category! {{ single_news.text_content|truncatechars:50 }} {{ single_news.id }} <a href="http://127.0.0.1:8000{% url 'single_news' single_news.id %}">Open post</a> -
..فعال کردن محیط مجازی در وی اس کد ابتدای پروژه جانگو میخ
mikham env to vscode fall konm ama khata mede ke script ha dar sistem shoma gher faal hastan ? -
DRF: Why does view return "<Response [200]>" rather than string?
I have the following view: @api_view(['POST']) @csrf_exempt def like_view(request, pk, destination): #destination is the user_id post = Posts.objects.get(pk=pk) if check_self_action(destination,post): print("self action!") return Response({"message","cannot like own post"}) if post.is_expired == True: print("expired") return Response({"message","post expired"}) liked = check_like(destination, post) if liked: post.likes.remove(destination) else: post.likes.add(destination) return JsonResponse({"Message":f"Post {pk} successfully liked by {destination}"}) As you can see I expect a response of the form {"Message":f"Post {pk} successfully liked by {destination}"} However, the response I get looks like this <Response [200]> Can you see or suggest why I am not getting the response I expect? Another clue might be that I have an almost identical view called dislike_view which gives me the exact response I expect. Here it is: @api_view(['POST']) @csrf_exempt def dislike_view(request, pk, destination): post = Posts.objects.get(pk=pk) if post.is_expired == True: return Response({"message","post expired"}) if check_self_action(destination,post): return Response({"message","cannot like own post"}) disliked = check_dislike(destination, post) if disliked: post.dislikes.remove(destination) else: post.dislikes.add(destination) return JsonResponse({"Message":f"Post {pk} successfully liked by {destination}"}) -
How to assign a cancel button with an id to delete the given id from database in Django
This is our database from which I wanna assign the id to the delete it this is how it will on HTML page the button so the button used is an anchor tag and I am using a for loop to print all the entries in the database but now I want to delete the entry when the user click on cancel but since the to_id and from_id can be used multiple time I want to delete on the basis of the id column so can you suggest a way to do so