Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store multiple records in single column using python and postgresql?
Was going through calorie counter made with django. there are two columns each store multiple records like if food.weight==100 gram: calorie will be 56 fat will be something.. sugar will be something if food.weight==1tbsp: calorie will be 2 fat will be something.. sugar will be something if food.weight == 1oz: calorie will be 0 fat will be something.. sugar will be something means multiple data are being stored in single column (food.weight) and those data are related to other data of other column (calorie/fat/sugar) (i think similar results can be found with number of relational table , like if i create a separate model for each type of food.weight ) How can i achieve this. I am a new django learner developed some initial projects. Btw i am from a different background ...no where near to comupter science and learning all by myself... Please suggest what i need to learn to solve this above mentioned problem...(I am learning python and django) -
How to save data to ManyToManyField in django?
I have a question concerning the following model. I want to populate the ManyToManyField from views.py instead of doing it from the Admin. But how do I add data to the cylinder field which is the ManyToManyField? Your help will be nice for me. Here are that codes: views:- def issue(request): form=IssueForm() if request.method=='POST': form=IssueForm(data=request.POST,files=request.FILES) if form.is_valid(): confirm=form.save(commit=False) confirm.save() form.save_m2m() return redirect(cylinderListView) return render(request,'cylinderentry_form.html',{'form':form}) models: class CylinderEntry(models.Model): substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued'), ] cylinderId=models.CharField(max_length=50,primary_key=True) Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def __str__(self): return str(self.cylinderId) class IssueCylinder(models.Model): cylinder=models.ManyToManyField('CylinderEntry') userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) form: class IssueForm(forms.ModelForm): class Meta: model=IssueCylinder fields=['cylinder','userName','issueDate'] cylinder= forms.ModelMultipleChoiceField( queryset=CylinderEntry.objects.all(), widget=forms.CheckboxSelectMultiple ) userName=forms.CharField() issueDate=forms.DateInput() -
Is there a possibility to set property to swagger_auto_schema resquest_body please?
I want to pass a list to admin parameter at the bottom, but it ask to set items and I do not know how ? It get an error @swagger_auto_schema( operation_description="Modification d'une boutique d'un utilisateur", method='PUT', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'name': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'description': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'logo': openapi.Schema(type=openapi.TYPE_FILE, description='file'), 'cover_picture': openapi.Schema(type=openapi.TYPE_FILE, description='file'), 'category': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'phone_number': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'email': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'coords_lat': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'coords_lng': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'audio': openapi.Schema(type=openapi.TYPE_FILE, description='file'), 'address': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'admin': openapi.Schema(type=openapi.TYPE_ARRAY, description='array', items=UsersSerializer), } ) ) -
Django rest_framework dynamic selecting other objects
i want to create an Api for an order system. I have Ingredients and Products, both have categories which have to match if you want to combine them. So if a user selects a Pizza how can I only load in the ingredients which are available for Pizza, so the user cant select pasta as a Topping on his Pizza. So if the User selects a Product pizza in extra and extraWo only the ingredients should show up, which are available for pizza Thank you for your help -
status 415 image upload DRF
why i get 415 response when try to post by code? having no problems with browser upload. class UploadImageView(generics.CreateAPIView): parser_classes = [MultiPartParser] queryset = Image.objects.all() serializer_class = ImageSerializer class ImageSerializer(serializers.ModelSerializer): class Meta: fields = ('image', 'tags') model = Image def create(self, validated_data): image = Image.objects.create(**validated_data) return image first try: data = {'tags': 'testtag', 'image': '/home/Test/test.png'} second: data = {'tags': 'testtag', 'image': b'\x89PNG\r\n\x1a\n......\x82'} resp = requests.post(url, data=data) Also tried BytesIO object with the same result. Response 415 - Unsupported Media Type -
How to arrange data according status=True in django
I want to display card first which have status=True, so how can i arrange it by status in my views.py or in template this is my views.py: def myItem(request): context = {} if Item.objects.filter(status=True).exists(): context['data'] = Item.objects.all()#here i am taking all data but i want to arrange it so that which data have status=True will come first. else: context['data'] = Item.objects.all() context['data_false'] = True return render(request,'frontend/myeoffice.html',context) this is in my Template: {% for i in data %} {% if i.status %} <div class="col-xl-4"> <div class="card shadow-sm p-4"> <div class="card-header p-0 text-center"> <h2 class="title">{{i.name}}</h2> </div> <div class="content text-break p-2"> <p class="copy">{{i.description|truncatechars:100}}</p> </div> <div class="card-footer text-left p-0"> <button class="btn btn-primary m-3">View</button> </div> </div> </div> {% else %} <div class="col-xl-4"> <div class="card shadow-sm p-4" data-toggle="modal" data-target=".bd-example-modal-lg" style="background: #ccc;"> <div class="card-header p-0 text-center"> <h2 class="title">{{i.name}}</h2> </div> <div class="content text-break p-2"> <p class="copy">{{i.description|truncatechars:100}}</p> </div> <div class="card-footer text-left p-0"> <button class="btn btn-primary disabled m-3" data-toggle="modal" data-target=".bd-example-modal-lg"> View </button> </div> </div> </div> {% endif %} {% endfor %} NOTE : I want data which have both status=False and status=True but order should be True first and False last -
How do I add 'extraPlugins' to Django CKeditor
For various reasons I need to create my own CKeditor plugin. However when I add the plugin to the 'extraPlugins' list in settings.py : CKEDITOR_CONFIGS, and add it to my custom toolbar, it simply doesn't show up in the CKeditor on my page. If I disable my custom toolbar, and instead set: 'toolbar': 'full' My custom plugin DOES indeed show up. This is my CKEDITOR_CONFIGS with custom toolbar, where my plugin doesn't show up: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', 'toolbar_YourCustomToolbarConfig': [ {'name': 'AdvancedFunctions', 'items': [ 'Undo', 'Redo' ]}, {'name': 'BasicText', 'items': [ 'Bold', 'Italic', 'Underline', '-', 'TextColor', 'BGColor', '-', 'RemoveFormat' ]}, {'name': 'Formating', 'items': [ 'Format' ]}, {'name': 'BasicPosition', 'items': [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ]}, {'name': 'BasicIndent', 'items': [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent' ]}, {'name': 'AdvancedFunctions', 'items': [ 'Find', 'Link', 'Unlink', 'Anchor' ]}, {'name': 'FileSystem', 'items': [ 'mbn_filesystem' ]}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }], # 'height': 291, 'width': '100%', 'tabSpaces': 4, 'extraPlugins': ','.join([ 'mbn_filesystem' ]), } And replacing 'YourCustomToolbarConfig' with 'full' makes my plugin show up, however it also shows a bunch of unnecessary plugins, since it by definition shows … -
How to paste 'br' after 'label' in django forms?
I have a form: class AddNewContactForm(forms.Form): name = forms.CharField(max_length=200, required=True, label='Enter contact name') number = forms.IntegerField(required=False, label='Enter contact phone number') and i would to have tag 'br' after 'label' to print 'lavel' above 'input' -
Django query filter on nested ManyToMany field
My models are below: class Label(models.Model): name = CharField() class Message(models.Model): labels = ManyToManyField(Label) class Thread(models.Model): messages = ManyToManyField(Message) I have to filter out thread whose all messages don't have label assigned. Thread --> all Messages --> Labels.empty() I have tried this Query: Thread.objects.filter( Q(messages__labels__isnull=True) ) But it returns thread object, even if one message in that thread doesn't have label. How to get query which iterates all messages and check if labels are empty in that each message. -
Django Validators in Serializer vs Validators in Models
I have searched about this extensively and have not found any substantial explanation for this - I have read the DRF documentation and also gone over the following SO links Django Model field validation vs DRF Serializer field validation, Django Model field validation vs DRF Serializer field validation. I have a certain Model where I want to define a Constraint where two fields cannot be the same and need to be unique together. Django models provide the following way to do this class Std(models.Model): std_cons = models.DecimalField(max_digits=11, decimal_places=4, null=True, blank=True) target_cons = models.DecimalField(max_digits=11, decimal_places=4, null=True, blank=True) key_item = models.BooleanField(default=False) class Meta: constraints = [ models.UniqueConstraint(fields = ['std_cons','target_cons'], name='unique_std_entry') ] I can also achieve this in the serializers using the UniqueTogetherValidator from rest_framework.validators import UniqueTogetherValidator class StdSerializer(serializers.Serializer): class Meta: model = Std fields = '__all__' validators = [ UniqueTogetherValidator( queryset=Std.objects.all(), fields=['std_cons', 'target_cons'] ) ] Questions: Which method should be used when and why? What is the significance of both the methods? Should both be used? (maybe Model Level to take care of DjangoAdmin and Serializer to take care of HTTP calls) -
You are trying to add a non-nullable field 'name' to comment without a default
Error ```You are trying to add a non-nullable field 'name' to comment without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: ``` models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey('auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg') def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField(max_length=255, null=True, blank=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) i tried and without blank=True and body = models.TextField(max_length=255, null=True, blank=True, default='Some String') This error constantly pops up, I would be grateful for any help -
how to create view for appointment form in footer in every page in Django
I could not add appointment data in the database In my every html template file, I have added a footer.html like bellow: <!DOCTYPE html> <html> <head> <head> <body> some content {% include 'footer.html' %} </body> <html> in footer.html, I have mentioned the address and appointment form as above <section> <div class="fo-appointment-form"> <form class="forms-sample" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> adress </div> <input type="text" name="name" id="id_name" placeholder="Name"> <input type="text" name="phone" id="id_phone_0" placeholder="Phone number"> <input type="email" name="email" id="id_email" class="gui-input" placeholder="Email address"> <textarea class="gui-textarea" id="id_message" name="message" placeholder="Message"></textarea> <input type="Submit" class="submit-btn" type="submit"> <form> </div> </section> in Django view.py def Appointment_view(request): if request.method == 'POST': appointment= Appointment.objects.create( name = request.POST.get("name"), phone = request.POST.get("phone"), email = request.POST.get("email"), message = request.POST.get("message"), ) appointment.save() return redirect('same?_page') return render(request, 'frontend/footer.html') can someone tell me how to do this? how to write view for footer? where is the mistake? -
How to print / access Django IntegerChoice human readable labels with Model definition
For the Django Model inherited from IntegerChoices with following human readable strings : class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') __empty__ = _('(Unknown)') How can I access the human-readable 'No' and 'Yes' text? -
making a smaller Django/mysql docker image
I am currently using this Dockerfile to build my backend service: FROM python:3.9-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8002 I also have a mysql database the Docker-compose file is: version: '3.8' services: dj: build: context: . dockerfile: Dockerfile ports: - 8000:8002 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: ... MYSQL_USER: ... MYSQL_PASSWORD: ... MYSQL_ROOT_PASSWORD: ... volumes: - .dbdata:/var/lib/mysql ports: - 33068:3306 I want to reduce the size of my container which is currently 1.2G any detailed explanation on how to do that would be helpful, precisely I want to know how to do a multisatge build or use a lighter base image properly because I looked at some blogs that use the alpine as their base image but that doesn't work for me probably because my requirement.txt: Django==3.1.3 djangorestframework==3.12.2 django-cors-headers==3.5.0 djangorestframework-simplejwt==4.7.1 pyjwt==2.1.0 mysqlclient==2.0.1 django-mysql==3.9 is not enough. -
"The view page.views.register_view didn't return an HttpResponse object. It returned None instead." Error while using custom registration form
I'm trying to create a custom user registration page only with email and password. This is my view.py file: def register_view(request, *args, **kwargs): user =request.user if user.is_authenticated: return HttpResponse(f"You are already authenticated as {user.email}.") context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect("home") else: context['registration_form'] = form return render(request, 'page/templates/register.html', context) When I try to access to the register.html page using the link in my website this is the error I'm gettin. The view page.views.register_view didn't return an HttpResponse object. It returned None instead. What could be the problem? Thank you -
Django, creating multiple identical fields in the same model
I am completely new to Django, so forgive me if this is the wrong approach. While I'm trying to learn Django, I like to do my own little practice problems to solidify my understanding. Working with models I created the example model objects: from django.db import models class Food(models.Model): name = models.CharField( max_length=50, help_text="Name of Fruit or Vegetable" ) food_group = models.CharField( max_length=9, class Vitamins(models.Model): name = models.ForeignKey( Food, on_delete=models.CASCADE ) vitamin_A = models.CharField( max_length=20, ) . . . folate = models.CharField( max_length=20, help_text="Folic Acid" ) In my object, I have 5 identical fields that store text i.e. (Trace amounts, 5mg, No Information). However it seems tedious to type out every field. Is there a more efficient way to do this? -
Import could not be resolved when trying to create mezzanine project in a venv with vs code
I tried to setup my first mezzanine project in a venv. pip install mezzanine gives me the warning django-contrib-comments 2.1.0 has requirement Django>=2.2, but you'll have django 1.11.29 which is incompatible.. Why does it want to use django-contrib-comments at all if mezzanine only works with older django versions? When I open the env folder in vs-code I get several import cloud not be resolved and foo is not definedwarnings. I tried to change the interpreter by choosing it in the dropdown-menu, by changing my settings.json and by updating the venv path as stated in https://techinscribed.com/python-virtual-environment-in-vscode/ and I checked for the pip and python version. The strange thing is that I get ➜ foundation_site_env python --version Python 2.7.16 ➜ foundation_site_env pip --version pip 21.1.2 from /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip (python 3.9)when I only open the env folder in vs code but (foundation_site_env) ➜ .venv python --version Python 3.6.8 (foundation_site_env) ➜ .venv pip --version pip 18.1 from /Users/lindacarmenschmid/.venv/foundation_site_env/lib/python3.6/site-packages/pip (python 3.6) when I open the .venv folder in vs code, so it only seems to activate the env when I open the .venv folder, but in both cases the warnings remain the same. Any ideas on what I might have done wrong and what else I … -
object has no attribute 'cleaned_data'
I am working on CS50 django project, yet i keep receiving the error of " object has no attribute 'cleaned_data". I have read all the related question but still cant figure out my problem here is my script of view.py class NewTitleForm(forms.Form): newtitle = forms.CharField(label="title ") class NewContentForm(forms.Form): newcontent = forms.CharField(widget=forms.Textarea(attrs={"rows":5, "cols":5})) def newpage(request): if request.method == "POST": titleinput = NewTitleForm(request.POST) contentinput = NewContentForm(request.POST) if titleinput.is_valid(): newtitle = titleinput.cleaned_data["newtitle"] newcontent = contentinput.cleaned_data["newcontent"] util.save_entry(newtitle,newcontent) else: return render(request, "encyclopedia/newpage.html", { "NewTitleForm": NewTitleForm(), "NewContentForm": NewContentForm() }) return render(request, "encyclopedia/newpage.html",{ "NewTitleForm": NewTitleForm(), "NewContentForm": NewContentForm() }) And the error code is AttributeError: 'NewContentForm' object has no attribute 'cleaned_data' I have no idea what's going on -
Apscheduler Job in Django executes twice
The scheduled job executes twice with difference in nanoseconds. I have a task as follows in task.py def print_hello(): print("time-->",datetime.datetime.now()) print("hello") def print_world(): print("time-->",datetime.datetime.now()) print("hello") scheduler = BackgroundScheduler() scheduler1 = BackgroundScheduler() Add in app.py from app folder consist following code line.. from django.apps import AppConfig from datetime import date class ExploitDataConfig(AppConfig): name = 'exploit_data' def ready(self): from exploit_data import task task.scheduler.add_job(task.print_hello, 'interval', minutes=5) task.scheduler1.add_job(task.print_world, 'interval', minutes=5 task.scheduler.start() task.scheduler1.start() I want this to execute only once at the interval of 5 minutes. ANY HELP IS APPRECIABLE .. -
Get max and min formatted date values from queryset in Django
I have a one to many relation between session and camp. Now I have to get the max and min dates of all camps combined for a particular session. I am able to do it like this: sess = Session.objects.last() max_min_dates = sess.camp.aggregate(Min('start_date'), Max('end_date')) But if I try to send this from HttpResponse then I am getting this error: TypeError: Object of type 'date' is not JSON serializable So I need to send the formatted date values in that. How can I modify the above code to get the same? -
How to hit Vscode breakpoints in unit tests from within a docker-compose setup running Django
What I'm trying to do seems simple enough, but it's been crazy hard to actually get there. I have a Django application that runs in a docker-compose environment, and I want to run and debug the unit tests with breakpoints in Vscode. Since this is a big project with a team that doesn't necessarily use vscode, I can't add libraries willy-nilly (like ptvsd, for example). I'm hoping there's a magic configuration for tasks.json and launch.json that will makes things work. I have a container for a postgres database, one for django, and one for redis, all defined in docker-compose.yml. There's a command that I can run in the terminal that will run the tests, it's: docker-compose run --rm app python manage.py test where app is the django app container. I'd love to be able to run this command in such a way that it can hit breakpoints in vscode. My incomplete stab at the launch.json file looks like this: { "configurations": [{ "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "compose-for-debug", "python": { "pathMappings": [{ "localRoot": "${workspaceFolder}", "remoteRoot": "/app" }], "projectType": "django" } }] } And my tasks.json: { "version": "2.0.0", "tasks": [{ "type": "docker-build", "label": "docker-build", "platform": … -
Django models Many to one not able to access all objects in a foreign key field
I might be confused however when I check the django-admin panel I can see (will provide a screenshot) , over 50 models attached to my primary model, however whenever I make a query in the code and try to access the set associated with the field I only ever get one entry. I am trying to make one query and check all models associated with the field. My models.py code: class TokenData(models.Model): name = models.CharField(max_length=200) contract_address = models.CharField(max_length=200,primary_key=True, unique=True) def save(self, *args, **kwargs): #print('save() is called.') super(TokenData, self).save(*args, **kwargs) def __str__(self): return self.name class WalletData(models.Model): address = models.CharField(max_length=200,primary_key=True,unique=True) contract_address = models.ForeignKey(to=TokenData,on_delete=models.CASCADE,) last_bitquery_scan = models.CharField(max_length=200) def __str__(self): return self.address I am trying to access the model like so : WalletData.objects.filter(address=address) One thing I noticed is when I create a variable containing the filter, and access the contract_address in the WalletData model, I can endlessly query myself in a circle for lack of a better word, by accessing the set and executing a get against it. I am just wanting to access all 50 models like shown below -
POST method does not pass the value password from the input field
Here form is submitted via POST method but password given in the input field of type=password not assigning to 'upassword' given in the userregister function.When I print the 'upassword' it gives an output "None".Also it gives an error like this when I give JAVASCRIPT validation. Internal Server Error: /User/Registration/ Traceback (most recent call last): File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\salon\user\views.py", line 214, in userregister epassword = sha256(upassword.encode()).hexdigest() AttributeError: 'NoneType' object has no attribute 'encode' views.py def userregister(request): if request.method == 'POST': upassword = request.POST.get('password') print(upassword) ucpassword=request.POST.get('cpassword') epassword = sha256(upassword.encode()).hexdigest() -
The extra function written for the DeleteView class does not work
I have added a function that if the post is deleted by the user, it will be deleted if there is an uploaded photo, but the function does not work. my view: class NewsDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = News template_name = 'news/news_delete.html' success_url = reverse_lazy('news_list') def delete_header_image(self, pk): news = get_object_or_404(News, id = pk) header_image = news.header_image if header_image is not None: os.remove(str(header_image)) return HttpResponseRedirect(reverse('news_list', args=[str(news.pk)])) else: return HttpResponseRedirect(reverse('news_list', args=[str(news.pk)])) def test_func(self): obj = self.get_object() if self.request.user.has_perm('news.all') or self.request.user.has_perm('news.delete_news') or obj.author == self.request.user: return True urls: urlpatterns = [ path('<int:pk>/delete', NewsDeleteView.as_view(), name='news_delete'), ] models: def get_header_image_filepath(self, filepath): return f'images/news/header/{self.author.id}/{self.header_image}' class News(models.Model): title = models.CharField(max_length=255) header_image = models.ImageField(null=True, blank=True, upload_to=get_header_image_filepath) body = RichTextUploadingField() datetime = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("news_detail", args=[str(self.id)]) -
Django DRF routing not a valid regular expression
I want to use a DRF viewset with an @action decorator, but when I call that endpoint I get the error: django.core.exceptions.ImproperlyConfigured: "^\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 2; was group 1 at position 32 Here is url.py: router = routers.DefaultRouter() router.register(r"", GenreViewSet, basename="genre") urlpatterns = router.urls And the viewsets.py: class GenreViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] pagination_class = None queryset = Genre.objects.all() def get_serializer_class(self): if self.action == "list": return GenreSerializer @action(detail=True, methods=["patch", "delete"], url_path="favourite") def make_genre_favourite(self, request, pk=None): genre = self.get_object() # Other code and responses here. The parent url comes from /api/genre/. The list endpoint works, it returns all genres as it should, it's the action that gives that error. Any help appreciated much. I've tried format_suffix_patterns and no luck in case you might be asking.