Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Live Scoreboard implementation in Django
I have to create a Live Scoreboard in Django for a game. The game will have 5 players and each of them will receive a score between -5 to 25 every round. The game will have multiple rounds and I want to display their total score(sum of scores up to the latest round) after every round on a scoreboard page that they can connect to from their devices.Being able to store every game after it ends would be an added bonus. I want to know how I could implement this -
Django url Error. Debug returns NoReverseMatch
I'm trying to make a link to the admin page (localhost:8000/admin), but when trying to link like this: Html: {% if user.is_staff %} <a class="nav-item nav-link" href="{% url 'admin' %}">Admin</a> {% endif %} Code: urlpatterns = [ path('admin/', admin.site.urls, name='admin'), ] I get an error saying NoReverseMatch at /. Traceback: File "C:\Users\krish\Envs\myproject\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\core\handlers\base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\core\handlers\base.py" in _get_response 143. response = response.render() File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\response.py" in rendered_content 83. content = template.render(context, self._request) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\backends\django.py" in render 61. return self.template.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 171. return self._render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\loader_tags.py" in render 150. return compiled_parent._render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\defaulttags.py" in render 309. return nodelist.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\template\defaulttags.py" in render 443. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\krish\Envs\myproject\lib\site-packages\django\urls\base.py" in reverse 90. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) … -
I am not able to use "python manage.py dbshell" in visual code
I have installed sq-lite program in my local machine & set environment variables also. After that I am able to use "python manage.py dbshell" in command line but when using same command in visual code it showing error "CommandError: You appear not to have the 'sqlite3' program installed or on your path." I have attached screenshot also for reference. In environment variables I have added "c:\sqlite" into path variable. dbshell_error_screenshot -
ManyToManyField Self object lis comes up as empty in the Admin panel of Django
I've got a Model object of Document that has a number of fields that link to itself. However, when creating a new object from the admin page, or editing an existing one, the list of linked Documents come up as empty. Other ManyToManyFields that are in the same object seem to be fine, and list the right content. I tried changing the related_name filter and play around with symmetrical and even changed self to Document,it still comes up as an empty list (I have other Document objects already created, so the object list is not empty) Note: I can tell they still link to Document as when I click the little plus button to add a document inside the document (recursive add), the pop up I get is for another Document with the right fields. Screenshot How can I get a list Document objects to link in object Document? Am I doing anything wrong? Thank you for your help. class Document(models.Model): name = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) document_content = models.TextField(blank=True, null=True) file_date = models.DateField(blank=True, null=True) file_text = models.TextField(blank=True, null=True) parent_document = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) #The ones below do not show up anything, show up as empty boxes. related_checklist … -
How to create a search function on a class-based list view?
I am trying to create a search function based on the title of my posts. Right now I am trying to implement this search using a filter but the list view is not rendering. I am unsure if I should implement a URL for my search function. This is my model: class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default = 'default0.jpg', upload_to='course_image/') description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=6) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) feedback = models.ManyToManyField(Feedback) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) This is my class-based list view: class PostListView(ListView): model = Post template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html context_object_name = 'post' ordering = ['date_posted'] paginate_by = 12 def get_queryset(self): try: title = self.kwargs['title'] except: title = '' if (title != ''): object_list = self.model.objects.filter(title__icontains = title) else: object_list = self.model.objects.all() return object_list This is my search bar: <div id="search"> <form method='GET' action=''> <input type="text" name='q' placeholder=""> <button id='search_holder'> <img src="/static/store/search_icon.gif" id="search_icon"> </button> </form> </div> This is my html that is rendering the posts: {% extends "store/base.html" %} {% block content %} {% include "store/home_ext.html" %} <div style="padding-top: 20px;" id="main" > <section class="text-center mb-4"> <div class="row" id="random"> {% for post in posts %} … -
how to configure autocomplete_light in django 2.2?
I tried to configure autocomplete_light for django2.2 but i'm getting some errors its because for django version i guess. Initially it was related to render() got an unexpected keyword argument 'renderer' this got fixed by adding "renderer=None" in render function in widgets.py. After that this error, from django.core import urlresolvers its depreciated in django 2.2. So i used, from django.urls import reverse(in base.py). then the error changed to "function' object has no attribute 'NoReverseMatch'". autocomplete_light_registry.py from autocomplete_light import shortcuts as autocomplete_light from django.db.models import Q from assets.models import Dealer class DealerAutocomplete(autocomplete_light.AutocompleteModelBase): autocomplete_js_attributes = { 'placeholder' : 'Region' } attrs={ 'placeholder':'Region', 'class':'form-control', 'data-autocomplete-minimum-characters': 1, } def choices_for_request(self): q = self.request.GET.get('q','') choices = self.choices.filter(is_deleted=False) if q: choices = choices.filter(Q(region__istartswith=q)) return self.order_choices(choices)[0:self.limit_choices] autocomplete_light.register(Dealer, DealerAutocomplete) forms.py class DealerForm(forms.ModelForm): class Meta: model = Dealer fields = ('region','dealer_name','type_dealer','address','loc_latitude','loc_longitude','mobile','phone','email') widgets = { "region": autocomplete_light.ChoiceWidget('DealerAutocomplete'), 'dealer_name' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Dealer name'}), 'type_dealer' : forms.Select(attrs={'class':'form-control', 'placeholder':'Dealer Type'}), 'address' : forms.Textarea(attrs={'class':'form-control', 'placeholder':'Address'}), 'loc_latitude' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Location Latitude'}), 'loc_longitude' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Location Longitude'}), 'mobile' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Mobile'}), 'phone' : forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone'}), 'email' : forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'}) } What i want know whether autocomplete_light works in django2.2 or is there any issues in my code. Please correct or pointed out the mistakes. -
django admin forms.ModelForm validation for blank IntegerField
How can you make it in django admin so that when you click save if the forms.IntegerField is blank to return a validation error?. Currently if you save the model it will still accept the transaction. Any suggestions? class CarInlineForm(forms.ModelForm): car_type = forms.CharField(disabled=True) car_qty = forms.IntegerField(min_value=1) class Meta: model = Car exclude = ['created'] class CarInline(admin.TabularInline): model = CarOrderItem extra = 1 max_num = 1 form = CarInlineForm exclude = [ 'created', ] class CarAdmin(admin.ModelAdmin): inlines = [CarInline] -
I need an real-life project for practice with python and Django
I'm working as an apprentice for a software company in Germany. The most time I work for projects with Visual Basic for Application (Excel). For my finals I need more practice in modern languages. I like to build a web-application for free, can be a little project or something bigger, the important thing is that I learn a few things about planing a project, speaking with the customer about the project and build the application. Why Python and Django? Aside from VBA, I learned Python for my own projects. But writing application for myself is not the same like working for a customer. Best Regards, Tobias.M -
How to link multiple form with primary key?
I am trying to create one to many relationship in django forms , in which i have created one customer with id , and i want to use information of that customer to create new form models.py from django.db import models # Create your models here. class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender = models.CharField(max_length=50); class Ipd(models.Model): Presenting_complaints = models.CharField(max_length=300); Reason_admission = models.CharField(max_length=300); patient = models.ForeignKey('Patient',on_delete=models.CASCADE forms.py from django.forms import ModelForm from django import forms from .models import Patient,Ipd class PatientForm(ModelForm): OPTIONS = ( ('',''), ('Doctor1','Doctor1'), ('Doctor2','Doctor2'), ) OPTIONS2 = ( ('Male', 'Male'), ('Female', 'Female'), ) Gender= forms.TypedChoiceField(required=False, choices=OPTIONS2, widget=forms.RadioSelect) consultant = forms.ChoiceField(choices=OPTIONS) class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm (ModelForm): patient = Patient.objects.all() class Meta: model = Ipd fields = ('Presenting_complaints','Reason_admission', 'patient') def save(self, commit=True): instance = super().save(commit) # set Car reverse foreign key from the Person model instance.patient_set.add(self.cleaned_data['patient']) return instance views.py @login_required def new(request): if request.POST: form = PatientForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Patient is successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = PatientForm() return render(request, 'new.html', {'form':form}) … -
"How to display DOC file on web page in django"
Problem is when I upload any doc file on the website it will display on my web page as HTML view of doc file format -
Using Django 2.2 Models with multiple foriegn keys ,how can one access and filter data?
I have this model of products class Product(models.Model): name = models.CharField(max_length=50) productId = models.AutoField(max_length=50,primary_key=True) productType = models.CharField(max_length=50) productPrice = models.PositiveIntegerField(default=0) matType = models.CharField(max_length=100,default='Use comma , to seperate multiple materials Ex. Cotton 90%, Spandex 10%') #Multiple Material divided by comma,mat1 is main material seller = models.ForeignKey(User, related_name='sellers',on_delete=models.CASCADE,default='NA') cat_1 = models.ForeignKey(Cat1,related_name='catlevel1',on_delete=models.CASCADE,default='NA') I have two foreign Keys, one is to User Class for seller information and another is to Categories with Model Name Cat1. For Same i have related names catlevel1 and sellers. I am using this code in html to access products by current logged in user. {% for prod in user.sellers.all %} {% for color in prod.colors.all %} {% for size in prod.sizes.all %} <tr> <td>{{ prod.name }}</td> <td>{{ prod.productPrice }}</td> <td>{{ prod.matType }}</td> <td>{{ color.colorMain }},{{ color.colorTrim }}</td> <td>{{ size.nameSize }}</td> <td>{{ size.quantity }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} The first loop (first line): {% for prod in user.sellers.all %} accesses all the products by current_user user. Here sellers is the related name of foreign key seller I want to get data using both foreign keys,seller in User Class and categories under cat1. So the main aim is to get products that is of current … -
Multiple authentication types in Django App
I have a Django App which exposes some REST APIs, with LDAP authentication enabled. It is working fine. Now, I want this app to support OKTA authentication as well so that Web UI client can authenticate via OKTA, not through LDAP. How can I configure my Django project to support both kinds of authentication (Ldap + Okta)? -
Django: deletion of files after conversion from TextField to File
I'm very new to Python Programming Language and Django platform. I encountered a problem after converting the texts filled in TextField to a '.txt'. Supposedly if I want to delete the files that I have just created as '.txt' (as given in write_text in Model.py), how can I do it in the Model.py? I have tried it using FileField to upload (as given in fail_fid in Model.py) and delete the files and it works fine. Codes in models.py: from django.db import models class fail_fid(models.Model): Fail_Fid_Title = models.CharField(max_length=100, default=False, null=True) Fail_Fid = models.FileField(upload_to='fids/faillist', blank=True) def __str__(self): return self.Fail_Fid_Title def delete(self, *args, **kwargs): self.Fail_Fid.delete() super().delete(*args, **kwargs) class write_text(models.Model): Fail_Fid_Title = models.CharField(max_length=100, default=False, null=True) Write_Text = models.TextField(default=True, blank=True) Codes in forms.py: from django import forms from .models import fail_fid, write_text class fidForm2(forms.ModelForm): class Meta: model = fail_fid fields = ('Fail_Fid_Title', 'Fail_Fid') class fidForm3(forms.ModelForm): class Meta: model = write_text fields = ('Fail_Fid_Title', 'Write_Text') Codes in views.py from django.shortcuts import render, redirect from .forms import fidForm1, fidForm2, fidForm3 from .models import fail_fid, write_text def failfid(request): fids1 = raw_mica.objects.all() fids2 = fail_fid.objects.all() fids3 = write_text.objects.all() fids4 = fids2 | fids3 return render(request, 'fid_list.html', {'fids2': fids2, 'fids3': fids3, 'fids4': fids4}) def upload_fid(request): if request.method == 'POST' and … -
signing up a Custom user model with createMixinModel
I want to write an API for a Custom User Model with MiXin. I wrote a CustomUser which inherits Django User Model. Then I defined Student Profile with some attributes. in serilizer.py I defined the fields I want to get information from Users. Now in Views.py I don't know how to code to sign up user with CreateMixinModel class StudentSignUpView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView, ): """This part is relatng to sign up students a""" queryset = Student.objects.all() serializer_class = StudentSignUpSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request,**kwargs): serializer = self.get_serializer(data=request.POST) print("answerrrrrr----------->>>", serializer) if serializer.is_valid(): customusers = CustomUser.objects.all() I want to be able a custom user to sign up -
There's Reverse Accessor Error occuring. What is it and how do I solve it?
[I used related_name but it didn't work[][1]1 -
How do I pass table data from a template over to Django on a button/submit click?
My template has a search field that brings up results on a table. In the table, with each result, I'd like to place a "+" Button that will allow the user to save that row of results to their profile. Here is what the page looks like: https://imgur.com/txKSuj0 The relevant chunk of my template: <form action="{% url 'foodlog:detail' foodlist.id %}" method="post"> {% csrf_token %} {{ form2 }} <input type="submit" name="search" value="Search"> </form> {% if foodResults %} <table> <th>Food</th> <th>Calories per 100 grams</th> <th></th> {% for x, y inResults %} <tr> <td>{{ x }}</td> <td>{{ y }}</td> <td> <input type="submit" name="add" value="+" method = "post"> </td> </tr>> {% endfor %} </table> {% endif %} Relevant chunk of my view: if request.method == 'POST': if 'add' in request.POST: #psuedo code #object.create(food=[buttonrow, firstheader], calories=[buttonrow, secondheader]) #object.save() I also don't know why those '<<<<<' appear on the page, as shown in the image. -
How to override model form to add current post_id as ForeignKey for Comment?
I am creating a Post-comments app. I am unable to override the model form for Comment to use the id of the Post being commented on using instance of the post. I have tried using various permutations of the value for the post_id with no success. Here is my models.py: class Post(models.Model): pid = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog-home')#, kwargs={'pk':self.pk}) class Comment(models.Model): cid = models.AutoField(primary_key=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField() comment_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.comment def get_absolute_url(self): return reverse('blog-home') def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) My view for creating a comment is as follows: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['comment'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['post_id'] return super(CommentCreateView, self).form_valid(form) def get_success_url(self): if blog_messages: messages.success(self.request, self.message) return reverse('blog-home', kwargs={'pk': self.kwargs['post_id']}) The template for creating the comment is as below: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Answer</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info", type="submit">Submit </button> </div> </form> </div> {% endblock %} … -
Django form processing, use data as variable
I'm pretty new in Django development. What i'm trying to accomplish is to process the data from forms and execute that on a windows/linux servers. I have already tried to provide the data through char.field and after clicking the button it was able to display it on the home page. My question is, how can i pass the data to subprocess.check_output and execute it on the servers ? Does it needs to be on the dictionary before returning it on the template? Because when I tried to add a function to execute it via subprocess. The home page is not proceeding due to "No object provided attribute is null" -
Click a html tag, modal form display and data is filled up in form
I'm coding about edit user. I want when I click a tag next to username, edit modal form display and user data is filled up in form. Can show me how do it? Thanks -
How to display result below the form without submitting it in django
Hi I have a form which has a multi-select dropdown on selecting i want to give result without submitting the form. Once result (pass/ fail) is viewed then submit the form and its details get saved in the db. So how do i show result based on the dropdown? -
django.db.utils.ProgrammingError: column "role" of relation "APP_profile" does not exist
Currently, I am facing the above-mentioned error when I am trying to execute the command python3 manage.py migrate I cannot figure out the issue and the posts on Stackoverflow suggest to delete the migrations and recreate it, which I did. But I still face the same issue. Please find below some code: models.py: from __future__ import unicode_literals from django.db import models from bokeh.themes import default from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser from django.utils import timezone # Create your models here. class Project(models.Model): REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) form_type = models.CharField(max_length=20, blank=False, null=False) created_at = models.DateTimeField(default=timezone.now()) status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending') user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) class Profile(models.Model): NORMAL = 1 APPROVER = 2 REVIEWER = 3 ROLE_CHOICES = ( (NORMAL, 'Normal'), (APPROVER, 'Approver'), (REVIEWER, 'Reviewer'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() admin.py: from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import Profile, Project admin.AdminSite.site_url = '/MyProject' class … -
How to add URL component to current URL via a HTML button? (Django 2.1)
I have a HTML button that is supposed to sort the search results by alphabetical order. Button HTML code: <a href="?a-z=True" type="button" class="btn btn-outline-{% if 'a-z' in request.GET %}success{% else %}secondary{% endif %}">A-Z</a> views.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') if request.GET.get('a-z') == 'True': articles = articles.order_by('Title') Currently, the URL contains the keywords searched by the user. For example, if the user searches for "cheese," the URL will be search/?keyword=cheese. When I click the sorting button, the URL becomes search/?a-z=True and loses the keyword, which means that the sorting mechanism isn't sorting the search results based on the keyword. I think I need the URL to contain both the keyword and ?a-z=True for the sorting mechanism to work on the search results. How can I make that happen? -
Django - Unable to open database file (sqlite3.OperationalError)
I am developing a small app with the django framework and when trying to serve it via apache2 I get the following error: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8) My settings.py entry for the database looks like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } The db file exists and has the following rights given by chmod: root@myVPS:/var/www/lab# ls -l db.sqlite3 total 30236 -rwxrwxr-x 1 www-data www-data 3018568 Jul 1 22:14 db.sqlite3 The root folder /var/www/lab: drwxrwxr-x 8 www-data www-data 4096 Jul 2 01:15 lab I read that it might be a problem with the rights but I can't seem to find what I did wrong. My Apache2 config file: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName sub.domain.com ServerAlias sub.domain.com DocumentRoot /var/www/lab <Directory /var/www/lab> Options FollowSymLinks AllowOverride All </Directory> ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/lab/static <Directory /var/www/lab/static> Require all granted </Directory> <Directory /var/www/lab/chatbot> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/www/lab/chatbot/wsgi.py WSGIDaemonProcess django_app python-path=/var/www/lab python-home=/var/www/lab/venv … -
Creating a new viewset with multiple filters for the viewset get method
Hi i have a viewset that I am creating. I want to over ride the the get functino and get all the records that have the filtered parameter which is passed into the get view. I also want to be able to do the rest of the crud functionality - GET POST PUT DELETE - and use the paramater that is passed through the url as a parameter for the POST and UPDATE. Right now, when i pass in the parameter, rather than filter the data that is returned, it is giving me no details found which is not what i want. i want it to be used as a secondary filter for all the records that i get back from the database. Here is the code: viewset class PreferenceUserViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all().filter(user_id=1) serializer_class = PreferenceSerializer class PreferenceNamespaceViewSet(viewsets.ModelViewSet): queryset = Preference.objects.all().filter(user_id=1) serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] @permission_classes((IsAuthenticated)) def list(self, request, namespace=None): # switch user_id value with logged in users id queryset = Preference.objects.all().filter(user_id=1, namespace=namespace) serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) urls: path('preferences/<str:namespace>/', PreferenceNamespaceViewSet.as_view({ 'get':'list' })), path('users/<int:pk>/stacks/', person_stack, name='user-stacks'), I … -
Does rest framework @action kwargs replace class values or not?
I have tried to search the answer for this question on rest framework docs or stackoverflow but I have not been able to find it. Suppose a rest framework viewset: class MyModelViewSet(ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] @action( detail=True, permission_classes=[], authentication_classes=[], ) def extra_action(self, request, pk=None): return Response() in this case, the extra_action action will have no permission nor authentication classes or will have the ones defined at class level? what happens if I override the get_permissions method? class MyModelViewSet(ModelViewSet): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_permissions(self): permission_classes = self.permission_classes[:] if self.action == 'extra_action': permission_classes.append(MyPermissionClass) return [permission() for permission in permission_classes] @action( detail=True, permission_classes=[], authentication_classes=[], ) def extra_action(self, request, pk=None): return Response() Thank you for your help!