Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Skipping a send email function and celery task during the unit testing
I have a Django view that I want to unit test it but the problem is in some line of the function it calls another function which has a send email function and this send email function has a celery task inside it. I don't know what to do to surpass this function call because when the debugger hits this line it stops and does nothing which I think is because of the celery task. Due to this problem, my unit test can't run completely. So I would be happy if someone could tell me what to do then. My own solution was to mock the sending email function but it doesn't work. I don't know what to do now. here is the code example of what happens during the view function. view_funtion(): ... function_a is called here function_a(): ... send_email_function is called here send_email_function(): some code here and initialization of the email template celery_task.delay() please let me know if I should add more detail. Thanks. -
In Django any user can block any user if user follow another user who blocked that user can't see his post
enter code here class post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = postManager() class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by') class Blocked(models.Model): user = foreign_key_field(User, related_name="blocked_users", ....) usres = many_to_many_field(User, related_name="blocked_by" ) i am developing small blog system where user can login follow and unfollow each other also block and unblock system if user block he another user that user which is blocked cant see his posts. i try many ways but can't get result like instagram and twitter system -
C:\Anaconda3\envs\MyDjangoEnv\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
I am trying to install channels but it is giving me following errors: 1.Building wheel for twisted (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Anaconda3\envs\MyDjangoEnv\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-install-twx22bnj\twisted\setup.py'"'"'; file='"'"'C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-install-twx22bnj\twisted\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-wheel-54761_h4' cwd: C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-install-twx22bnj\twisted\ 2.C:\Anaconda3\envs\MyDjangoEnv\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory 3.C:\Anaconda3\envs\MyDjangoEnv\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\cl.exe' failed with exit status 2 ERROR: Failed building wheel for twisted Running setup.py clean for twisted 4.C:\Anaconda3\envs\MyDjangoEnv\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\cl.exe' failed with exit status 2 5.ERROR: Command errored out with exit status 1: 'C:\Anaconda3\envs\MyDjangoEnv\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-install-twx22bnj\twisted\setup.py'"'"'; file='"'"'C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-install-twx22bnj\twisted\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\NextGen DigiTech\AppData\Local\Temp\pip-record-atgh_ht3\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Anaconda3\envs\MyDjangoEnv\Include\twisted' Check the logs for full command output. My installed environment are: 1.Windows 10 pro 2.Virtual environment 3.Django 3.8 4.Microsoft Visual Studio Community 2019 So, what will be the solution here? Any help will be highly … -
Django Docker: custom static/media roots outside of app folder: collectstatic and upload failing silently - why?
I used django-cookiecutter to dockerize my Django project. All works in development but in production, my custom locations /var/www/... are seemingly ignored. When powering up the production.yml, it says: django_1 | 2718 static files copied to '/var/www/static', 4936 post-processed. But no files to be found in /var/www/static. Similarly, django-filer uploads seem to disappear quietly for no apparent reason. Django DOCKERFILE: RUN mkdir -p /var/www/static RUN chown django:django /var/www/static RUN mkdir -p /var/www/media RUN chown django:django /var/www/media In Django production.py settings, I overwrite the static_root and media_root locations: # STATIC STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATIC_ROOT = "/var/www/static/" # MEDIA MEDIA_ROOT = "/var/www/media/" -
Django - migrating only new migrations after loading dump
The migration process of my test suite got very long in my project, so I created a pg_dump which I load to my DB each time I run my unit tests. Now the pg_dump was created manually, (which later I tend to integrate into a CI system) However now, I have some other migrations I created after the dump (and I don't want to create a new dump) and I need to run migrations. My question: How do I make django migrate only the new migrations? I searched for this topic online but found addressing this specifc problem. The closest thing I found was this post which wasn't very helpful for me Django backup strategy with dumpdata and migrations -
Error WORKER TIMEOUT on Docker Django AWS S3 and Heroku
I need to upload various and heavy files to my app, In development works fine but in production environment crash with this the traceback: 2020-10-19T06:51:02.387330+00:00 app[web.1]: [2020-10-19 06:51:02 +0000] [3] [CRITICAL] WORKER TIMEOUT (pid:87) 2020-10-19T06:51:02.403179+00:00 app[web.1]: [2020-10-19 08:51:02 +0200] [87] [INFO] Worker exiting (pid: 87) 2020-10-19T06:51:02.601253+00:00 app[web.1]: [2020-10-19 06:51:02 +0000] [112] [INFO] Booting worker with pid: 112 2020-10-19T06:51:02.405325+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/app/tratamiento/crear_media/197/" host=softwaredilains.herokuapp.com request_id=6dfc67b9-eb21-4ba2-b44b-4b9c23a5c350 fwd="95.19.228.74" dyno=web.1 connect=1ms service=30806ms status=503 bytes=0 protocol=http I have read something about Heroku workers and request timeout. Anybody know how to set config on Django, Heroku or Docker to fix it ? Thanks in advanced. -
How to display "for loop" data for another "for loop" in djnago render template?
views.py def index(request): data = posts.objects.all().order_by("post_date").reverse() p = Paginator(data, 3) page_num =request.GET.get('page',1) try: page = p.page(page_num) except EmptyPage: page=p.page(1) context = { "data" : page, "one":[likes.objects.filter(post_id=dat.id).count() for dat in data], } if request.method == 'POST' and "post" in request.POST: post = request.POST['post'] user_id = request.user data = posts(post = post, user_id = user_id).save() return render(request, "network/index.html", context) @csrf_exempt def like_post(request): if request.method == 'POST': data = json.loads(request.body) user_id = data.get("user_id","") user = User.objects.get(username=user_id) post_id = data.get("post_id","") post = posts.objects.get(pk=post_id) lik = likes(user_id = user, post_id = post) lik.save() liked = likes.objects.filter(post_id = post_id).count() print(liked) return JsonResponse({"liked":liked}) index.html {% for datas in data %} <div class="row"> <div class="col-md-12"> <div class="card shadow-lg"> <div class="card-body" id="div1"> <div class="row"> <div class="col-md-6"> <h5 class="card-title"><i class="fa fa-user-circle" aria-hidden="true"></i> <a href="{% url 'profile' datas.id %}">{{datas.user_id|capfirst}}</a></h5> </div> <div class=" col-md-6 text-right" > {% if request.user.id == datas.user_id_id %} <button class="btn btn-sm btn-outline-primary" onclick="load_post(this, '{{datas.id}}')" id="edit"> Edit</button> {% endif %} </div> </div> <div id="msg"> <hr> {{datas.post}} <hr> </div> <div id="one"> </div> <div class="row"> <div class="col-md-4"> <i class="fa fa-thumbs-up" ></i> <span id="add"> {% for gg in one %} {{gg}} {% endfor %} </span> </div> <div class="col-md-4"></div> <div class="col-md-4 text-right">{{datas.post_date}}</div> </div> </div> </div> </div> </div> <br> {% endfor %} I need … -
Unable to symbolicate stack trace: Network request failed - React Native
I can't communicate with my server. I just getting an error like this on android Unable to symbolicate stack trace: Network request failed -
GET a parameter with & included
I am receiving a URL such as the following: /return-graph/?rc=Mahindra%20&%20Mahindra_Nasik HTTP/1.1" 200 0 But when I try to get the URL it only shows the following q = request.GET['rc'] print(q) output: Mahindra whereas I need the fullname to make the query Desired Output: Mahindra & Mahindra_Nasik -
Django Error reporting with Custom send_email
I kindly need your help to make django error reports by email. I use service account with Gmail API to authorize and send emails. How can this work with default django error reporting send_email. I know I have to add the below to the settings and debug must be false: ADMINS, MANAGERS, SERVER_EMAIL -
How to pass value entered in textbox to flask in text format from django?
I am a beginner in django and flask. I want to pass the value entered in textbox from django to flask. views.py from django.shortcuts import render import requests # Create your views here. def form(request): return render(request,'hello/index.html') html file <!DOCTYPE html> <html> <body> <form action="output"> Enter name: <br/> <input type="text" name="name"> <br/> <input type="submit" ><br/> </form> </body> </html> flask app = Flask(__name__) @app.route('/') def index(): return "hello" if __name__ == '__main__': app.run(debug=True) In the flask i should get the values entered in django textbox.... -
Passing model field to html source/path in django templates
so im trying to pass an image to my html here is my code {% if q.number > 105 and q.number < 116 %} <p>{{ q.number }} </p> <img src="{% static 'images/{{ q.number }}.png' %}" alt={{ q.number }} /> {% endif %} the paragraph work fine, but i cant get to my image, its work fine if i replace the source with 106 - 115 (all is well) "{% static 'images/106.png' %}" both of them use the same if else, only the source changed i have tried to search the documentation but im having a difficult time understanding a lot of them -
How to create multiple model instances?
I want to create multiple model instances but with serializers I am unable to do it. And can I do this crud operation without serilizers. I am a newbie please help me. serializers.py class WorkExperienceSerialzer(BaseModelSerializer): hidden_fields_to_add = {"created_by": None, "user": None} class Meta(BaseModelSerializer.Meta): model = WorkExperienceData fields = [ "company", "designation", "description", "from_date", "to_date", "reference_name", "reference_mailid", "user", "id", ] extra_kwargs = { "user": {"read_only": True}, } def create(self, validated_data, **kwargs): instance = super(WorkExperienceSerialzer, self).create(validated_data) return instance def update(self, instance, validated_data): instance = super(WorkExperienceSerialzer, self).update( instance, validated_data ) return instance def get_default_value_for_field(self, field): value = super(WorkExperienceSerialzer, self).get_default_value_for_field( field ) if not value: if field == "user": value = self.context["request"].user return value def validate(self, attrs): user = self.context["request"].user if hasattr(user, "related_experience_detail"): raise serializers.ValidationError( "This user has already exists !" ) return attrs views.py class WorkExperienceViewSet(ViewListUpdateDeleteViewSet, BaseModelViewSet): queryset = WorkExperienceData.objects.all() serializer_class = WorkExperienceSerialzer I need to create multiple model instance for the user. -
In Django, why is the admin panel showing the names of all the models?
The code in the Django is like this: from django.db import models class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('Out Door', 'Out Door'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) As it can be seen, the def str(self) is only in class Customer, so in the Admin panel, shouldn't only 'Customer' be shown and the 'Products' and 'Orders' should be shown in some other different way?? -
Django Graphene writing mutations with multiple layers of nested foreign keys
How do you write the schema and query for nested foreign keys? I checked the docs and found no examples of how to do this. So here was my attempt based on github and stackoverflow answers lets say I have these models: class Address(models.Model): name = models.CharField() class Person(models.Model): name = models.CharField() address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=False, null=False) class Blog(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) text = models.TextField() I tried writing a schema like this: class AddressInput(graphene.InputObjectType): name = graphene.String(required=True) class PersonInput(graphene.InputObjectType): name = graphene.String(required=True) address =graphene.Field(AddressInput) class CreateNewBlog(graphene.Mutation): address = graphene.Field(AddressType) person=graphene.Field(PersonType) blog=graphene.Field(BlogType) class Arguments: address_data = AddressInput() person_data = PersonInput() text = graphene.String() @staticmethod def mutate(root, info, person_data=None, address_data=None, **input): address = Address.objects.create(name=address_data.name) person = Person.objects.create(address=address, name=person_data.name) blog = Blog.objects.create(person =person, text=input['text']) blog.save() return CreateNewBlog(blog=blog) and I used a query like this: mutation { CreateNewBlog(person: { address: {name: "aaa"}, name: "First Last" }, text: "hi hi") { Blog { person{ name address{ name } }, text } } } I got this error message: { "errors": [ { "message": "'NoneType' object has no attribute 'name'", "locations": [ { "line": 32, "column": 9 } ], "path": [ "CreateNewBlog" ] } ], "data": { "CreateNewBlog": null } } I … -
After learning Python- what?
After learning Python on beginner level, and practicing what would you recommend to go with, I am so keen to learn Django, but, I would like to know is it possible to understand Django 3.x with knowledge of Python 3.x and how if you can refer me to some good place to learn more and get more resources about these two, as all I am getting - respectfully, but, I don't understand - are Indian-based tutorials. Thank you! -
Django + Ajax + Cors = empty responses
I'm using jquery ajax in addition to django-cors-headers on my site in order to allow a form to be displayed as an iframe on another site that I don't own/control. While the form can be submitted, any time there is an ajax call from the page to a view in my project, the ajax POST being sent from the page (i.e. iframe) to the django view doesn't contain any data. Similarly, on the response, there is no data being sent from the view to the ajax function (i.e. the JSON is empty). Should CORS + Ajax work without using DRF? I've got the following settings in my settings file CORS_ORIGIN_ALLOW_ALL = True CSRF_COOKIE_SAMESITE = None In my ajax call, I'm passing the following headers: headers: { 'X-CSRFToken': '{{ csrf_token }}', 'X-Requested-With': 'XMLHttpRequest' }, Can you think of what else might be causing this? Thanks! -
Error when adding application in django proyect
I am a total begginer with django and I am having troubles when i try to run the proyect. I created a virtual environment, install django and django rest, start a django proyect and then i created my application. After that, i code a very simple model, serializer and view, to test all this new features, but when i tried to run it i got the following error: ModuleNotFoundError: No module named 'myapi' This is my proyect structure: My problem is when i try to add my application to the INSTALLED_APPS array in settings.py. I will show the code so far: setting.py of the proyect app_tv_movies/urls.py myapi/urls.py I dont understand why why django doesnt recognize my app! -
Bad Request Check all data table Django
I'm having a trouble why it keeps telling the console bad request after I check all the data, but if I manually check each item on table it works fine, but when I use check all - bad request I think the problem it has "on" data on my table but don't know why see the image below. Is there any expert can know about this? thanks in advance Bad Request using check all Check manually table.html <button type="submit" id="delete_btn" class="btn btn-secondary round btn-min-width mr-1 mb-1" >Mark as Paid</button> <table class="table" name="table" id="table"> <thead> <tr > <th >No</th> <th><input type="checkbox" onClick="toggle(this)" /></th> <th>ID Number</th> <th >Name</th> <th >Barangay</th> <th >Sex</th> <th >Sector</th> <th Amount</th> <th >Signature/Thumb Marks</th> <th >ID Presented/ Date & Issuance</th> <th>Date Received</th> <th >Remarks</th> </tr> </thead> <tbody class="report-content"> {% csrf_token %} {% for user_information in benefeciaries %} <tr id="{{user_information.id}}"> <td></td> <td><input type="checkbox" name="product_id[]" value="{{user_information.id}}" id="delete_product"></td> <td>{{user_information.covid_id}} </td> <td>{{user_information.lastname}}, {{user_information.firstname}} {{user_information.middle}}</td> <td width="5%">{{user_information.barangay}}</td> <td></td> <td ></td> <td>{{user_information.amount|floatformat:2|intcomma}}</td> <td></td> <td ></td> <td ></td> <td></td> </tr> {% endfor %} </tbody> </table> javascript //js checkall function toggle(source) { checkboxes = document.getElementsByName('product_id[]'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } //js mark as paid button $(document).ready(function(){ $('#delete_btn').click(function(){ if(confirm("Are you sure ?")){ … -
django upload multiple file without plugin
I'm trying to upload multiple file using django but my code is uploadign only one image not all images, I'm trying to upload multiple images without using any pluging or javascript just a simple way to do a foreach because I want to use only one input field has multiple attribute like in PHP codes My model is : from django.db import models from django.contrib.auth.models import User from album.models import Album from django.core.files import File class Images(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) album = models.ForeignKey(Album, on_delete= models.CASCADE) image_value = models.FileField(upload_to='galleries/images', max_length=350, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'album_images' def __str__(self): return self.album Form is : from django import forms from django.forms import ClearableFileInput from .models import * class ImagesUploadClass(forms.ModelForm): class Meta: model = Images exclude = ['user'] fields = ('image_value') View is : from django.shortcuts import render, redirect from .forms import ImagesUploadClass from .models import Images from django.http import HttpResponseRedirect def uploadMultiPleImagesFunction(request): upload_image = ImagesUploadClass() if request.method == "POST": form_add_data = ImagesUploadClass(request.POST, request.FILES) if (form_add_data.is_valid()): form_add_data.save.save() return HttpResponseRedirect('/album') else: print(form_add_data.errors) return render(request, 'images/upload_images.html', { 'upload_image' : upload_image, }) And my template html is : {% extends "base.html" %} {% block maincontent %} <form method="POST" action="" enctype="multipart/form-data"> {% … -
Can I create a SALESFORCE case using simple salesforce python library?
I am working on an app that uses the Django framework. The app has an issue reporting or request form that used to create a support ticket on Hubspot. The support system recently switched to Salesforce and now I need to find a way to create tickets/cases in there. I have found that the simple-salesforce python library is very popular to communicate with Salesforce API. The doc shows all the ways to connect/authenticate with the API, but I cannot find any function that can help me to create a case. Once you get the security token, you can get the resource object by simply doing the following: from simple_salesforce import Salesforce sf = Salesforce(username='myemail@example.com', password='password', security_token='token') How can I use the sf object to create a case or maybe get the necessary info to send some types of a POST request to do so? -
how do I make custom filters work in django_filters?
So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEAR CHOICE" from templates, the page refreshes but it doesn't work. I think I'm having a problem with my "year_filter_method" also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = YEARCHOICES return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.py {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% include 'main/includes/navbar.html' %} {% include 'main/includes/filter.html' %} … -
Django Jet Dashboard does not show/activate the updated model and view
I have been inheriting this project where the developer of which is not available to answer question anymore. Thus I have been struggling to figure out a way to help my admin add new items called "icon". I updated the models.py in 'api' app and migrated, and checked to make sure the new model table turns up in the database. However, I have been struggling to add this model onto the Django Jet Dashboard. Even after I press the reset button, the row for 'icon' model does not show up. Let me show you the dashboard.py from django.utils.translation import ugettext_lazy as _ from jet.dashboard import modules from jet.dashboard.dashboard import Dashboard, AppIndexDashboard from jet.utils import get_admin_site_name class CustomIndexDashboard(Dashboard): columns = 3 modules.DashboardModule.draggable = False modules.DashboardModule.style = True modules.DashboardModule def init_with_context(self, context): self.children.append(modules.ModelList( _('Data'), models=( 'api.Category', 'api.Company', 'api.User', 'api.Holiday', 'api.Config', 'api.Pattern', 'api.WorkType', 'api.ChangeWorkSchedule', 'api.UserWorkSchedule', 'api.Icon', ############# <- this is the 'icon' ), column=1, order=0 )) picture of Django JET interface that's missing 'icon' Also, since my admin wants to have a convenient functionality where he can directly upload images onto the database, I created a file named "dashboard_modules_views.py", following along and improvising from Django Jet documentation. Below is the dashboard_moduels_views.py import boto3 … -
Django app: can I run management command that is defined in a dependency?
My Django application called my_app pulls in a dependency called my_dependency. my_dependency declares a management command called useful_thing Is there a way I can run useful_thing directly from my_app's start.sh? I've tried calling it directly but it's not found, but maybe there's a way I can point to it. I'm new to Django and suspect this is not a sensible thing to try and do. -
How can I create a ModelViewSet for my Customer and Order Models in Django?
So I have a Customer Model. class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) and a OrderItem Model. class OrderItem(models.Model): order = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1) product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1) quantity = models.PositiveIntegerField(default=1) ready = 1 on_its_way = 2 delivered = 3 STATUS_CHOICES = ( (ready, 'ready'), (on_its_way, 'on its way'), (delivered, 'delivered'), ) status = models.SmallIntegerField(choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) I created another model ByCustomer Model class ByCustomer(models.Model): name = models.ForeignKey(Customer, on_delete=models.CASCADE) orders = models.ForeignKey(OrderItem, on_delete=models.CASCADE) I want to turn it into a ModelViewSet where it only shows the orders of the selected Customer. class By_Customer_View(viewsets.ModelViewSet): # code let's you select only one customer # and returns all the Orders that customer has I've seen something like this for @api_view @api_view(['GET']) def by_customer(request, pk): tasks = ByCustomer.objects.get(name=pk) serializer = ByCustomerSerializer(tasks, many=False) return Response(serializer.data) How would this work with ModelViewSet? I can't add extra parameters on (viewsets.ModelViewSet, pk). What other fields should I add and what am I missing? Still new to ModelViewSets so I don't know its limitations. If ModelViewSet doesn't have …