Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx: how to reroute subdomains to Django?
How to catch and reroute subdomains internally in Nginx to Django's URL dispatcher? api.project.org/ -> /api/ www.project.org/ -> /www/ project.org/ -> /www/ I want to get something like this: location api.project.org/ { uwsgi_pass 127.0.0.1:8080/api/; } -
How to get all related data using django signal post_save and save it to another table
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. this is my code in models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels) if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) I hope the title and the picture is enough to understand what im trying to say if not, im sorry! UPDATE this … -
Django CheckboxSelectMultiple allow none
I need some help, I'm using a forms.ModelMultipleChoiceField to represent a ManyToManyField, rendered as a widget=forms.CheckboxSelectMultiple. All work perfect but the problem come when none checkbox was selected, it raises a validationError when ask form.is_valid(). I need Select None, One, Many or All. It is any way to allow blank or empty? Thanks!! -
How to create custom search Mixin?
I have a ListView which utilizes the q GET parameter for a search box. The problem is that I am not following the DRY principle as I have other search boxes which are similar. Therefore I would like to make a custom SearchMixin to handle the search queries. My ListView previously looked like this: class MemoListView(LoginRequiredMixin, ListView): """ Display a list of memos. **Context** ``Memo`` An instance of :model:`memos.Memo` **Template:** :template:`memos/memos.html` """ model = Memo template_name = 'memos/memos.html' context_object_name = 'memos' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['memo_list'] = Memo.objects.all() return context def get_ordering(self): ordering = self.request.GET.get('ordering', '-date_time') return ordering def get_queryset(self): query = self.request.GET.get('q') user_casino = self.request.user.casino user_emp_type = self.request.user.employee_type ordering = self.get_ordering() if query: object_list = Memo.objects.filter( casino=user_casino).filter( receiver=user_emp_type).filter( Q(title__icontains=query) | Q(content__icontains=query ) ) else: object_list = Memo.objects.filter( casino=user_casino).filter( receiver=user_emp_type ) if ordering and isinstance(ordering, str): ordering = (ordering,) object_list = object_list.order_by(*ordering) return object_list I am trying to create the SearchMixin as such: class SearchMixin: def get_queryset(self): queryset = super(SearchMixin, self).get_queryset() query = self.request.GET.get('q') if query: print('yes') return queryset.filter(Q(title__icontains=query) | Q(content__icontains=query)) print('no') return queryset The problem is that the query is not hitting the SearchMixin when I add it to the MemoListView as such: class MemoListView(LoginRequiredMixin, SearchMixin, ListView): … -
How too make dropdown list from database django
guys i have problem about django forms when post to my database here my code : forms.py : class InstagramUsernameForm(forms.ModelForm): nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.all()) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan")) class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') models.py : class Instagram(models.Model): nama_depan = models.CharField(max_length=100) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return "{}".format(self.username) class InstagramUsername(models.Model): nama_orang = models.CharField(max_length=20) username = models.CharField(max_length=20) nama_depan = models.CharField(max_length=30) def __str__(self): return self.nama_orang this is my views.py: def create2(request): akun_form = InstagramUsernameForm(request.POST or None) if request.method == 'POST': if akun_form.is_valid(): akun_form.save() return redirect('sosmed:awe') context = { "akun_form":akun_form, } so the problem is when i deactivate "nama_depan" in forms.py its can save to models database when i activate it cant save to models database anyone know it ty ;D -
How could I show the data from mysql to a modal where it I could update it also?
Im a new to Django and i was trying to show the information/data from mysql to a Modal and on same time I can also update those data if possible. class User(models.Model): login_id = models.AutoField(primary_key=True) user_id = models.CharField(max_length=45, blank=True, null=True) employee = models.ForeignKey(Employee, models.DO_NOTHING, blank=True, null=True) password = models.CharField(max_length=45, blank=True, null=True) user_type = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'user' -
Django save all required documents
I have this code in my html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr> {% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile" value="{{d.id}}" style="outline: none;" required/>{{d.Description}}</td> <td></td> </tr> {% endfor %} This is my code in views.py V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() \model class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files/%Y/%m/%d',null=True,blank=True) Remarks = models.CharField(max_length=500,blank=True,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) How to save all in the database all the required documents that the user input? QUESTION UPDATED all documents that the students input, it will save in the database, in my case even the students input 4 documents only 1 documents save in the database -
How to create a similar to "setUp" method in unittest using pytest fixtures and django
I have the code below in my test files and trying to refactor it. I am new to pytest and i am trying to achieve the similar method setUp available with unittest to be able to retrieve the object created in the db to other function instead of repeating the codes. In this case I want to reuse month from test_setup to the other functions. test_models.py @pytest.mark.django_db class TestMonth: # def test_setup(self): # month = Month.objects.create(name="january", slug="january") # month.save() def test_month_model_save(self): month = Month.objects.create(name="january", slug="january") month.save() assert month.name == "january" assert month.name == month.slug def test_month_get_absolute_url(self, client): month = Month.objects.create(name="january", slug="january") month.save() response = client.get(reverse('core:month_detail', kwargs={'slug': month.slug})) assert response.status_code == 200 I would appreciate the help. -
Heroku config for a Django app that requires a Firebase JSON?
I have a Python Django app deployed on Heroku that uses Firebase through the drf-firebase-auth library (which I must use for a number of reasons). I know that configuration shouldn't be checked into version control, but I'm not sure how to avoid it in my case. The drf-firebase-auth library requires the Firebase credential JSON file to be saved in my code's directory structure. How can I pass this JSON essentially via Heroku environment variables without needing to commit the JSON file to my git repo (and push to Heroku), so that I can have a proper config setup for staging/production/etc? The drf-firebase-auth library instructs me to add this to my settings.py and also to save my very sensitive firebase.json file to my codebase: DRF_FIREBASE_AUTH = { 'FIREBASE_SERVICE_ACCOUNT_KEY': 'project/config/firebase.json' } The implementation within this 3rd party library looks a bit like this: import firebase_admin from drf_firebase_auth.settings import api_settings ... firebase_credentials = firebase_admin.credentials.Certificate( api_settings.FIREBASE_SERVICE_ACCOUNT_KEY ) firebase = firebase_admin.initialize_app(firebase_credentials) ... The problem is that I would like to avoid committing this Firebase JSON to git in order to deploy to Heroku. -
Proper way to run nameko service(s) inside a Django application?
If I have a vanilla Django REST (DRF) application and I would like to integrate a nameko service (specifically an event_handler event listening service), what's the best way to achieve this? I cannot simply nameko run a service if it's part of a Django application. I'm considering running the nameko service via a custom Django management command, but would I lose some of nameko's features, say, scalability? Eg. nameko maintains a pool of 10 workers per nameko run (if I remember correctly). -
How to get single filed value with aggregate from other model?
I need to divide two queries values from one model and group it by names from another model, but I can't understand how to connect it by foreign key and how I can divide different queries. Query that I need in SQL: Select m2.regionname,m2.indicatorname, round(CAST( m2.a2Value as float) / m1.a1Value,2) from( select r.name as regionname , ina.name as indicatorname, sum(a.value) as a1Value from Region as "r" left join city_region as "cr" on r.region_id = cr.region_id left join Office as "o" on cr.city_id = o.city_id left join Assets as "a" on o.office_id = a.office_id left join Indicators as "i" on a.indicator_id = i.indicator_id left join IndicatorNames as "ina" on i.indicator_name_id = ina.indicator__name_id where a.month between '01-01-2019' and '31-01-2019' group by r.name, ina.name ) m1 join ( select r.name as regionname , ina.name as indicatorname, sum(a.value) as a2Value from Region as "r" left join city_region as "cr" on r.region_id = cr.region_id left join Office as "o" on cr.city_id = o.city_id left join Assets as "a" on o.office_id = a.office_id left join Indicators as "i" on a.indicator_id = i.indicator_id left join IndicatorNames as "ina" on i.indicator_name_id = ina.indicator__name_id where a.month between '01-02-2019' and '27-02-2019' group by r.name, ina.name) m2 on m1.regionname = m2.regionname … -
Get all related data from model and save it to the another model using django signal
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) in table student enrollment record it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. student enrollment record subjectsectionteacher This is what the result I want Result I want This is the result I get what I got result class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) -
i got the below error while calling the app
I have started making web development i got the below error even the app is given File "c:\users\vivek\appdata\local\programs\python\python37-32\Lib\pathlib.py", line 1168, in stat return self._accessor.stat(self) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
Django: Forbidden (CSRF cookie not set.), Why this is happening , and How to fix it
I wrote a test file to check if the URL works or not and it keeps printing Forbidden (CSRF cookie not set.) could please check what's the problem #post handler @csrf_exempt def post(self, request, *args, **kwargs): valid_json = is_json(request.body) if not valid_json: error_data = json.dumps({'message': 'Invalid data sent, please send using JSON format'}) return self.render_to_response(error_data, status=400) data = json.loads(request.body) form = SupervisorForm(data) if form.is_valid(): obj = form.save(commit=True) obj_data = obj.serialize() return self.render_to_response(obj_data, status=201) if form.errors: data_error = json.dumps(form.errors) return self.render_to_response(data_error, status=400) json_data = json.dumps({'message': 'Not Allowed'}) status_code = HTTP_400_BAD_REQUEST return self.render_to_response(json_data, status_code) def post(): data = { 'supervisor_name':'name', 'supervisor_phone': '76786875', 'supervisor_email': 'sdsds@sdsd.com', 'supervisor_image': 'path to local image', } json_data = json.dumps(data) json_loads = json.loads(json_data) print(type(json_data)) print(type(json_loads)) print(help(requests.put)) r = requests.put('http://127.0.0.1:8000/api', json = json.dumps(data)) return r.json() -
How to get data from a foreign key in django
I have a model as follows: class Products(models.Model): name=models.CharField(max_length=100) desc=models.CharField(max_length=1000) price=models.IntegerField() class Cart(models.Model): product=models.ForeignKey(Products,models.CASCADE) qty=models.IntegerField() I need to show all the items in the cart with their name and price. I have searched how to do this but don't understand. Please help. If you need more info I will give you. -
How can I implement text exchange between users
I have been working on a web app (lost and found platform) as a hobby project to learn django rest framework and angular. The idea is simple at the beginning, just let users post items they found and show list of found items. However, I don't know the best technology or approach to let the owner contact the original poster and claim the item. Any suggestions would be greatly appreciated. Thanks -
How to use django-storages to store and retrieve one field in my model
I use DRF for building our customer facing web app at my work. We have a Profile model which contains an ImageField which represent a User profile and his profile picture respectively. My job is to stop using FileSystem as a storage and switch to use s3 to store the images. I figured I would be able to do this using django-storages app. But I can't understand how to get django-storages to work with only one field in a model instead of using it as a default storage. I have tried using a FileField with storage set to storages.backends.s3boto3.S3Boto3Storage but am not able to save a file to s3. To summarize my question - How to configure django-storages as storage for only one field How to set and retrieve the field in my model. class Profile(models.Model): img = ImageField(upload_to=get_directory, default='img/generic_profile.jpg') name = CharField(max_length=256) new_s3_field = FileField(storage=S3Boto3Storage) profile = Profile() profile.new_s3_field = ContentFile('sample.jpg', open('sampel.jpg') # does not work File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1079, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1111, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1064, in as_sql for obj in self.query.objs File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 1013, … -
How to send a JSON message via Python Requests/URL Module to a Pi Django server from a Pizero W on the same router/LAN?
I have a Raspberry Pi 3+ and a Raspberry Pizero W connected to the same home wireless network. The Pi 3+ is hosting a Django server, and the IP address of the Pi 3+ is static on the home network at 192.384.5.767. The Pizero W has a static IP address on the home network of 192.384.5.343. When I ping the Pi 3+ Server from the Pizero W, I can see that it is up: pi@PIZEROW:~$ ping 192.384.5.767 64 bytes from 192.384.5.767: icmp_seq=1 ttl=64 time=10.5 ms 64 bytes from 192.384.5.767: icmp_seq=2 ttl=64 time=30.0 ms 64 bytes from 192.384.5.767: icmp_seq=3 ttl=64 time=32.1 ms Additionally, when I access the website hosted by the Django server on a tablet, there are no issues. However, I need two-way communication between the Pizero W and the Django server so would like to test sending a super simple JSON message from the Pizero W to the Pi 3+ server and receive an acknowledgement from the server that it received the message. I don't need the server to do anything with the message other than to receive it, discard it, and send a confirm that the message was received. I tried doing this from the Pizero W using: … -
Django 'Page not found' error when setting up URLs
I'm following this tutorial: https://www.youtube.com/watch?v=Z4D3M-NSN58 This is the point where I get the 404 error: https://www.youtube.com/watch?v=Z4D3M-NSN58&t=1044s What I did so far: Set up a new project, Created a virtualenv, Set up views.py, from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(response): return HttpResponse("<h3>MySite</h3>") Created urls.py inside my main folder, from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] Modified the urls.py inside pycache folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include("main.urls")), ] Upon connecting to http://127.0.0.1:8000/ I receive the 404 error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in firstwebsite.urls, Django tried these URL patterns, in this order: admin/ home/ The empty path didn't match any of these. I am unable to proceed. -
Refactoring clean method of django form
I'm trying to refactoring the form code of a django app. The form have this view belong that to a crispy form but I don't know that is relevant. My doubt is if exists a way for simplify or separate the clean method of the form. def clean(self): cleaned_data = super(RequirementsForm,self).clean() stand_type = cleaned_data.get('stand_type') interviewers = cleaned_data.get('numeroentrevistadores') lunch_number = cleaned_data.get('lunch_number') veggie_lunch_number = cleaned_data.get('veggie_lunch_number') dp1 = cleaned_data.get('day_preference_1') st1 = cleaned_data.get('stand_preference_1') st2 = cleaned_data.get('stand_preference_2') st3 = cleaned_data.get('stand_preference_3') rs = cleaned_data.get('require_stand') pn = cleaned_data.get('producerName') pp = cleaned_data.get('producerPhone') pe = cleaned_data.get('producerEmail') total_lunch = lunch_number + veggie_lunch_number #if stand_type and total_lunch: # if stand_type == "1" and total_lunch > 2: # raise forms.ValidationError( # "error1" # ) #if stand_type == "2" and total_lunch > 4: # raise forms.ValidationError( # "error2" # ) if interviewers: if (stand_type == "1" or stand_type == "2") and interviewers > 2: raise forms.ValidationError( "error3" ) if (stand_type == "4" or stand_type == "5") and interviewers > 4: raise forms.ValidationError( "error4" ) if stand_type == "3" and interviewers > 3: raise forms.ValidationError( "error5" ) if total_lunch: if (stand_type == "1" or stand_type == "2") and (lunch_number + veggie_lunch_number) > 2: raise forms.ValidationError( "error6" ) if (stand_type == "4" or stand_type == … -
Django- Update an object with a list of dictionaries
I am trying to update multiple objects with different values using a list of dictionaries. I am able to update all of the objects with the code shown below. However, all of the objects are updated with the values contained in the last dictionary in the list. The dictionary and lists shown below contain the values that I expect them to, so there does not seem to be an issue there... I'm at a loss on how to solve this. Any help or advise is greatly appreciated. models.py ... event_set = (Event.objects.filter(recurring_event__pk=self.id)) event_set_list = [] for events in event_set: event_set_list.append(object) update_event = [] for item in recurring_event_list: defaults = {} defaults['recurring_event']=item[0] defaults['title']=item[1] defaults['start']=item[2] defaults['end']=item[3] update_event.append(defaults) for event in event_set_list: obj = Event.objects.get(id=event.id) for index in range(len(update_event)): for d in update_event[index]: setattr(obj, 'recurring_event', update_event[index]['recurring_event']) setattr(obj, 'title', update_event[index]['title']) setattr(obj, 'start', update_event[index]['start']) setattr(obj, 'end', update_event[index]['end']) obj.save() -
Django filter "__contains" lookup throwing " is not defined"
I'm trying to get all the objects in my database that the name is LIKE '%something%' After reading the documentation and searching online I figured out that using django I would have to use __contains lookup. But when I try to, the console throws me an error 500 'NameError: name 'ingredient_name__contains' is not defined' My model is the following: class Ingredient(models.Model): article_number = models.AutoField(primary_key=True) ingredient_name = models.CharField(max_length=100, null=False) cost_amount = models.FloatField(validators=[MinValueValidator(0.1)]) cost_per_unit = models.FloatField(validators=[MinValueValidator(0)]) unit = models.ForeignKey(MeasurementUnit,on_delete=models.CASCADE) def __str__(self): return self.ingredient_name And the filtering method is: def filter(request, filter): filtered = Ingredient.objects.all().filter(ingredient_name__contains(filter)) I can't figure out what I missing in this, it's driving me mad. If anyone could help I qould really appreciate it! -
accessing a different user's information in django
I know to access the logged-in user's data we use request.user. My goal is to list all the users in the table and have a link to their profile page. How do I make the link go to the user's profile page? I have the following: # app/views.py def tutors_list(request): user_list = CustomUser.objects.all() context = { 'user_list': user_list } return render(request, 'tutors_list.html', context) def show_profile(request, username): user = CustomUser.objects.get(username = username) ### NOT DISPLAYING RIGHT USER #user = CustomUser.objects.get(id=id) context = { 'user': user } return render(request, 'show_profile.html', context) # myproject/urls.py url_patterns = [ # ... path('show_profile/', views.show_profile, name='show_profile'), # ... I'm getting an error saying show_profile is expecting 1 more argument, username. How exactly would this model work if I need to pull data for a specific user in the database and not the logged-in user? -
Allow user to connect their database to django app
I am developing an app in which user stores their data. I want to add option to allow user to connect their database (on their server) to the django project so that they can store their sensitive information. Eg:- Data stored on my app database -> Name, Username, Email Data stored on user database -> Phone, Bank Details etc. I cannot configure user database credentials in settings.py as it will be dynamic and different for different users. So, how do i accomplish this? -
Use existing ModelSerializer with JSONResponse
I have a Twitter authentication view that doesn't use a viewset so the auth can be handled on the backend. The view takes in the oauth_token & uses Twython to get the profile & create a Twitter model. Currently I just return status 201 on success, but to alleviate the need for another request after creation, I'd like to return the created model. I have a TwitterSerializer already which defines the fields that I want to include, so I'd like to be able to reuse this if possible. TwitterSerializer class TwitterSerializer(serializers.ModelSerializer): class Meta: model = Twitter fields = ( "id", "twitter_user_id", "screen_name", "display_name", "profile_image_url", ) When I try to use this, I get the error that Instance of TwitterSerializer is not JSON serializable. serialized = TwitterSerializer(instance=twitter) return JsonResponse({ "created": serialized }) I could return a serialized instance of the model using serializers.serialize() serialized = serializers.serialize('json', [twitter, ]) serialized = serialized[0] return JsonResponse({ "created": serialized }) I could pass the fields kwarg to serialize() but I don't want to have to repeat myself if I don't have to. So would it be possible to re-use my TwitterSerializer in this case? I'm having trouble finding a direct answer since most docs assume …