Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django iterate through queryset by each field unique value
I'm currently having trouble trying to export by data to a custom csv format. I have the following models: class Transaction(models.Model): id = models.CharField(primary_key=True, max_length=255) from_account = models.ForeignKey("TestApp.User", null=True, blank=True, related_name='transaction_from_account', on_delete=models.CASCADE) to_account = models.ForeignKey("TestApp.User", null=True, blank=True, related_name='transaction_to_account', on_delete=models.CASCADE) amount = models.DecimalField("Amount", max_digits=65, decimal_places=0, default=0) confirmed = models.DateTimeField() My csv format is at follow as text: for each group of transactions of a user if user in `from_account` or `to_account`: for each day in confirmed order_by ascending: date | amount | user.name I'm having difficult trying to figure out the query i need to do to iterate through each group. I tried to look up but can only find documents related to count() by group. Hope someone can help me what i need to create this custom query :) -
The cause of grayed out in Pycharm
I'm developing Django web apps. In order to import "settings_common.py" from "settings_dev.py" , I state from .settings_common import * But somehow this statement is grayed out. Pycharm capture I can not figure out why it's grayed out. -
Heroku is unable to recognize my 'Procfile',It is showing 'Procfile declares types -> (none)',Please help me out,what should I do?
I have tried each and everything...Renamed the Procfile,Made it to the root see the images below This is the error showing on my webapp page This is showing on my dashboard as heroku has not recognized my Procfile This is the directory in which Procfile is there Procfile declares types -> (none) The above code is being executed while push This is the content of my Procfile Please Help me out -
Django DeleteView form loads, but somehow does not delete the item
I have been trying to implementing deleteview, however, while the form and page loads works fine, it does not delete the data at the end. I have been stuck at this for hours, please help me! Competencies model class Competencies(models.Model): employee = models.ForeignKey(Profile, blank = False, null = True, on_delete = models.SET_NULL) competency_category = models.ForeignKey(competency_category, blank = False, null = True, on_delete=models.CASCADE) . . def __str__(self): return self.summary Views.py - DeleteView class from django.views.generic import DetailView, DeleteView class Competencies_Delete(DeleteView): model = Competencies template_name = 'GnC/HuNet_DeleteDGC.html' def get_object(self): id = self.kwargs.get("pk") return get_object_or_404(Competencies, id = id) def get_success_url(self): return reverse('GnC:User_GnC') Html file that onclick 'Delete', allows deletion {%for competencies in Personal_competencies_list%} <tr> <td><a href = '../allusers/{{competencies.id}}/DeleteC'>Delete</a></td> </tr> {%endfor%} HuNet_DeleteDGC.html {%extends 'utilitypage.html'%} {%block content%} <form action="{% url 'GnC:User_GnC'%}" method='POST'> {%csrf_token%} <h4>Do you want to delete "{{object.summary}}"?</h4> <p><input type ="submit" value = "Confirm"></p> <p><a href="{% url 'GnC:User_GnC'%}">Cancel</a></p> </form> {%endblock%} urls.py app_name = 'GnC' urlpatterns = [ path('allusers/<int:pk>/DeleteC', views.Competencies_Delete.as_view(), name ="Delete_User_Competencies") ] -
Django session not persisting with generic views
class IndexTemplateView(TemplateView): '''Index TemplateView.''' template_name = 'frontend/index.html' def post(self, request, *args, **kwargs): '''Manages credentials received for methods calling authentication.''' bitrix24_domain = request.GET.get('DOMAIN') request.session['bitrix24_domain'] = bitrix24_domain print(request.session['bitrix24_domain']) # String is stored and printed to the screen. return redirect('index') # Bitrix24 sends credentials via POST right after GET request. # CSRF protection would cause error in this case. @csrf_exempt def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class LoginTemplateView(TemplateView): '''Login TemplateView.''' template_name = 'frontend/login.html' def get(self, request, *args, **kwargs): '''Renders the login page.''' redirect_uri = get_google_redirect_uri() print(request.session.items()) # Returns empty session. The string was never saved. return redirect(redirect_uri) I've tried setting request.session.modified = True but it didn't work either. I really don't know why I can't store a string in session. I've also tried to store in self.request within the POST request, but without success, tried to store it in the dispatch() function, in the setup() function. Tried almost everything and I can't store a single piece of information in my session. I'm also using Django Rest framework. Can anyone help me on how to use sessions with generic views? -
Difficulty adding slug to Generic Detail View in Django
The view works with just the PK, however, the problem is that my PK on the live site is an incoherent string and I want to make it coherent titling for an article to boost SEO. I don't want to change the PK to the slug. I want both. When I try to add both the PK and a slug it fails and I get the error: no reverse match. URL path: path('idea/<slug:slug>,<int:pk>', views.IdeaDetailView.as_view(), name='detail') Model: class Idea(models.Model): idea_id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Searches ID') idea_number = models.IntegerField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) idea_title = models.CharField(max_length=300, blank=True, null=True) idea_text = NonStrippingTextField(max_length=10000, blank=True, null=True) Views.py: class IdeaDetailView(generic.DetailView): model = Idea template_name = "idea/detail.html" def get_context_data(self, **kwargs): context = super(IdeaDetailView, self).get_context_data(**kwargs) context['results'] = Idea.objects.filter(idea_id=self.kwargs.get('pk')) return context Admin.py: class IdeaAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("idea_title",)} I want to add a slug which is the idea_title, however if I try to add that into the URL it fails. -
Django adding dict to template as a table
How can I add dictionary to a template nicely with Django - Just want all the information in a nice table. I have the following dict: {'Information': {0: 'size', 1: 'energy [kWh]', 2: 'ratio [PR]'}, 'Value': {0: 570.66, 1: 984092.66, 2: 81.7}} Tried to use {% for v in values[0] %} - Could not parse the remainder: '[0]' from 'values[0]' HTML Part <div> <table> <tr> <th>Information</th> <th>Value</th> </tr> <tr> {% for key, values in dict_data.items %} {% for v in values %} <td>{{v}}</td> {% endfor %} </tr> {% endfor %} </table> </div> It's resulting with that: Thank you! -
How to fix Exception Value: confirmation_pg() missing 1 required positional argument: 'snake_id'?
I am having difficulties trying to have the databases preset snake_id to be recognized by the function here is the error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/available/available/available/available/detail/ Django Version: 3.0.3 Python Version: 3.8.1 Installed Applications: ['TJW.apps.TjwConfig', '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 (most recent call last): File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\danfi\PycharmProjects\TJWEXOTICS\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /available/available/available/available/detail/ Exception Value: confirmation_pg() missing 1 required positional argument: 'snake_id' here is my views.py code: from django.http import Http404 from django.shortcuts import render, get_object_or_404 from django.template import loader from django.http import HttpResponse from .models import Snake # Create your views here. def title(request): return render(request, 'TJW/Homepage.html') def available(request): all_snakes = Snake.objects.all() template = loader.get_template('TJW/available.html') context = {'all_snakes': all_snakes} return HttpResponse(template.render(context, request)) def detailed(request): return render(request, 'TJW/Detail.html') def confirmation_pg(request, snake_id): snake = get_object_or_404(Snake, pk=snake_id) return render(request, 'TJW/Confirmation.html', {'snake': snake}) def cart(request): return render(request, 'TJW/Cart.html') this is my models.py where my database is: from django.db import models # Create your models here. class Snake(models.Model): snake_mutation = models.CharField(max_length=40) snake_sex = models.CharField(max_length=6) snake_picture … -
KeyError when trying to create a nested route
I am trying to create a https://dog.ceo/dog-api/ clone and I am running into a small problem. Here is my code: from django.db import models # Create your models here. class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos') Serializers from rest_framework import serializers from .models import Breed, BreedImage class BreedSerializer(serializers.ModelSerializer): class Meta: model = Breed fields = ['name', 'BreedImages'] class BreedSerializerRandom(serializers.ModelSerializer): class Meta: model = Breed fields = ['id', 'BreedImages'] Views from django.shortcuts import render from rest_framework import generics from .models import Breed from .serializers import BreedSerializer, BreedSerializerRandom from rest_framework.parsers import FileUploadParser, FormParser, MultiPartParser # Create your views here. class BreedList(generics.ListCreateAPIView): parser_classes = (FormParser, MultiPartParser) queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None class BreedDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None class BreedDetailRandom(generics.RetrieveUpdateDestroyAPIView): serializer_class = BreedSerializerRandom def get_queryset(self): return Breed.objects.filter(id=self.kwargs['id']).order_by('?')[0] Urls from django.urls import path from Breed import views urlpatterns = [ path('breeds/', views.BreedList.as_view()), path('breeds/<int:pk>/', views.BreedDetail.as_view()), path('breeds/<int:pk>/random', views.BreedDetailRandom.as_view()), ] My error is: KeyError at /breeds/1/random 'id' I am trying to create a nested url to get a random image from specific dog breed I have on my API, and I am unsure what is the problem. -
Django Rest Framework: Prevent duplicate objects when using CreateModelMixin
I have a Viewset where a user can create reviews for a specific product and list their all the reviews they have created for all products: class ProductReviewViewset(CreateModelMixin, ListModelMixin, GenericViewSet): serializer_class = ProductReviewSerializer def get_queryset(self): # Return all reviews for user that are not marked as deleted user = self.request.user return ProductReview.objects.filter(user=user, deleted=False).order_by('review__name') def perform_create(self, serializer): # Add user to review object before saving user = self.request.user serializer.save(user=self.request.user) The problem is that this allows the user to create multiple reviews for the same object. I wanted to prevent this, and only allow to create a review if there is no other review already created for that product (reviews marked as "deleted" will not be counted). So far I was able to override the .create() method and do the serialization, validation and checking for duplicates in there. class ProductReviewViewset(CreateModelMixin, ListModelMixin, GenericViewSet): serializer_class = ProductReviewSerializer def get_queryset(self): # Return all reviews for user that are not marked as deleted user = self.request.user return ProductReview.objects.filter(user=user, deleted=False).order_by('review__name') def create(self, request, *args, **kwargs): # Override create method to prevent duplicate object creation serializer = ProductReviewSerializer(data=self.request.data) serializer.is_valid(raise_exception=True) user = self.request.user product = serializer.validated_data['product'] exists = ProductReview.objects.filter(user=user, product=product, deleted=False).exists() if not exists: serializer.save(user=user) return Response(status=status.HTTP_201_CREATED) else: return … -
No user matches given query even though the user exists
I'm fairly new to Django and am working on making user profile pages accessible by using the user's username in the url, e.g. mysite.com/profile/someusername I'll be having links to the profile in a couple places, but the first place I'm experimenting on is in my navbar to access the logged-in user's page. base.html <a class="dropdown-item" href="{% url 'fillups:user_profile' username=user.username %}" class="btn btn-simple">Overview</a> This correctly displays the currently logged-in user's name, for the case of this example we'll user the username seconduser This is the url pattern I'm using for this: path('profile/<str:username>/',views.UserProfile.as_view(),name='user_profile') So far, the navbar will display the username, seconduser, and when I click the button I'm brought to the url /profile/seconduser/, which is what I want. The problem is, I'm not able to now use the username in my view to query the objects for the given user. Here is what I have for this view so far views.py class UserProfile(TemplateView): template_name = 'fillups/user_profile.html' slug_field = "username" slug_url_kwarg = "username" def get_context_data(self, **kwargs): context = super(UserProfile, self).get_context_data(**kwargs) usr = get_object_or_404(User, username=self.kwargs.get("username")) overview_stats = { 'total_cars': Car.objects.filter(username=usr).count(), 'total_fillups': Fillup.objects.filter(username=self.request.user).count(), 'total_distance': Fillup.objects.filter(username=self.request.user).aggregate(Sum('trip_distance')), 'total_gallons': Fillup.objects.filter(username=self.request.user).aggregate(total_gallons = Round(Sum('gallons'),4)), 'avg_price': Fillup.objects.filter(username=self.request.user).aggregate(avg_price = Round(Avg('price_per_gallon'),3)), 'total_spent': sum_total_sale(Fillup.objects.filter(username=self.request.user)), 'avg_mpg': avg_mpg(Fillup.objects.filter(username=self.request.user)) } context['stats'] = overview_stats context['active_cars'] = Car.objects.filter(status='Active').filter(username=self.request.user) … -
Django unable to load files from static
I have the following configured: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] It works fine when I was doing development on Windows, but porting the same code to Linux on AWS and accessing it on public IP gives me error that it cannot load the static files. I am running in DEBUG = True I tried countless solution but it doesn't work. -
Django inheritance on model
I'm using DRF and I have what appears to be a design issue with my models: Background: I'm doing a personal project for finance administration, so I have models for SavingsAccount, CreditCard, Incomes (this is really simplified but I think that is enough to see the problem). The problem: In incomes I should be able to track to which account I added the money, but that could be to a savings account or to a credit card, so I made another model with the common attributes for both called Account. I'm using InheritanceManager to make it a little bit easier. from model_utils.managers import InheritanceManager class Account(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=120) balance = models.DecimalField(decimal_places=4, max_digits=12) objects = InheritanceManager() def get_child(self): return Account.objects.get_subclass(pk=self.pk) class SavingsAccount(Account): bank = models.CharField(max_length=120) is_investment = models.BooleanField(default=0) class CreditCard(Account): cut = models.IntegerField() pay = models.IntegerField() bank = models.CharField(max_length=120) credit = models.DecimalField(decimal_places=4, max_digits=12) @property def used(self): return self.credit - self.balance class Income(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) amount = models.DecimalField(decimal_places=4, max_digits=12) account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="incomes") description = models.TextField() date = models.DateField() with this I'm able to interact with the account with things like: income = Income.objects.select_related("account").first() and then income.account.get_child() to retrieve the SavingsAccount or … -
Distinct querysets from Django
Trying to get some fields from my queryset to be unique, when it is outputted to the screen. class-based view: class PostListView(ListView): queryset = Post.objects.distinct() template_name = 'list/list.html' context_object_name = 'posts' ordering = ['-date_posted'] Html: {%for post in posts%} <option value="{{post.vehicle_type}}" >{{post.vehicle_type}}</option> {%endfor%} How do I make this specific loop be unique while being able to use all the object on another loop, on the same page -
Django how to debug a frozen save operation on a queryset object
I have the following code in a Django project (within the create method of a Django Rest Framework serializer) def create(self, validated_data): <...> log.info("\n\n\n") log.info(f"django model: {self.Meta.model}") log.info("CREATING CASE NOW .....") case = self.Meta.model(**kwargs) log.info(f"Case to be saved: {case}") case.save() log.info(f"Case object Created: {case}") When I'm posting to the endpoint, it's just freezing up completely on .save(). Here's example output: 2020-06-15 02:47:46,008 - serializers - INFO ===> django model: <class 'citator.models.InternalCase'> 2020-06-15 02:47:46,008 - serializers - INFO ===> django model: <class 'citator.models.InternalCase'> 2020-06-15 02:47:46,009 - serializers - INFO ===> CREATING CASE NOW ..... 2020-06-15 02:47:46,009 - serializers - INFO ===> CREATING CASE NOW ..... 2020-06-15 02:47:46,010 - serializers - INFO ===> Case to be saved: seychelles8698 2020-06-15 02:47:46,010 - serializers - INFO ===> Case to be saved: seychelles8698 No error is thrown and the connection isn't broken. How can I debug this? Is there a way to get logging from the save method? -
Best way to DRY in create/update model forms in django
How do you manage your model forms for create or updated operations?. I want to look if there is way to respect the DRY django’s philosophy, like one more dynamic ModelForm class or something like that to handle both operations instead of two classes: class EmployeeCreateForm(forms.ModelForm): class Meta: ... class EmoloyeeUpdateForm(forms.ModelForm): .... I use model form factory and instance parameter: Employeeform = model_form_factory() form = EmployeeForm(instance=SomeModel.objects.get....) But what if I want to keep any model pk field as read only during updating (i.e. Employeer id), changing widget fields (i.e. model foreign keys by default shows as html select tag but i want them as character field, that’s why I’m using instance parameter). Actually I achieved this with what i mentioned, creating 2 classes for its related operations and defining widgets with attrs. Thanks. -
Django - How to import an object from jupyter notebook to django?
I'm working on a web app which have the follow functionality: User load an excel file The web-app analysis the data Shows results in graphics I´m using django for backend and jupyter notebook to analysis the data and I have installed django-extensions for both to play nice. I've been able to upload the data and passing to the notebook but onces I have made all the analysis with it, I dont know how to export the result back to django for use it in the API. The result object is a DataFrame like the image attached I have called df_plot16 How can I do this? I have read that I have to put my notebook code in modules to export but I'm not sure this is the best way to do it. My project structure is like this and the data analysis code is inside the .ipynb - ClusterApp - MiApp - notebooks ClusterLogic.ipynb - static - templates - manage.py -
Storing multiple strings to a single field in Django model
I am trying to create a simple test program for a site. Basically the user will enter in a large amount of JSON. Then I will parse the JSON and get 10 random properties from the JSON. Then I will display those 10 properties and ask the user what the answer is. Then I am going to store the users answer in the admin panel as a way for me to check if they were right or wrong. Basically I want to keep track of property user_answer correct_answer But I would like to keep it as a single item. -
Many-To-One Using Django Allauth
I am creating a website where teachers can have many students and students can have one teacher. So far I have just been using the default Django Allauth User model. I now want to separate teachers from students and give them relationships. I was thinking I would: Add an is_teacher flag to the default user class (this way I could simply determine if a user is a student or a teacher in my templates). I also think I should be able to add this to my current Allauth User models without causing any problems (doing this should keep my Allauth User models as-is but add the extra is_teacher field shouldnt it?). class User(AbstractUser): is_teacher = models.BooleanField('teacher status', default=False) Create additional student and teacher tables to hold extra data specific to either students or teachers and hold my student-teacher relationships: class Student(models.Model): student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) teacher= models.OneToManyField(Teacher) extra_field_example = # field to hold students age class Teacher(models.Model): teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student = models.OneToManyField(Student) extra_field_example = # field to hold teachers current number of students Create a signal which creates a Student profile and attaches it to the user whenever a new user is created (id manually create … -
implementation relation in drf
I want to ask. I want to display kategori, but why not display it? following the code Let's say that we have the following views: # views.py @api_view(['GET', ]) def APIPostList(request): kategori = Kategori.objects.all() queryset = Post.objects.filter(status=1).order_by('-created_on').select_related('kategori').values() serializer = ArticleSerializer(queryset,context={'request': request},many=True) data = { 'data':serializer.data, return Response(data) # End views.py this is models.py # model.py class Kategori(models.Model): kategori = models.CharField(max_length=200, unique=True) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) .. .. kategori = models.ForeignKey(Kategori,on_delete=models.CASCADE,related_name='blog_kategori') # End model.py this is serializer.py # serializer.py class KategoriSerializer(serializers.ModelSerializer): class Meta: model = Kategori fields = "__all__" depth = 1 class ArticleSerializer(serializers.ModelSerializer): kategori = KategoriSerializer(source='blog_kategori',many=True,read_only=True) .... class Meta: model = Post fields = ('title','slug','kategori') depth = 1 # End serializer.py Django 3 latest version django-rest-framework latest version -
DRF Django File Upload ModelViewSet: why do we have to override perform_create?
I can't really figure this out. Given this model: class AppRelease(models.Model): name = models.CharField(null=False, max_length=250) file = models.FileField(upload_to=app_release_directory_path, storage=OverwriteStorage(), null=True) In order to achieve a working POST with a file upload, if we want it to work, we have to override perform create and pass the variables in the save method. class AppReleaseViewSet(viewsets.ModelViewSet): queryset = AppRelease.objects.all() serializer_class = AppReleaseSerializer parser_classes = (MultiPartParser, FormParser, JSONParser) def perform_create(self, serializer) -> None: serializer.save(name=self.request.data.get('app_id'), file=self.request.data.get('file')) What I don't understand is, why do we need to override perform_create if we are not really adding any extra data. Why doesn't it work out of the box if the parameters sent are the same? I want to know this, because, even if I know how to make it work, I prefer to reduce the code I write, in order to make everything more readable. And this seems like repeating something just for the sake of it, without adding anything. Is there, maybe, another way of doing it? Thanks for your insight. -
How to solve server error (500) while deploying Django project to Heroku?
My Django project works fine locally but as soon as I'm about to deploy to Heroku, I include this piece of code in my settings.py file: ENV_TYPE = os.environ.get('ENV_TYPE') if ENV_TYPE == "HEROKU": DEBUG = False Now when I run python manage.py runserver locally, I get a Server Error (500) in my browser. But as soon as I change DEBUG to True, everything works fine. What could be the issue? Kindly note that I set DEBUG = True, but still, there's no way of viewing the error log. It shows a white screen with the Server Error (500) on top. -
How to render png in django for email
In Django, I am trying to render a dynamically generated image for a HTML email. So far, this has been working when I use base64, but this type of image cannot be displayed in Gmail (in Outlook it works fine). Do anyone knows how to render it maybe as PNG? I was avoiding save it, sinceI don't know if it should be fine doing that on a web server. I would like to pass it as a variable to render. Working rendering in base64 # Get map image img_url = "https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/pin-l+e7ab3c(%s,%s)/%s,%s,15/500x500?access_token=pk.xxxxxxx" % (lng,lat,lng,lat) response = requests.get(img_url) usr_map = ("data:" + response.headers['Content-Type'] + ";" + "base64," + str(base64.b64encode(response.content).decode("utf-8"))) context = { ... 'usr_map': usr_map, ... } # Add email subject subject = "Subject" html_content = render_to_string('main/customer_order_confirmation.html', context) plain_message = strip_tags(html_content) # Envio de email al cliente send_mail(subject=subject, message=plain_message, from_email="xxx@xxx.xx", recipient_list=[xxx@xxx.xx], html_message=html_content, fail_silently=False) Working rendering in base64 # HTML email ... <img alt="Logo" src="{{ usr_map }}"> ... -
Trying to update urls in Django but keep getting errors
I want to make my urls more descriptive for SEO purposes. I want to add session variables and database variables, however neither seems to be working. path was: path('thing/<int:pk>'...) trying to change to: path('thing/<str:db_varible>/<int:pk>'...) and trying to change to: path('thing/<str:local_session_variable>/<int:pk>'...) I'm keep getting the NoReverseMatch error. -
My AJAX is working and I want to know why
In my app I made a favorite list that a user can populate using AJAX. Is it working perfectly but I am not sure if I did it the right way and I would like to know how to do it the proper way. Or maybe somehow I did it right. My html: <div class='sub_button'> <form class="add_btn" method='post'>{% csrf_token %} <button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button> </div> My AJAX: $(".row").on('click', ".added", function(event) { let addedBtn = $(this); console.log(addedBtn) event.preventDefault(); var product = $(this).val(); var url = '/finder/add/'; $.ajax({ url: url, type: "POST", data:{ 'product': product, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) addedBtn.hide(); } }); }); My views.py def add(request): data = {'success': False} if request.method=='POST': product = request.POST.get('product') user = request.user splitted = product.split(' ') sub_product = Product.objects.get(pk=(splitted[1])) original_product = Product.objects.get(pk=(splitted[0])) p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product) p.save() data['success'] = True return JsonResponse(data) What is bugging me is the way I passed '{{product.id }} {{ sub_product.id }}'. Because I've made it after some tinkering.