Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pagination by date (week)
I am making a website that displays this week's soccer games from the day you open the website to six days later (current week), and i want to paginate by date. example <previous> <19 feb - 25 feb> <next> then when i press next <previous> <26 feb - 4 march> <next> in views.py. matches is a list of dictionaries, each dictionary is a single game that contains the date of the game and other info and its sorted by date def home(request): start = datetime.now().date() end = today + timedelta(6) matches = request_games(today, after_week) return render(request, "sporty/home.html",{ "matches": matches, "start" : start, "end": end }) in home.html {% for match in matches %} //match info {% endfor %} -
Django Logging: Output all Logger messages to a file
I'm trying to do some debugging and cannot figure out how I can get all the usual server output that I would normally get on a development server. Here's my logging file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'catch_all_logger': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'somelogfile.log'), }, }, 'loggers': { 'django': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.server': { 'handlers': ['catch_all_logger'], 'level': 'DEBUG', 'propagate': True, }, 'django.security.DisallowedHost': { 'handlers': ['catch_all_logger'], 'propagate': True, }, 'django.security.csrf': { 'handlers': ['catch_all_logger'], 'propagate': True, }, }, } When I do cat somelogfile.log, I get almost useless information: Bad request: /url/where/bad/request However, the documentation says that django.server for instance will show status code and a message with it as extra context on the INFO level with HTTP 5XX as ERROR and 4XX as WARNING. Do I have the logging level setup incorrectly? Would love some guidance as I'm puzzled. -
Multiple Values into initial form data
I am attempting to render a form which will have certain fields prefilled based on the Primary Key. Im currently only able to successfully prefill one field (Project). Do I have to define all the other fields in my view? This is my Model class Document(models.Model): DOC_TYPE = ( ('Proposal', 'Proposal'), ('Invoice', 'Invoice'), ('Receipt', 'Receipt'), ('Other', 'Other') ) docName = models.CharField("Document Name", max_length=1000, null=True) docType = models.CharField("Document Type", max_length=10, null = True, choices=DOC_TYPE) company = models.ForeignKey('project.Company', on_delete=models.PROTECT, blank = True, null = True) customer = customer = models.ForeignKey('customer.Customer', on_delete=models.PROTECT, null = True) project = models.ForeignKey('project.Project', on_delete=models.PROTECT, blank = True, null = True) docFile = models.FileField("Document", upload_to='newdocuments/') note = models.TextField("Note About Document", blank = True, null = True) dateUpload = models.DateTimeField(auto_now_add=True) This is my View def ProjectAddDocument(request, pk): project = Project.objects.get(id=pk) form = ProjectAddDocumentForm(initial={'project':pk}) if request.method == 'POST': form = ProjectAddDocumentForm(request.POST) if form.is_valid(): form.save() return redirect('file_list') context = {'form':form} return render(request, 'project/adddocument.html', context) This is my URL path('adddocument/<int:pk>/', views.ProjectAddDocument, name='proj_document'), This is my Form class ProjectAddDocumentForm(ModelForm): class Meta: model = Document fields = ['docName', 'docType', 'company', 'customer', 'project', 'note', 'docFile'] -
How to validate and redirect on fail in CreateView get
I am trying to do some sanity checks in a CreateView get request and want to redirect user to a different URL in case the sanity checks fail. How can I achieve this? For example: class JobCreateView(LoginRequiredMixin, CreateView): model = Job form_class = JobFormClass # This does not let me redirect on return since a dictionary return is expected and redirect is not acceptable def get_context_data(self, **kwargs): if not self.request.user.is_superuser: messages.add_message( self.request, messages.ERROR, _("You are not authorized! Bugger off!") ) return redirect("home") # The user is good to proceed return super().get_context_data(**kwargs) This gives me back the following error: context must be a dict rather than HttpResponseRedirect. I am using get_context_data because I don't know what to use to be honest. Feel free to suggest something better. My use case in not really a super user check, that just felt like a better example -
Best practice for saving new model instance in Django Rest Framework
I'm new to DRF and I can't wrap my head around where to save new model instances when I POST to my endpoints. I need to overwrite my def create() method because I'm managing nested objects in my queries. I've noticed that I can save new instances from the model Serializer ( def create(self, validated_data)) but also from the associated class view ( def create(self, request)) What's the best practice here? I'm pretty sure I'm confusing major concepts, please indulge me! -
I try to build Follow system, I have error when i try to get the pk of the vested account
I try to build follow system in Django, My code Filed when I try to get the pk of the current vested account which I try follow them The Error message NoReverseMatch at /account/3/ Reverse for 'add-follower' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/follower/(?P[0-9]+)/add$'] my models class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="follow") My views class AddFollwers(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): account = Account.objects.get(pk=pk) account.following.add(request.user) return redirect('account', pk=account.pk) The urls urlpatterns = [ path('<int:user_id>/', account_view, name="view"), path('follower/<int:pk>/add', AddFollwers.as_view(), name='add-follower'),] The Template <form action="{% url 'account:add-follower' pk=pk%}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-success">Follow</button> </form> -
Heroku Django APScheduler not releasing memory after job completes
I have a django site that is running some heavy computational stuff that is scheduled with APScheduler hosted on Heroku. Everything is working as intended however Heroku is throwing error "Error R14 (Memory quota exceeded)" I have found other posts similar to this, link, issue but they are outdated and I haven't been able to get them to work. My code is listed below. I want this to run Mon-Fri between the hours of 800 and 1600. I am using heroku's PostgreSQL database. Eventually memory usage will get so high it will crash and restart. sched = BlockingScheduler( executors={ 'threadpool': ThreadPoolExecutor(max_workers=1), 'processpool': ProcessPoolExecutor(max_workers=1) } ) @sched.scheduled_job('cron', minute='*/30', day_of_week='mon-fri', hour='8-18', max_instances=1, id="server", executor='threadpool') def _server(): print('Start server') server = Server() server.get_stocks() del server gc.collect() sched.start() I know this is leaking memory because this clock.py memory usage before the server starts. This is after the server has done its' work and rests. If anyone can point me in the right direction I am open to trying anything. Thank you in advanced. -
ModelForm and using a specific queryset
I am creating a form for a model, one of the fields of the model is a ForeignKey. I want the options of the ForeignKey to be the ones related to that instance of the model. to make it clearer, here is some code: views.py def AddOrderDetail(request, pk): Product = Products.objects.get(ProductID=pk) order = Orders.objects.last() locations = Product.productqtys_set.values_list('Sublocation', flat=True).distinct() form = OrderDetailForm(request.POST or None) forms.py class OrderDetailForm(forms.ModelForm): class Meta: model = OrderDetails fields = ( ... 'Location', ... ) now I want the data retrieved from the query that I am performing in the view: locations = Product.productqtys_set.values_list('Sublocation', flat=True).distinct() to be the data that the user can select from while selecting the location of the OrderDetail. Moreover, I have another problem. I want to initialize some fields, I tried using the initial={} while defining the form in view, as shown below: form = OrderDetailForm(request.POST or None, initial={"ProductCode": Product, "OrderID": order, "Location": locations}) but when I do that I get the following error, 'OrderDetailForm' object has no attribute 'ProductCode'. I tried another way in the Function in the view.py file which is the following: form.fields['ProductCode'].initial = Product form.fields['OrderID'].initial = order but sadly, I still get the same error 'OrderDetailForm' object has no … -
Changing the import statement of a 3rd party app
I've a django application where I'm importing a 3rd party app. The app is written for python3, however my application environment is python 2.7 and django 1.11.16 . The 3rd party app works very well with python2 except for one line in the beginning. One of the file of the 3rd party app contains this: from urllib.parse import urlencode, quote . If I change this line to from urllib import urlencode, quote in the virtualenv, it works perfectly, however this is a very bad solution. I don't want to fork the whole application, but is there any other way for the workaround? -
Test webhook error: TLS failure - Stripe connection problem with Django API on Google App Engine
I try to send a test event to a webhook endpoint to my Django Stripe endpoint path('stripe/', views.StripeView) however I get an error Test webhook error: TLS failure. There is no more information and just link to ssllabs when my website has B overall rating. When I was using local testing with stripe listen --forward-to localhost:8007/stripe/ everything was working properly. All my certificates which are set on Google App Engine with flexible environment seems to be working properly. I thought that maybe the problem is associated with CSRF therefore I removed GenericAPIView and I added decorator @csrf_exempt in accordance to the Stripe documentation however it still does not work. Does anyone have an idea how can I solve this problem? @require_POST @csrf_exempt def StripeView(request): # serializer_class = StripeSerializer # def post(self, request): payload = request.body try: sig_header = request.META['HTTP_STRIPE_SIGNATURE'] except: return HttpResponse(status=400) ... -
How to make choosing group in admin.py mandatory?
In admin.py, I am adding groups as fieldset to one of my model. fieldsets = ( (None, {'fields': ('username', 'first_name', 'last_name', 'email',)}), ('Permissions', {'fields': ('groups',)}), ) The issue I have is that I do not know how to make choosing them mandatory - user can be in each or both of them, but cannot be blank. How can I force it, to ensure that user added will be in a group? -
Django migration is not changing database in AWS Elastic Beanstalk
I have deployed my Djnago app using AWS Elastic Beanstalk. I have added some data and everything was working fine. Then I have increased max_length of one of the CharField in model.py. I have deployed the app again using 'eb deploy' command. But it did not increase the field length in database. If I try to add subject_id greater than 10, I get this error: django.db.utils.DataError: value too long for type character varying(10) Model.py: class Subject(models.Model): #subject_id = models.CharField(max_length=10, blank=True) subject_id = models.CharField(max_length=50, blank=True) 0001_initial.py: #Generated by Django 3.0.4 on 2021-02-18 18:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('accounts', '0001_initial'),] operations = [ migrations.CreateModel( name='Subject', fields=[('subject_id', models.CharField(blank=True, max_length=50)),],),] I have added migration command in .ebextensions/django_build.config file. The 0001_initial.py file inside migration folder shows the changes. But it is not updated in the database(AWS RDS postgresql). I have checked django_migrations table in postgresql database. It's showing the last migration happened when I first created the instance. I need to change subject_id field length of Subject model in existing database. Any help will be appreciated. .ebextensions/django_build.config: container_commands: 01_create_log_folder: command: "mkdir -p log && chown webapp:webapp -R log" 02_source_env: command: "source /etc/profile.d/sh.local" leader_only: true … -
Got AttributeError when attempting to get a value for field `content_object` on serializer `ProjectActionSerializer`
The serializer field might be named incorrectly and not match any attribute or key on the Activity instance. Original exception text was: 'Activity' object has no attribute 'content_object'. These are the Serializers I used class ProjectVoteSerializer(serializers.ModelSerializer): class Meta: model = Activity fields = ( 'voter', 'created', 'id', ) class ProjectActionSerializer(serializers.ModelSerializer): content_object = GenericRelatedField({ Activity: ProjectVoteSerializer(many=False) }) class Meta: model = ActivityObject fields = ( 'id', 'content_object', ) These are the models: class ActivityObject(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Activity(models.Model): project = models.OneToOneField(Project, on_delete=models.CASCADE, related_name='vote_project') comment = models.OneToOneField(ProjectComment, on_delete=models.CASCADE, related_name='vote_comment',null=True) voter = models.ForeignKey(User, on_delete=models.CASCADE, related_name='voted_by') UP_VOTE = 'U' DOWN_VOTE = 'D' ACTIVITY_TYPES = ( (UP_VOTE, 'Up Vote'), (DOWN_VOTE, 'Down Vote'), ) activity_type = models.CharField(max_length=1, choices=ACTIVITY_TYPES) created = models.DateTimeField(editable=False, db_index=True) modified = models.DateTimeField(db_index=True, default=timezone.now) activity = GenericRelation(ActivityObject) class Meta: unique_together = ['project', 'voter'] API views.py print(project_votes) This is the output data before serializing <QuerySet [<Activity: Activity object (12)>, <Activity: Activity object (10)>]> Getting error at this line when serializing project_votes_serializer = ProjectActionSerializer(project_votes, many=True, context={"request": request}) -
How to Preserve White Space and line breaks in Django?
I am making a project where I want to display a user's code. I am using Django's forms. But when I post that form, the form doesn't preserve the white space and the line breaks. Can you please help me? # this is my form class VigenereCipherDiscussForm(forms.ModelForm): class Meta: model = VigenereCipherDiscuss fields = ['text', 'share'] widgets = { "text": forms.Textarea(attrs={"class":"form-control", "rows":4}), "share": forms.Textarea(attrs={"class":"form-control", "rows":5, "placeholder": "Put in your cipher text or code in here to share with others"}) } # (stackoverflow preserves the line breaks, the "class Meta" is indented nicely) If i have this code: x = 2 if x == 2: return "2" else: return None # I want this code to be outputted in the form the way it is right now! But django gives me x=2 if x==2: return "2" else return None -
Queryset filter by variable that's in another queryset
I am trying to filter a queryset by a variable in another queryset that hasn't been set yet. I know it sounds confusing so let me show you. Views.py def ViewThreadView(request, thread): posts = Post.objects.filter(post_thread=thread) thread = Thread.objects.get(pk=thread) form_class = QuickReplyForm thread_name = thread.name return render(request, 'thread/viewthread.html', {'thread': thread, 'posts': posts, 'thread_name': thread_name}) As of now, if I want to access the post author in the template, I'd do this {% for post in posts %} post.author {% endfor %} My question is, how do I access the tables of post.author. So if I want to filter how many posts that author has, I want to do something like user_posts = Post.objects.get(author=post.author). But that can't work in the views because "posts" is a queryset and not a value. How can I do this? -
Field 'id' expected a number but got
I try to build follow system in Django, it showed Field 'id' expected a number but got ''. how can i get the pk of the current profile user which I vested. This my view def follow_unfollow_profile(request, **kwargs): if request.method == 'POST': my_account = Account.objects.get(username=request.user) pk = request.POST.get('account_pk') obj = Account.objects.get(pk=pk) if obj.username in my_account.following.all(): my_account.following.remove(obj.username) else: my_account.following.add(obj.username) return redirect(request.META.get('HTTP_REFERER')) This is the urls path('<int:user_id>/', account_view, name="view"), path('follow/', follow_unfollow_profile, name='follow-unfollow-view'), The form Which I try to get the object pk <form action="{% url 'account:follow-unfollow-view'%}" method="POST"> {% csrf_token %} <input type="hidden" name="account_pk" value={{account.pk}}> <button type="submit" class="btn btn-success">Follow</button> </form> -
Why Validation Error is not showing in forms
I am building a Blog App and i am stuck on a problem. The Problem Validation Error is not raising. What i am trying to do I made a feature that if user select past time in DateTimeField in Browser Page then a Validation error will be shown. BUT the error is showing. forms.py from django.core.exceptions import ValidationError class PostForm(forms.ModelForm): date_added = forms.DateTimeField(initial=timezone.now) def clean_date(self): date_added = self.cleaned_data['date_added'] if date_added.date() < datetime.date_added.today(): raise forms.ValidationError("The date cannot be in the past!") return date_added views.py def new__blog_post(request,user_id): if request.method != 'POST': form = PostForm() else: form = PostForm(request.POST,request.FILES) new_post = form.save() new_post.post_owner = request.user new_post.save() return redirect('mains:posts',user_id=user_id) context = {'form':form,'posts':posts} return render(request, 'new_blog_post.html', context) My other question related to this , Question I don't know what i am doing wrong in this. Any help would be Appreciated. Thank You in Advance. -
pylance(reportMissingModuleSource) error in VS Code while using Django
https://github.com/microsoft/pyright/blob/master/docs/configuration.md" The error directs to this GitHub readme, no clarification, and no solution is given for this error The Error Message Shown I reinstall python and Django again still not working. What should I do? -
AttributeError at /admin/imports/import/add: 'NoneType' object has no attribute 'attname' (Django)
I have used embedded approach for constructing django models namely productDetails, ShipmentDetails , Customer and Import. I m using Pycharm IDE and no sql database. This is models.py file from djongo import models from django import forms # Create your models here. class ProductDetail(models.Model): product_name = models.CharField(max_length=70, blank=False) quantity = models.IntegerField(blank=False) net_weight = models.FloatField(max_length=70, default=False) class Meta: abstract = True class ProductDetailForm(forms.ModelForm): class Meta: model = ProductDetail fields = ( 'product_name', 'quantity', 'net_weight' ) class ShipmentDetails(models.Model): bl_no = models.CharField(max_length=100) ship_date = models.DateField() vessel_name = models.CharField(max_length=70) vessel_type = models.CharField(max_length=70) load = models.FloatField() class Meta: abstract = True class ShipmentDetailsForm(forms.ModelForm): class Meta: model = ShipmentDetails fields = ( 'bl_no', 'ship_date', 'vessel_name', 'vessel_type', 'load' ) class Customer(models.Model): customer_name = models.CharField(max_length=70, default="anything", null=True) class Meta: abstract = True class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'customer_name', ) class Import(models.Model): shipmentDetails = models.EmbeddedField( model_container=ShipmentDetails, model_form_class=ShipmentDetailsForm ) exporter = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) importer = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) indenter = models.EmbeddedField( model_container=Customer, model_form_class=CustomerForm ) productDetails = models.EmbeddedField( model_container=ProductDetail, model_form_class=ProductDetailForm ) Payment_options = ( ('C', 'Cash'), ('CD', 'Card'), ) Status_options = ( ('S', 'Signed'), ('US', 'Unsigned'), ('P', 'Pending'), ) dealDate = models.DateField() departureDate = models.DateField() arrivalDate = models.DateField() paymentTerm = models.IntegerField(choices=Payment_options) status = … -
pycharm does not accept html file
I use the Django authentication system, and for this I created a template, named this file login.html and in the registration directory. I already had a file with this name (login.html), and then I created this file and deleted the previous file, now pycharm does not accept the new file as html, and because of this I can not put Django template in this file and Leave a link. And you know you can't rename the file, because then the Django template authentication system can't find it. And now I do not know what to do. What can I do to make pycharm accept this as html? -
Is it possible to write down django project on colab?
I am a beginner. I have started Django project in Google Colab. But all time I am facing local host connectivity issue after execution of python manage.py runserver. Please help me. -
Django Web App running on local Debian 10 but failing on Azure
I can run my web app on my local machine - no errors. But when porting the directory strcture to Azure, I get the ModuleNotFoundError: No module named 'django'. Here is what I did: My app is publicly available on GitHub. The app runs in a virtual environment (called deploydjango). That is reflected in the tree structure of the repo. I ensured that Python version was correct (3.8 as on my local machine). I posted the code to Azure (using the Azure extension of Visual Studio Code). When browsing to the web app URL, I get the error message: :( Application Error If you are the application administrator, you can access the diagnostic resources. That takes me to Diagnose and solve problems on Azure page for the Web App Service. Here I find Availability and Performance. Herein the tab "Web App Dow" is found. Under Application Logs I am advised, that: Application logs from instance: lw0sdlwk00016P contain an error or a warning Clicking More info, I get a log telling me: 2021-02-18T12:02:07.203140817Z [2021-02-18 12:02:07 +0000] [37] [ERROR] Exception in worker process 2021-02-18T12:02:07.203175518Z Traceback (most recent call last): 2021-02-18T12:02:07.203181819Z File "/opt/python/3.8.6/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-02-18T12:02:07.203186419Z worker.init_process() 2021-02-18T12:02:07.203190419Z File "/opt/python/3.8.6/lib/python3.8/site-packages/gunicorn/workers/base.py", line … -
How buid a django architecture for multiple user interfaces working with the same data
(don't judge strictly pls, this is my first question) I have a model like Company. Two user interfaces: an administrator's cabinet(Cabinet) (not native django) and an interface for ordinary users (Main). Let's use the example of a list of companies. On the Cabinet, I want to show the companies that he can edit, on the Main - all public companies. I doubt for how to properly organize this moment on the backend. What I think? Make the base class CompanyListService in the service layer, write general logic in it, and separately each interface has its own class: CabinetCompanyListService(CompanyListService), MainCompanyListService(CompanyListService) Pass the model manager to it during initialization(Company is django Model): class CompanyListService: def __init__(self, manager=Company.main_manager): self.manager = manager then I can get here all the data options needed for the front class MainCompanyListService(CompanyListService): def get_companies(self): return self.manager.get_publish_companies() class CabinetCompanyListService(CompanyListService): def get_companies(self): return self.manager.get_available_companies_where_user_is_staff() class MainManager(TreeManager): def get_available_companies(self): """Includes blocked, rejected etc... Companies that actually exist and are available at least to the creator, admin""" return self.get_queryset().exclude(status='deleted') def get_publish_companies(self): return self.get_queryset(status='active') def get_available_companies_where_user_is_staff(self, user): """Companies where user has CompanyManager role""" self.get_available_companies().filter(company_company_managers__user=user) Not sure if this is good architecture. In general, I don't have enough experience to understand how good or bad … -
How to Create a User in nested serializer using generic ListCreateAPIView?
I am working on genericAPIViews in DRF. I am using a built in user model with UserProfile model having one to one relation with it. But I am unable to create user due to nested serializer. My question is that how I can create my built in User model and Profile User model at the same time as UserProfile model is nested in User model.Here is my code: Models.py USER_CHOICE = ( ('SS', 'SS'), ('SP', 'SP') ) LOGIN_TYPE = ( ('Local', 'Local'), ('Facebook', 'Facebook'), ('Google', 'Google') ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cell_phone = models.CharField(max_length=15, blank=True, default="", null=True) country = models.CharField(max_length=50, blank=True, default="", null=True) state = models.CharField(max_length=50, blank=True, default="", null=True) profile_image = models.FileField(upload_to='user_images/', default='', blank=True) postal_code = models.CharField(max_length=50, blank=True, default="", null=True) registration_id = models.CharField(max_length=200, null=True, blank=True, default=None) active = models.BooleanField(default=True) # roles = models.ForeignKey(Role, null=True, on_delete=models.CASCADE, related_name='role', blank=True) user_type = models.CharField(max_length=50, choices=USER_CHOICE, null=True, blank=True) login_type = models.CharField(max_length=40, choices=LOGIN_TYPE, default='local') reset_pass = models.BooleanField(default=False) confirmed_email = models.BooleanField(default=False) remember_me = models.BooleanField(default=False) reset_code = models.CharField(max_length=200, null=True, blank=True, default="") reset_code_time = models.DateTimeField(auto_now_add=True, blank=True) longitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) latitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) r_code = models.CharField(max_length=15, null=True, blank=True) refer_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_refer") referred = models.ManyToManyField(User, related_name="user_referred", null=True, blank=True) otp = … -
Update related object with rest framework
Given the following models:- class User(models.Model): first_name = models.CharField() etc. class Relation(models.Model): user = models.ForeignKey(User, related_name='relations', on_delete=models.CASCADE) is_primary = models.BooleanField(default=False) how would I go about creating a serializer and view that can be used to set a particular user's relation to be the primary one? I was hoping to be able to POST something like:- { 'relation': 6 } and for that to find the Relation with ID of 6 and set it's is_primary to True but I can't figure out how to do it. I've tried the serializer like this:- class SetRelationSerializer(serializers.ModelSerializer): relation = serializers.PrimaryKeyRelatedField(queryset=Relation.objects.all()) class Meta: model = User fields = ['relation'] and a viewset action like this:- @action(['post'], detail=False) def set_primary_relation(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) // what do I need in here? return Response(status=status.HTTP_204_NO_CONTENT) Is the only way to do something like:- self.request.user.relations.get(id=serializer.data['relation']).update(is_primary=True) ? Because that seems a bit unpleasant to me. Surely there's a better way?