Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translation instructions in Wagtail don't work
trying to create multiple language fields in wagtail based on the instructions. My base.py file contains: MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ] USE_I18N = True My blog/models.py file looks like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailsearch import index from django.utils import translation class TranslatedField(object): def __init__(self, en_field, es_field): self.en_field = en_field self.es_field = es_field def __get__(self, instance, owner): if translation.get_language() == 'es': return getattr(instance, self.es_field) else: return getattr(instance, self.en_field) class BlogIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] subpage_types = ['blog.BlogPage'] class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) #body_en = RichTextField(blank=True) #body_es = RichTextField(blank=True) body = TranslatedField( 'body_en', 'body_es', ) search_fields = Page.search_fields + [ index.SearchField('intro'), #index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), #FieldPanel('body', classname="full"), ] parent_page_types = ['blog.BlogIndexPage'] When I run ./manage.py makemigrations it runs fine, but when I run ./manage.py migrate, I get the error: django.db.utils.ProgrammingError: column "body_es" of relation "blog_blogpage" already exists How do I resolve this error? -
django-auth-ldap AUTH_LDAP_FIND_GROUP_PERMS not working
Problem As far as I can tell, django-auth-ldap is doing everything I need given my configuration. Except that it's unable to establish a mapping from ldap groups to django groups. I have a group in ldap called dev, i.e., cn=dev. I also have a group in django called dev. When I login with my user in Django (uid=fkilibarda), django-auth-ldap is able to get my firstname, lastname, and email, but it fails to add me to the dev group. Debugging django_auth_ldap.backend line: 203 def get_group_permissions(self, user, obj=None): if not hasattr(user, 'ldap_user') and self.settings.AUTHORIZE_ALL_USERS: _LDAPUser(self, user=user) # This sets user.ldap_user if hasattr(user, 'ldap_user') and (user.ldap_user.dn is not None): return user.ldap_user.get_group_permissions() else: return set() I've found that hasattr(user, 'ldap_user') is always false. Thus, user.ldap_user.get_group_permissions() never runs, which is why the group mapping is never established. I just don't understand the significance of the above. Why doesn't user have the ldap_user attribute? Configuration AUTH_LDAP_SERVER_URI = "example_server" AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=group,dc=example,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=posixGroup)', ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'cn=dev,ou=group,dc=example,dc=example,dc=com', 'is_staff': 'cn=dev,ou=group,dc=example,dc=example,dc=com', 'is_superuser': 'cn=dev,ou=group,dc=example,dc=example,dc=com', } AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=people,dc=example,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)' ) AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_ALWAYS_UPDATE_USER = True Version django-auth-ldap==1.2.14 python3 -
Determining IsAuthenticated in DRF Using DRF-JWT to retrieve a list testing with Postman
So I'm using DRF JWT for my authentication. User submits credentials, and if valid, responds with a JWT that is stored in sessionStorage. Any time the user navigates the protected routes, the JWT /api/auth/refresh to refresh the token if it is still valid. Anyway, moving on from authentication and onto protected routes where data is retrieved based on if the user is IsAuthenticated according to DRF. The problem is I am having difficulty figuring out how to determine IsAuthenticated in DRF without having the user supply credentials again. I should mention right now I am testing with Postman. API URL: /api/help/questions I have the view as: class GetQuestionsAPIView(ListAPIView): queryset = Help.objects.all() serializer_class = GetQuestionsSerializer permission_classes = [IsAuthenticated,] The serializer is: class GetQuestionsSerializer(ModelSerializer): class Meta: model = Help fields = '__all__' def validate(self, data): return data I have a valid token from /api/auth/signin/. I'm trying to pass it on to the /api/help/questions/ route to retrieve the list of questions. GET /api/help/questions/ doesn't work because it wants credentials. Authentication credentials were not provided. GET /api/help/questions/ with Content-type: application/json and 'Authorizationand the token in the header also saysAuthentication credentials were not provided.` Thought maybe it should be POST since I submitting credentials and … -
how to I log the subaddress of HTTP request
I am trying to make a simple webserver. For example, when try to visit website wordpress/mywebsite/thisiswhatIwanttorecord the backend will record the thisiswhatIwanttorecord part in a db or even just txt file and return a standard error page no matter what the suburl is. Does anyone know how to do this in Python Django? Seems like it could be as easy as changing a config file for example in Tomcat. Log all HTTP requests of Tomcat Server? -
Django Model Form: data query from selected primary key
This is my models.py file from django.db import models # Create your models here. class SchoolInfo(models.Model): school_name=models.CharField('School Name', max_length=100) built_date=models.DateTimeField('Built Date') def __str__(self): return self.school_name class TeacherName(models.Model): schoolinfo=models.ForeignKey(SchoolInfo, on_delete=models.CASCADE) teacher_name=models.CharField('Teacher Name', max_length=100) teacher_subject = models.CharField('Subject Name', max_length=100) teacher_contact_number = models.CharField('Phone Number', max_length=100) date_published = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.schoolinfo class Student(models.Model): std_name=models.CharField('Student Name ', max_length=200) CLASS_NAME=( ('6','SIX'), ('7','SEVEN'), ('8','Eight'), ('9','Nine'), ('10','Ten'), ('Ex-10','EX-Ten'), ) std_class_name=models.CharField('Class Name', max_length=7, choices=CLASS_NAME) std_roll_number=models.IntegerField('Roll Number') GENDER=( ('Male','Male'), ('Female','Female'), ) std_gender=models.CharField('Gender', max_length=7, choices=GENDER) GROUP=( ('Science','Science Group'), ('B.Studies','Business Group'), ('Arts and Humatics','Arts and Humatics'), ('General','General'), ) std_group=models.CharField('Group', max_length=17, choices=GROUP) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.std_name class ExaminationName(models.Model): examination_name=models.CharField('Examination Name ', max_length=100) exam_date=models.DateTimeField('Exam Date: ') pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.examination_name class MainSubject(models.Model): main_subject_name = models.CharField('Main Subject Name', max_length=100) main_subject_code=models.DecimalField('Main Subject Code', decimal_places=0, default=0, max_digits=10) subject_full_marks = models.DecimalField('Subject Full Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.main_subject_name class SubjectName(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subject_name=models.CharField('Subject Name', max_length=100) subject_full_marks=models.DecimalField('Subject Full Marks',max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.subject_name class SubjectPart(models.Model): #mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subject_part_name=models.CharField('Subject Part', max_length=100) subject_part_full_marks = models.DecimalField('Full Marks', max_digits=6, decimal_places=0, default=100) subject_part_pass_marks = models.DecimalField('Pass Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) … -
Save Data Without Refreshing The Page
I have a view that refresh the time of a model in database whenever it's called. def data(request): new = Data.objects.filter(user=request.user) if new: new.update(timestamp=timezone.now()) This view is related to the URL, url(r'^data/$', views.data, name='data') So, how can I call this view & update the time in database when user click a URL or a button without refreshing the page? -
Query for Many to Many Fields in Django
I have these classes - class DocumentType(models.Model): type_id = models.AutoField(primary_key=True) name = models.CharField('type name', max_length=200) class MetaData(models.Model): metadata_id = models.AutoField(primary_key = True) name = models.CharField('metadata name', max_length=200, unique=True) description = models.TextField('description') class DocumentTypeMetaData(models.Model): documentType_id = models.ManyToManyField(DocumentType,) metadata_id = models.ManyToManyField(MetaData,) required = models.BooleanField(default=False) For example, a DocumentType value of 'Photo' would have Required Metadata of 'Decade' and 'Orientation'. In the DocumentTypeMetaData class I would like to have a def __str__(self) function that returns something like the following in the admin page - Photo: (Decade, Photo Type) required The format is not critical, I just want to know which metadata is required. Currently, all that is displayed is DocumentTypeMetaData object on the admin page. I am struggling with how to write the queries for this function. Thanks! Mark -
javascript increment value of hidden input and pass it to django view
I am trying to increment the number of inputs in a form when a user clicks on a map. It should pass coordinates of the clicked spot to the input. There are two options to add an input to the form: 1. By clicking on 'Add' button (then we receive an empty input). 2. By clicking on the map (then we receive an input with coordinates). To increment the number of inputs I use a hidden input which stores the value of additional points. When I use the 'Add' button, everything works correctly. I get the empty input and when I reload the page I am able to see just created fields. But when I add this inputs by clicking on a map, after reloading the page I lose all of the inputs. However I see that the value of hidden input was incremented but the fields don't show up on the page. I have tried using ajax to solve it but it didn't work... or I don't know how to use it properly. This is my code: <h2> New Trip: </h2> <form action="{% url 'trips:new' %}" method="post"> {% csrf_token %} <div id="trip-form"> {% for field in trip_form %} {{ … -
OAuth2 Client (Python/Django)
I'm creating a single sign-on (SSO) service using Python, Django, Django Rest Framework and Django OAuth Toolkit (https://github.com/evonove/django-oauth-toolkit). The SSO service will be a central, stand-alone application providing user identity services (granting access to user information as an OAuth2 Protected Resource). Django OAuth Toolkit helps to implement the OAuth2 Authorisation Server. Is there a similarly good quality Django or Python library that can help in implementing the OAuth2 Client (see following diagram snippet taken from https://tools.ietf.org/html/rfc6749#section-1.2)? +--------+ +---------------+ | |--(A)- Authorization Request ->| Resource | | | | Owner | | |<-(B)-- Authorization Grant ---| | | | +---------------+ | | | | +---------------+ | |--(C)-- Authorization Grant -->| Authorization | | Client | | Server | | |<-(D)----- Access Token -------| | | | +---------------+ | | | | +---------------+ | |--(E)----- Access Token ------>| Resource | | | | Server | | |<-(F)--- Protected Resource ---| | +--------+ +---------------+ (I expect the main use case wouldn't be a problem to implement myself, but if a good library provides handling of corner cases, errors, retries and is well tested, then it would be a shame to reinvent.) Thanks, Paul. -
Django: use first name instead of username in login success message
I am using the following view to display a welcome back message when users login successfully. I want to use first name instead of the username attribute in the message, I tried to implement methods such as request.user.get_short_name(), but somehow I could not get it right. Is there a short way for this or I have to define a method inside the class? class LoginView(SuccessMessageMixin, FormView): form_class = AuthenticationForm template_name = 'registration/login.html' success_message = 'Welcome back %(username)s!' -
Django: determine language on a mobile device?
I read on internationalization and localization in the django documentation (https://docs.djangoproject.com/en/1.9/topics/i18n/) - but somehow I missed the point, how Django actually determines the language - and how it would be possible to adapt it's default behaviour. It's about displaying a website on a mobile device in the correct language. I'm on Django 1.9 -
Django template inheritance not rendered
I'm following the django docs on template inheritance, and I think my code is correct but it doesn't work, the template people_index.html is not rendered. I have three templates, base.html, base_index.html, people_index.html, each one inherited on the previous. Like this: base.html {% include "base/header.html" %} <body> {% include "base/navbar.html" %} {% include 'base/messages.html' %} <div class="container container-content"> {% block content %} {% endblock content %} </div><!-- /.container --> </body> </html> base_index.html {% extends "base/base.html" %} <h3 class="snps-slim-font">Index de {{ index_of }}</h3> <div class="input-group"> <span class="input-group-addon">Filtrar</span> <input id="filter" type="text" class="form-control" placeholder="Ingrese un criterio"> </div> <table class="table table-hover table-condensed"> {% block table_content %} {% endblock table_content %} </table> And finally people_index.html {% extends "base/base_index.html" %} {% block table_content %} <thead> <tr> <th class="snps-slim-font">APELLIDOS</th> <th class="snps-slim-font">NOMBRES</th> <th class="snps-slim-font">DOCUMENTO</th> <th class="snps-slim-font">CUIL</th> <th class="snps-slim-font">ACCIONES</th> </tr> </thead> <tbody class="searchable"> {% for person in object_list %} <tr> <td>{{ person.last_names }}</td> <td>{{ person.first_names }}</td> <td>{{ person.document_number }}</td> <td>{{ person.cuil_number }}</td> <td class="snps-text-align-center"> <a href="{% url 'people:person-detail' person.id %}" title="ver perfil"><i class="glyphicon glyphicon-eye-open" aria-hidden="true"></i></a>&nbsp;<a href="{% url 'people:person-update' person.id %}" title="editar perfil"> <i class="glyphicon glyphicon-edit" aria-hidden="true"></i></a></td> </tr> {% endfor %} </tbody> {% endblock table_content %} The view if someone asks: class PersonListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): model = Person template_name = 'people/people_index.html' … -
Django: Messaging
Here's the model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) I wants to order the Users based upon who sent a message to request.user & to whom request.user sent a message most recently! As we see on social networks. This is what I tried, users = User.objects.filter(Q(sender__receiver=request.user) | Q(receiver__sender=request.user)).annotate(Max('receiver')).order_by('-receiver__max') This code is working fine only when request.user sends someone a message(It's re-orders it's name & place it to the top). But, It's not changing the order of users in case if someone sends a message to request.user. I also tried, users = Message.objects.filter(sender=request.user, receiver=request.user).order_by("created_at") But, I could't filter out the distinct users. It's showing equal number of users as messages. Also, I have to use {{ users.sender }} OR {{ users.receiver }} in order to print the users name which is a problem itself in case of ordering & distinct users. How can I fix this problem? -
Django - filter with multiple para
I am trying to create a filter with multiple parameters. I found the first answer of this link is useful, so took his idea. However, I don't know how to create a string variable containing all values.Here is my code: {% with amount_comments|to_string+","+limit_amount_comments|to_string as args %} {% if page_nr|page_not_over_amount:args %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} {% endwith %} and this is to_string filter: @register.filter(name='to_string') def to_string(value): return str(value) then page_not_over_amount filter using that args: @register.filter(name='page_not_over_amount') def page_not_over_amount(page_nr, args): if args is None: return False else: arg_list = [arg.strip() for arg in args.split(',')] comment_amount = arg_list[0] comment_limit = arg_list[1] if page_nr*comment_limit < comment_amount-comment_limit: return True else: return False But I get this exception: Could not parse some characters: amount_comments|to_string|+","+limit_amount_comments||to_string Thanks in advance! -
Running python bot in django background
I've got a django project with simple form to take users details in. I want to use python bot running in the background and constantly checking django database for any changes. Is it Celery the right tool for this job? Any other solution? Thank you -
Write to elastic search from inside Django view
I'm trying to sync a local SQLite database-entry with an elastic search index. Here is the view: def sync_greasebook(request, model_id): data = create_json(model_id) es = Elasticsearch(hosts=[{'host': 'my_host', 'port': '9200'}]) res = es.index(index='my_index', doc_type='my_doctype', id=model_id, body=data) return redirect('/') And error at line 4: ConnectionError(: Failed to establish a new connection: getaddrinfo() argument 2 must be integer or string) caused by: NewConnectionError(: Failed to establish a new connection: getaddrinfo() argument 2 must be integer or string) The put to elastic search works normally. Am I missing knowledge that doesn't allow this behavior inside Django? Any help would be much appreciated -
momentJs with class not work correctly django
hi i have a difficulty with moment.js first entry it good but after i have invalid date . I call my data in front with {{....}} : {% for lastRequest in listLastRequeteClient %} <!-- en attente --> <li class="collection-item"> <span class="title">{{ lastRequest.categoryName }}</span> <div class="row"> <div class="col s5 ultra-small leftalign "style="padding-left: 0px"> {{ lastRequest.nameRequest }} </div> <div class="col s3 ultra-small center-align"> <span class="countDateTime">{{ lastRequest.dateRequest }}</span> </div> <div class="col s4 ultra-small "> {% if lastRequest.isWaitingWorking == True %} <span class="new badge orange" data-badge-caption="En attente"></span> {% elif lastRequest.isWaitingWorking == True %} <span class="new badge blue" data-badge-caption="En cours"></span> {% elif lastRequest.isFinish == True %} <span class="new badge" data-badge-caption="Effectué"></span> {% endif %} </div> </div> </li> % endfor %} and my Javascript : function countDateEntry() { $(".countDateTime").each(function() { // get it Oct. 27, 2017, 2:27 p.m var dateEntry = $(this).text(); console.log(dateEntry); // format it var delSpace = dateEntry.replace(/ /gi, ""); var delVir = delSpace.replace(/,/gi, ""); var delDoublePoint = delVir.replace(/:/gi, ""); var FinishSerialize = delDoublePoint.replace(/\./gi, ""); console.log(FinishSerialize); // test is date is valid console.log(moment(FinishSerialize, 'MMMDYYYYhma').isValid()); var formatMomentDate = moment(FinishSerialize, 'MMMDYYYYhma').fromNow(); console.log(formatMomentDate); //$(this).text(formatMomentDate); }); } but show my console.log invalid date : First entry it is ok after it is bad . Oct. 27, 2017, 2:27 p.m. … -
DateInput in django admin form
I'm editing the form of my app admin section. model.py class Friend(models.Model): id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) genre = models.CharField(max_length=1, choices=(("M", "Male"), ("F", "Famale"))) birth_date = models.DateField() admin.py class FriendAdmin(admin.ModelAdmin): change_form_template = 'admin/change_form.html' change_list_template = 'admin/change_list.html' admin.site.register(Friend, FriendAdmin) form.py class FriendForm(admin.ModelAdmin): form = Friend fields = ('birth_date',) widgets = {'birth_date': forms.DateInput(attrs={'class': 'form-control'})} I expect that my form contains only the "birth_date" field and that it has the "form-control" class and the "DateInput" type. Nevertheless, my form contains all the fields and the "birth_date" is a simple text field. What am I doing wrong? P.S. I've imported bootstrap, bootstrap-daterangepicker, jquery and moment library and I've added this code to my change_form.html page: <script type="text/javascript"> $('.datepicker').datepicker(); </script> -
Use Django proxy model class when obtaining ManyToMany fields through related_name field
Is there a way to force a related ManyToMany field to use a Proxy class instead of the model that is associated with it? I have the following code: # Code in models.py class Member(models.Model): username = models.CharField(max_length=100) class BaseGroup(models.Model): member = models.ManyToManyField('Member', related_name='groups') class Group(BaseGroup): class Meta: proxy = True def some_method(self): return 'something' # Code in view: member = Member.objects.first() group = member.groups.first() print group.some_method() The code above throws the error: "Group object has no attribute 'some_method'", because the "member.groups.first()" line returns a "BaseGroup" instead of the proxy "Group", therefore I cannot use the methods that I implemented on the proxy class. Is there a way to inform the ManyToManyField (or the query) to return the proxy class instead of the base model? -
Does Jupyter support 'read-only' notebooks?
My team is currently developing a fairly quick clustering job using Pandas for business analysts. We're planning on hosting a local server where the end user can input a few parameters to be used during the routine execution, which will access an internal database and then return a CSV file. A Jupyter server would be ideal for us, but the problem is that we can't have the user being able to edit the underlying code - all he needs to do is supply the parameters and start job execution. Converting it to HMTL, I think, turns everything static and means we can't delived updated data on demand. Plan B is just making a small django app but I'm wondering if there's a way to accomplish what I need with Jupyter itself, or else if there's any better alternative for similar use cases? We don't even plan to display any widgets, just provide the user with the raw data output. thanks in advance -
django-parler translations for abstract model
My django app must be translatable, static pages and models too. For translating models I'm using django-parler app. This works fine, but for simple models, I mean, models that doesn't inherits from an abstract model class. Let's say that we have a Vehicle abstract model class Vehicle(TranslatableModel): translations = TranslatedFields( description=models.CharField(max_length=100) ) class Meta: abstract = True and a child model which is Car: class Car(Vehicle) """...""" This raised me this error: TypeError: Can't create TranslatedFieldsModel for abstract class Vehicle. I'd like still using django model inheritance. So, what can I do for translating my models using django-parler, it support translations for abstract models or I'll need to use another app to achieve this, in that case any suggestion on any? -
Upgrade issues in django from version 1.7.9 to 1.11.6, unknown command runfcgi
I am working on updating django from 1.7.9 to 1.11.6. While using 1.7.9 we use runfcgi on our production server. Looks like runfcgi does not exist in 1.11.6. When i do $ python manage.py help runfcgi does not show up. For someone who uses runfcgi, what is the right path forward for 1.11.6 ? Any recommendation / pointers would be helpful. -
Wagtail proper way to add settings to a stream block
say we have a stream block as: class CarouselStreamBlock(StreamBlock): image = StructBlock([ ('file', ImageChooserBlock()), ('caption', RichTextBlock( classname='caption' )), ]) We have a scenario that we want to give the admin editor the ability of setting each carousel's width, height, bgcolor etc... I have tried to add that settings as another struct block named to the carousel itself with a max_length of 1. class CarouselStreamBlock(StreamBlock): settings = StructBlock([ ('align', blocks.ChoiceBlock(choices=[('center', 'Center'), ('right', 'Right'), ('left', 'Left'), ], default='center', max_length=10) ), ('width', blocks.IntegerBlock(required=False ) ), ('background_color', blocks.CharBlock(max_length=10, required=False)) ], icon='cog' ) image = StructBlock([ ('file', ImageChooserBlock()), ('caption', RichTextBlock( classname='caption' )), ]) But I am not satisfied with this way. Is there a better way of doing this? -
What is best way to return object permission with instance using Django Rest Framework and django-guardian
I'm using Django Rest Framework and django-guardian (for per object permissions), what is best way to return object permission with instance. For example now request "/api/v1/objects/" returns: { "id":0, "category": "string", "name": "string", "address": "string", } but I want return object with permissions: { "id":0, "category": "string", "name": "string", "address": "string", "permissions": { "change": true, "delete": true } } this would be useful, for example, if the user does not have the right to delete the object, on the frontend do not display the delete button. Below is project structure: #Model class Object(models.Model): owner = models.ForeignKey(User) category = models.ForeignKey(Category, null=True, default=None) name = models.CharField(max_length=255) address = models.CharField(max_length=255, default='') #Serializer class ObjectSerializer(ModelSerializer): is_folder = BooleanField(read_only=True) class Meta: model = Object fields = ('id', 'category', 'is_folder', 'name', 'address') #ViewSet class ObjectsViewSet(BaseViewSet, RetrieveModelMixin, ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin): queryset = Object.objects serializer_class = ObjectSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, ObjectPermission) def get_queryset(self): queryset = super(ObjectsViewSet, self).get_queryset() return queryset.filter(owner=self.request.user) #Permission class ObjectPermission(permissions.BasePermission): def has_permission(self, request, view): if request.method in ['GET']: return request.user.has_perm('view_object') if request.method in ['POST']: return request.user.has_perm('add_object') if request.method in ['PUT', 'PATCH']: return request.user.has_perm('change_object') if request.method in ['DELETE']: return request.user.has_perm('delete_object') return False def has_object_permission(self, request, view, obj): if request.method in ['GET']: return request.user.has_perm('view_object', obj) if request.method … -
Serializer to filter relations base on arbitrary attributes
I'm new to DRF, what I have works but I am interested if there is a better way to do it: I have a PrimaryKeyRelatedField serializer to enumerate a many-to-many relation. It works fine, i.e.: mobile_forms = serializers.PrimaryKeyRelatedField( allow_empty=True, many=True, queryset=MobileForm.objects.all(), required=False) My question is that for this relation, I always only want to return related items that have their deleted status set to False. In order to achieve this I am doing: active_mobile_forms = serializers.SerializerMethodField() def get_active_mobile_forms(self, obj): return obj.mobile_forms.filter(Q(deleted=False)).values_list('pk',flat=True) It seems wrong to me to have to create a separate serializer to filter the objects returned. Based on my understanding of the queryset argument to the PrimaryKeyRelatedField is used to validate input, so it is not appropriate to filter here. Basically, I'm interested in the best practice for filtering a PrimaryKeyRelatedField relation when objects are returned via a serializer. Any insight would be appreciated.