Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Crispy forms - inline Formsets 'ManagementForm data' error with update view
Good Evening, Im having trouble with a crispy forms inlineformset. I have followed guides as per: https://github.com/timhughes/django-cbv-inline-formset/blob/master/music/views.py https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_formsets.html#formsets and I must be missing something as am getting the error: ['ManagementForm data is missing or has been tampered with'] here is my update view: class EditDeviceModel(PermissionRequiredMixin, SuccessMessageMixin, UpdateView): model = DeviceModel form_class = DeviceModelForm template_name = "app_settings/base_formset.html" permission_required = 'config.change_devicemodel' success_message = 'Device Type "%(model)s" saved successfully' def get_success_url(self, **kwargs): return '{}#device_models'.format(reverse("config:config_settings")) def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, model=self.object.model, ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title']='Edit Device Model' if self.request.POST: context['formset'] = DeviceFormSet(self.request.POST, instance=self.object) else: context['formset'] = DeviceFormSet(instance=self.object) context['helper'] = DeviceFormSetHelper() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] if formset.is_valid(): self.object = form.save() formset.instance = self.object formset.save() return redirect(self.success_url) else: return self.render_to_response(self.get_context_data(form=form)) Here is my form: DeviceFormSet = inlineformset_factory(DeviceModel, MonitoredResource, form=MonitoredResourceForm, extra=1) class DeviceFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(DeviceFormSetHelper, self).__init__(*args, **kwargs) self.form_method = 'post' self.render_required_fields = True self.form_id = 'snmp_resource_form' self.form_method = 'POST' self.add_input(Submit("submit", "Save")) self.layout = Layout( Div( Div( Field('model'), Field('resource', placeholder="Resource"), css_class='col-lg-6' ), css_class='row' ), ) and in the templates I render: {% block content %} {% include "home/form_errors.html" %} <div class="col-lg-6"> {% crispy form %} </div> <div class="col-lg-6"> {% crispy formset … -
How to play audio in Django ?
How To use the audio file of the local system to play in django? {% load staticfiles %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <link href="{% static 'css/result_style.css' %}" type="text/css" rel="stylesheet"/> <link rel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <div class="container" align="center"><br><br><br> {% load custom_filters %} <h2>{{summary}}</h2> <br> This part is working fine while playing this part in simple html code <p>Click on the audio To Listen Your Summary</p> <audio controls> <source src="D:\textanalysis\audio_file.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> <div> </body> </html> -
Connect google/collab or binder to a django database
I made a django application where people can create projets, upload csv files and see some stats in a dashboard using d3. I would like to let my users manipulate the files with a jupyter notebook like interface. I am wondering what would be the easiest way to do so. As the data needs to be secure, could I make a 'link' between a google colab and my postgress database where is the data so user could read and write content un the database. My django is organised like this today : User upload a csv to a postgress db, backend converts it to a pd.df and then sends it as json to my front end. I would like users to be able to get the csv file from collab to manipulate it and them.to send the new df to backend or front end. All with a secured access with password for example. Would be great if it would work on my aws server. The solution I imagine is making a sort of api.rest that would ask for data and be able to write again. Are there any good exemple of such applications ? Any example would usefull. Thank for … -
Return value based on condition in serializer
I have an Entry model in my app and when it's deleted I simply mark is as deleted instead of soft deleting (so original content stays in database). I want to implement a logic in my Serializer class that if an Entry is marked as deleted (boolean field) the field 'content' returns value "deleted" instead of the original content. I have already implemented logic that if it's deleted it cannot be changed. I've tried using a CharField with source parameter but then it requires to be read-only so that won't work as I still want the content to be write-able. -
python pandas iloc works on jupyter but not on flask
I am developing an API from flask and for that I had to use pandas in between of a function. So to access a data I used pandas iloc but it shows an error 'IndexError: single positional indexer is out-of-bounds'. Here's my code: price = float(cf.loc[cf['company_name'] == 'Agricultural Development Bank Limited', 'Close'].iloc[0]) If I run the same thing at jupyter then it works perfectly. Cjeck out the screenshot of running this code in jupyter notebook Please help. -
Unsure how to compute a particular value to be displayed (Python/Django)
So basically in my store, every item has a specific weight and once the customer adds whatever they want and go to checkout, they can see every single order of theirs along with the name information and weight. I want to also add the total weight of all the items together. Currently, it displays only the weight of each particular item.For exampleItem A is 2 Kg and item B is 3 kgIf customer adds 2 item A and 3 Item B It displays Item: A quantity: 2 Weight : 4kgItem: B quantity: 3 Weight: 9kg.I want to also add Total weight : 13 kg This is my views.py def checkout(request): try: current_order = Order.objects.filter(owner=1).get(status="pre-place") except Order.DoesNotExist: return HttpResponse("Your current order is empty<br><a href=\"browse\">Go back</a>") else: total_weight = 0 items = OrderDetail.objects.filter(orderID=current_order) template_name = 'store/checkout.html' order_details = [] for item in items: weight = item.supplyID.weight * item.quantity order_details.append((item, weight)) return render(request, template_name, {'order_details': order_details, 'current_order': current_order}) This is my template <h1>Your current order</h1> <a href="{% url 'Store:browse' %}">return to selecting supplies</a><br><br> <table> <tr><th>name</th><th>item weight(kg)</th><th>qty</th><th>total weight(kg)</th></tr> {% for order_detail, weight in order_details %} <tr> <td>{{ order_detail.supplyID.name }}</td> <td>{{ order_detail.supplyID.weight }}</td> <td>{{ order_detail.quantity }}</td> <td>{{ weight }}</td> </tr> {% endfor %} </table> -
How to get the app label in tests.py stored in that app in Django?
I am trying to get the app label in my tests.py. It should basically just give me the app label in whose folder the python module is located. So if we have myapp/tests.py, then within that file, it should return 'myapp'. Right now, the only way I can think about doing this is importing a model from that app, and calling the following: MyModel._meta.app_label However, there must be another way to just get the app label without using a model right? Any help is appreciated. -
Django querying on model which is involved in generic relation
Here I have 2 models, Company and UserSupervision. Company is related as a foreign key with generic relation model UserSupervision. I want to have a query as following: Company.objects.filter(**{'usersupervision__content_type': Company, 'usersupervision__user': some_user, 'usersupervision__date_cancelled': None}) So, I want to get all companies of some_user appeared in UserSupervision model. I know that Company and UserSupervision are not directly related, so i thought, maybe i have to use raw sql with joins? Or any other more appropriate solution? class Company(models.Model): id = models.UUIDField(blank=True, editable=False, primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=150, unique=True) users = models.ManyToManyField(User, related_name='companies', through='CompanyMembership') date_created = models.DateTimeField('created date', blank=True, editable=False, auto_now_add=True) date_updated = models.DateTimeField('updated date', blank=True, editable=False, auto_now=True) class UserSupervision(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) supervision = models.ForeignKey(Supervision, on_delete=models.SET_NULL, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField() content_object = GenericForeignKey() date_assigned = models.DateTimeField('assigned date', blank=True, editable=False, auto_now_add=True) date_cancelled = models.DateTimeField('cancelled date', blank=True, null=True, default=None) -
django elasticsearch error inside docker using docker-compose while building index
docker-compose.yml version: "3" services: rango_api: container_name: rango build: ./ command: python manage.py runserver 0.0.0.0:8000 command: python manage.py search_index --rebuild working_dir: /usr/src/rango_api environment: REDIS_URI: redis://redis:6379 ports: - "8000:8000" volumes: - ./:/usr/src/rango_api links: - redis - elasticsearch #redis redis: image: redis environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.5.0 ports: - "9200:9200" - "9300:9300" django settings.py elastic search connection ELASTICSEARCH_DSL = { 'default': { 'hosts': 'elasticsearch:9200' }, } errors: rango | Are you sure you want to delete the 'posts' indexes? [n/Y]: Traceback (most recent call last): rango | File "manage.py", line 15, in <module> rango | execute_from_command_line(sys.argv) rango | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line rango | utility.execute() rango | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute rango | self.fetch_command(subcommand).run_from_argv(self.argv) rango | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv rango | self.execute(*args, **cmd_options) rango | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute rango | output = self.handle(*args, **options) rango | File "/usr/local/lib/python3.6/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 134, in handle rango | self._rebuild(models, options) rango | File "/usr/local/lib/python3.6/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 111, in _rebuild rango | if not self._delete(models, options): rango | File "/usr/local/lib/python3.6/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 100, in _delete rango | "the '{}' indexes? [n/Y]: ".format(", ".join(index_names))) rango | EOFError: EOF when reading a line i am trying elastci search … -
Upload, process and then download a file in Django
I am making a Django app where one uploads a .mp3, then this .mp3 file is processed by the server, and then the user can download the processed file. I don't know how to handle the uploads and downloads. I have tried using filetransfers but it doesn't seem to answer my problem. PS : I am not at all familiarized with Http protocols... -
Compare 2 labels in Rest Api Django
I got 2 label values on my django server (db used postgresql) and i want to compare them and post the result on my android app.but since i am new to django i hav no idea how to compare lables -
AttributeError: 'function' object has no attribute 'execute'
It's a django project,the views.py is from django.shortcuts import render from django.db import connection def get_cursor(): return connection.cursor def index(request): cursor = get_cursor() cursor.execute("select id,name,author from book") books = cursor.fetchall() return render(request, 'index.html') Few minutes, it's work, but now error, and it can not get data from mysql,I don't know if is my system fault. -
filter queryset based on url arguments
how to get parameters in a url in view and filter the query based on that? i also want to have multiple arguments in urls and all of them are optional? to deliver the requiremnt clearly here is a look on the urls in urls.py: url(r'^search/(?P<insurance>\D+)/(?P<area>\D+)/(?P<slug>\D+)/(?P<illness>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<area>\D+)/(?P<slug>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<slug>\D+)/(?P<illness>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<area>\D+)/(?P<illness>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<area>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<slug>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<area>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/(?P<illness>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<insurance>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<area>\D+)/(?P<slug>\D+)/(?P<illness>\D+)$',new_search,name='new_search'), url(r'^search/(?P<area>\D+)/(?P<slug>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<area>\D+)/(?P<illness>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<area>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<slug>\D+)/(?P<illness>\D+)/$',new_search,name='new_search'), url(r'^search/(?P<slug>\D+)/$',new_search,name='new_search'), how to filter a queryset based on those urls in views.py ??? -
Can anyone help me to print following pyramid using python [on hold]
Can anyone help me to print following pyramid using python HHHHHHHHH HHHHHHH HHHHH HHH H -
Should I make external API calls in django model managers
I have local django models that mirror some external service's entities. So basically when I create a local object, I start with making post requests to the service and then fill fields of the local object with the data from response and save it. Is it a good idea to put external api calls to model manager in order to abstract the logic for views and tests? Or is there a better approach? What I would like to achieve is to avoid duplicate logic everywhere in the codebase. -
no reverse match url error for my django 2.0.5 shop project
am working on a django 2.0.5 project building an ecommerce store using django shop,am getting a no reverse match url error Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[0-9]+)\\/$'] myshop/cart/urls.py from django.urls import path from . import views app_name = 'cart' urlpatterns = [ path('', views.cart_detail, name='cart_detail'), path('add/<int:product_id>/', views.cart_add, name='cart_add'), path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'), ] myshop/cart/views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) myshop/cart/templates/cart/detail.html {% extends "shop/base.html" %} {% load static %} {% block title %} Your shopping cart {% endblock %} {% block content %} <h1>Your shopping cart</h1> <table class="cart"> <thead> <tr> <th>Image</th> <th>Product</th> <th>Quantity</th> <th>Remove</th> <th>Unit price</th> <th>Price</th> </tr> </thead> <tbody> {% for item in cart %} {% with product=item.product %} <tr> <td> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %}{{ … -
Facebook Account Kit Django auth
Is it possible to authorize users via API methods by Account Kit access_token with django-rest-framework-social-oauth2 library? If not, where do you advise to start custom implementation of account kit authorization? -
Django adding CSS from the application to the header
My blog page- blog.html in blog application extends from base.html from the root directory. The blog application has its own CSS file - blog.css. How can I place the blog.css in the blog.html head area along with other CSS links from the base.html? The challenge here is that the blog.html since extends the base.html, I am unable to add the blog.css into the header. This is because the base.html has already closed the HTML head tag. Any help appreciated Thanks and regards -
Django 1.11 Model Migration Operations doesn't apply
My operation inside my migration is executed, whereas nothing happened into the database concerning the payer field. Here's my model: class User(AbstractBaseUser, PermissionsMixin, WithCsvImportMixin): first_name = models.CharField(_('first name'), max_length=30, blank=False) last_name = models.CharField(_('last name'), max_length=30, blank=False) email = models.EmailField(_('email address'), unique=True, blank=False) external_id = models.CharField(_('external id'), db_index=True, max_length=50, unique=True, blank=False, null=True) is_staff = models.BooleanField(_('staff status'), default=False) is_active = models.BooleanField(_('active'), default=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) payer = models.CharField(_('payer'), max_length=50, blank=False, default='') The first migration concerning the payer field: # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-11-15 21:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authenticate', '0012_auto_20181112_1631'), ] operations = [ migrations.AddField( model_name='user', name='payer', field=models.CharField(default='', max_length=50, verbose_name='payer'), ), ] And this is the one that is executed but the result doesn't seems to be applied to the database: # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-11-15 22:01 from django.db import migrations, transaction from xxx.authenticate.models import User # The xxx is here to replace the actual application name def create_payer_names(apps, schema_editor): with transaction.atomic(): for user in User.objects.all(): if user.external_id != "": user.payer = user.external_id user.save() class Migration(migrations.Migration): dependencies = [ ('authenticate', '0013_user_payer'), ] operations = [ migrations.RunPython(create_payer_names, … -
Django Formset edit view
I'm trying to edit the data, but instead of editing it adds a new record. Where is the error? Is a formset. I'm trying to edit the data, but instead of editing it adds a new record. Where is the error? Is a formset I'm trying to edit the data, but instead of editing it adds a new record. Where is the error? Is a formset. I'm trying to edit the data, but instead of editing it adds a new record. Where is the error? Is a formset #part of models.py class Call(models.Model): ... pictures = models.ManyToManyField(Picture) #part of forms.py class PictureForm(forms.ModelForm): class Meta: model = Picture fields = '__all__' PictureFormset = formset_factory(PictureForm, extra=3) class CallForm(forms.Form): ... pictures = PictureFormset() #part of views.py def call_edit(request, id): call = Call.objects.get(id=id) if request.method == 'POST': form = CallForm(request.POST) picture_instances = PictureFormset(request.POST, request.FILES) if form.is_valid(): if picture_instances.is_valid(): ... has_microphone_hall=form.cleaned_data['has_microphone_hall'], cam_amount_hall=form.cleaned_data['cam_amount_hall'], has_horn_hall=form.cleaned_data['has_horn_hall'], ... ) call.save() args = { 'form': form, 'call': call, 'technicians': technicians, } for item in picture_instances: if item.is_valid(): picture = item.save() call.pictures.add(picture) # checar else: ("CHECK - ERROR") picture.save() return HttpResponseRedirect('index') else: print (form.errors) args = { 'form': form, 'call': call, } return render(request, 'call-add.html', args) else: form = CallForm() args … -
Django email template encoding
I maked a view with a form, that should send message on user email, but i have a problev with encoding. My template have some kirillic letters, and if i try to send mail i get an error: 'ascii' codec can't encode characters in position 325-329: ordinal not in range(128) If i change text in my template to english letters everything works. View: def index(request): seos = SEO.objects.get(id__exact=1) socs = Social_networks.objects.get(id__exact=1) globs = globalapp.objects.get(id__exact=1) index = Index.objects.get(id__exact=1) form = ContactForm(request.POST) formmm = ContactusForm(request.POST) email = globalapp.objects.values_list('emailfb', flat=True).get(id=1) if form.is_valid(): subject = form.cleaned_data['subject'] sender = form.cleaned_data['sender'] message = form.cleaned_data['message'] fille = form.cleaned_data['fille'] recepients = email from_email, to = sender, recepients html_content = loader.render_to_string('globalapp/chunks/email_tpl.html', {'subject': subject, 'sender':sender, 'message':message, 'fille':fille}) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.send() if request.method == 'POST': subject = request.POST['subject'] email = request.POST['sender'] message = request.POST['message'] form = 'Шапка' post.objects.create( subject = subject, email = email, message = message, form = form ) return HttpResponse('') return render(request, 'globalapp/index.html', {'seos': seos, 'socs': socs, 'globs': globs, 'index': index, 'form': form, 'formmm': formmm }) Template: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <h2>Новое сообщение с сайта!</h2> <p>Имя: {{ subject }}</p> <p>Email: {{ sender }}</p> <p>Сообщение: {{ message }}</p> </html> Ill tryed already … -
Initial django admin forms with data
I've used django-admin and assigned a django-form to it. I need to fill up one of my custom rows with a random dynamic data. I can't use initial from form attributes BTW. I need to get the data from my URL and my URL is generated with another component. -
Залил на plesk через phusion, не может найти дб, в чем может быть трабла?
enter image description here вот это выкидывает. вот так запускается: passenger_enabled on; passenger_app_type wsgi; passenger_app_env development; passenger_startup_file passenger_wsgi.py; Вот passenger_wsgi.py: import sys, os ApplicationDirectory = 'Gigabit' ApplicationName = 'Gigabit' VirtualEnvDirectory = 'django-app-venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() всё испробовал ничего не помогло. -
How to properly extend and include in Django tempates
Following is my homepage.html is home app {% extends "base.html" %} {% load static %} <link rel = "stylesheet" href = "{% static 'css/home.css' %}" > #reference to stylesheet in the home app static directory {% block body %} <h1>I am homepage</h1> {% endblock %} My base.html in the project root folder is the following <!DOCTYPE html> <html> <head> <link rel = "stylesheet" href = "{% static 'base.css' %}" > #stylesheet in root folder </head> <body> {% block content %} {% endblock %} </body> </html> But here, the home.css in the homepage.html is not functional as the base.html on extend closes the head before the home.css can come in the head section. Is there any way I can add the CSS into the header Thanks -
Django 'type' object is not iterable
I made a simple API that list students their respected universities using Django Rest Framework. The url to list the data is http://127.0.0.1:8000/api/v1/students/. After trying out the API,I got the following error TypeError at /api/v1/students/ 'type' object is not iterable I was able to find some solution on StackOverflow but not much luck in finding a solution. I am using APIView in the views.py file and I want to understand why this happens when I used APIView (this issue also appears using Viewset). I've tried changing the changing the permissions did not help. Also setting many=True to 'False' did not solve the issue also. Anybody has any ideas? Thanks in advance. Here is the other files for better understanding of this issue models.py from django.db import models class University(models.Model): name = models.CharField(max_length=50) url = models.URLField(unique=True) class Meta: verbose_name = "University" verbose_name_plural = "Universities" def __str__(self): return self.name class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) university = models.ForeignKey(University, on_delete=models.CASCADE,) class Meta: verbose_name = "Student" verbose_name_plural = "Students" def __str__(self): return '%s %s' % (self.first_name, self.last_name) serializers.py from rest_framework import serializers from . import models class StudentSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'first_name', 'last_name', 'university' ) model = models.Student class …