Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create a form to post multiple new objects to a model based on a series of binary choices?
I'm currently writing my first Django web application and having a lot of fun but have hit a brick wall with a page I need to render. The site is an NFL predictions game site, whereby people can pick game winners, week by week. To accomplish this I've got models for Teams, Users, Predictions, Scores (for my competition, not the NFL games), Games, and Results. The Results and Games models pull data in from NFL XML & JSON feeds. Teams is a static model for all 32 teams. The Predictions, Results, and Game models all share a GameID property. Predictions have a score field which is updated as part of a save function override on Results, which itself then updates the Scores model for each user's weekly score tally. I can add Predictions for users through the Django admin console and through the Django shell just fine - but now I need to move on to create a webpage where users can simply pick the winner of each matchup with the click of a button. I have a basic layout for this page to get me started using a function based view, which currently just lists all of the fixtures … -
counting views sometimes work, sometimes not counting
it's weird. sometimes it counts, sometimes it doesn't. I don't see anything wrong with the code, here's my code. class Post(models.Model): with_votes = PostVoteCountManager() #nothing to do with views objects = models.Manager() #nothing to do with views @property def update_view(self): self.views = self.views + 1 return self.save() and in my html I simply did <small class="text-muted ">{{ post.views }}view{{ post.views|pluralize }} | </small><span> -
Django dynamic modelForm choices doesn't work
I need to dynamically set the choices for a ModelForm's field at request-time. In the ModelForm's constructor I add the choices: class ScanSetPlotForm(ModelForm): class Meta: model = models.ScanSetPlot fields = ['scan_set_def_name', 'label_x_name', 'label_y_name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['scan_set_def_name'].choices = scan_set_module.get_form_scan_set_def_list() self.fields['label_x_name'].choices = scan_label.get_form_scan_labels_list() self.fields['label_y_name'].choices = scan_label.get_form_scan_labels_list() This works for the form entry itself - the custom choices appear in list boxes. However, when creating the model from the posted data: form = forms.ScanSetPlotForm(request.POST) I get the "Select a valid choice" error for all the fields, because the errors are done in super().init, before I've been able to add the choices. Any help would be much appreciated, thanks. -
Sending email with accented characters using django.core.mail.EmailMessage
I am trying to send an email with accented letters in the body using Django's built in send_mail() module. However, accented letters show up as question marks when the recipient opens the message. I have tried to explicitly set UTF-8 encoding with no results. html_content = u""" <p>Gentile {},<br/><br/> è stata inserita una richiesta. [...]</p> """.format(rcpt) send_mail(subject, "", mail_from, [rcpt], html_message = html_content, fail_silently=False, ) The "è" character shows up as "??" in Gmail, while I expected it to be shown as "è". Has anyone encountered this problem before? Thanks so much! -
Django Rest Framework - Versioning docs
I have a versioned API using Django Rest Framework NamespaceVersioning REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' } This works wonders and I can access all my v1 and v2 endpoints. url(r'^v1/', include((router.urls, 'v1'), namespace='v1')), url(r'^v2/', include((router.urls, 'v2'), namespace='v2')), I am also using the Built-in API documentation as suggested in the official docs from rest_framework.documentation import include_docs_urls urlpatterns = [ ... url(r'^docs/', include_docs_urls(title='My API title')) ] My problem is that I'd like to have different docs for versions 1 and 2, since some serializers are different for each version. If I do something like this: url(r'^v1/docs/', include_docs_urls(title='My API title')) url(r'^v2/docs/', include_docs_urls(title='My API title')) I receive the following warning. WARNINGS: (urls.W005) URL namespace 'api-docs' isn't unique. You may not be able to reverse all URLs in this namespace Is there a recommended way of doing this? -
Create a carousel by randomly selecting 4 images from a image folder in Django
I am trying to create a carousel in django home page. I want it to randomly select 4 images from an image folder in our static or media files that contains around 20-30 images. Each time they should be random. I am not sure how to code for it. I am very new to coding in django. Would be nice if someone can guide me how to go about doing it. -
Get count of each item separately in a queryset Django DRF
My goal is to get how many Employee related to each Department. For example, in 1 department works 3 employees, in 2 department works another 2 employees. I figured out how to get all Employee count for all Department (Department.objects.values('employee').count(). models.py: class Department(models.Model): dep_name = models.CharField(max_length=100) def __str__(self): return self.dep_name class Employee(models.Model): emp_name = models.CharField(max_length=100) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.emp_name views.py: class DepartmentView(viewsets.ModelViewSet): queryset = Department.objects.all() serializer_class = DepartmentSerializer class EmployeeView(viewsets.ModelViewSet): queryset = Employee.objects.all() serializer_class = EmployeeSerializer serializers.py: class DepartmentSerializer(serializers.ModelSerializer): class Meta: fields = ('dep_name', 'organization') model = Department class EmployeeSerializer(serializers.ModelSerializer): dep_count = serializers.SerializerMethodField() # emp_id = serializers.IntegerField(write_only=True) # emp_id = serializers.ReadOnlyField() emp_id = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all()) class Meta: fields = ('emp_id', 'emp_name', 'department', 'dep_count') model = Employee def get_dep_count(self, obj, emp_id=emp_id): # dep_count = Department.objects.values('employee').get(pk=emp_id) dep_count = Department.objects.annotate(dep_count=Count('employee')).count() return dep_count Output: You will give this: for first department {'dep_count':3, 'dep_count':2} and for the second department - {'dep_count':3, 'dep_count':2}). Desired output: first department {'dep_count':3}, second department {'dep_count':2}. As you see, I tried different approaches (using IntegerField and ReadOnlyField), also try self.instance.pk = because I need pk as I think this help to solve a problem. I hope, that rewriting get_dep_count can help me - such as adding some param, … -
Why my array in vue does't affect page data is updated?
I am writing simple application in vue where i am requesting server for data. Data are recieved and wrriten to two array of object but they are not updated to my html. I had to change delimeters because i use django. I check the data (if its really there) and tried some dummy data to try if the vue app works and every thinks seems fine. Vue app: var app1 = new Vue({ delimiters :['[[', ']]'], el: "#app-1", data:{ questions : [{text:"test", 'pk':1}], possible : [{text:"test", 'pk':1}] }, created:()=>{ let pk = $("#pk").val() SetupCSRF(); $.ajax({ type:"post", url:"/tester/test/questions", data:JSON.stringify({pk:pk}), contentType:"application/json", dataType:"json", success:(data)=>{ console.log(data); this.questions = data.questions; this.possible = data.possible; } }); } }); part of html where i use vue: <div id="app-1"> <div class="testquestions"> <div v-for="question in questions"> <div>[[question.text]]</div> <button class="remove" v-bind:value="question.pk">Remove</button> </div> </div> <div> <div class="questions" v-for="p in possible"> <p>[[p.text]]</p> <button class="add" v-bind:value="p.pk">Add</button> </div> </div> <button v-on:click="test">click</button> </div> -
Is there a way to restrict access to DRF interface while still being able to access api-endpoints?
I'm creating a site that has Django Rest Framework as its backend and ReactJS as its frontend. I have multiple api-endpoints for various data, i.e. /api/ /api/users/ /api/objects/ /api/other_objects/ etc I don't want regular users to have direct access to the DRF interface. If anyone decides to go to one of those urls, I'd prefer to redirect them to the index page if they don't have staff status. I tried to redirect users using decorators in views: from django.contrib.auth.decorators import user_passes_test def staff_check(user): if user.is_authenticated and user.is_staff: return True else: return False @user_passes_test(staff_check, login_url='/', redirect_field_name=None) @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'objects': reverse('objects-list', request=request, format=format), 'other_objects': reverse('other-objects-list', request=request, format=format) }) It works fine as far as redirection goes, but when my React app tries to fetch data from endpoints with decorators, it gets redirected as well. I know that I can instead set permissions on the views, i.e. class ObjectsList(generics.ListCreateAPIView): queryset = Object.objects.all().order_by('created') serializer_class = ObjectSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) However it still allows users to view the interface (with or without content, dependent on the permissions). Is there a way to keep endpoints accessable to React's fetch command without redirection, but still redirect users, when they … -
Must i include authentication_classes attribute in my django class view
According to the Django Rest Framework, when you want to specify what authentication to use, you can either set it as a global in your settings file e.g REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } or as a per class view e.g @authentication_classes((SessionAuthentication, TokenAuthentication)) Now what i don't seem to get is that when we specify it as a global in our settings, must we also include it as a per class view. Please i hope i am specific enough -
My rest api view always creates a new object instead of put , delete and patch
I am creating a restapi view which should be a one and all endpoint for all the crud.But no matter what i do it always executes post method .The terminal shows me that for e.g the patch method has been executed but it always does post and therefore creates a new object and it also doesn't delete the object it shows me the correct status code but the object is still there. Here's my view class StatusGET_New( generics.ListCreateAPIView, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin ): queryset = Status.objects.all() serializer_class = StatusSerializers permission_classes = [] def perform_destroy(self, instance): if instance is not None: return instance.delete() return None def get_queryset(self): qs = Status.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( content__icontains = query ) return qs def get_object(self): request = self.request passed_id = request.GET.get('pk',None) queryset = self.get_queryset() obj = None if passed_id is not None: obj = get_object_or_404(queryset,pk = passed_id) self.check_object_permissions(request,obj) return obj def get(self,request,*args,**kwargs): passed_id = self.request.GET.get('pk',None) if passed_id is not None: return self.retrieve(request,*args,**kwargs) return super().get(request,*args,**kwargs) def post(self,request,*args,**kwargs): return self.create(request,*args,**kwargs) def put(self,request,*args,**kwargs): url_passed_id = request.GET.get("pk",None) json_data = {} body_ = request.body if is_json(body_): json_data = json.loads(request.body) new_passed_id = json_data.get('pk',None) passed_id = url_passed_id or new_passed_id or None self.passed_id = passed_id … -
Unable to get POST or GET form data while using AJAX
Have been trying to filter data using django-filters. The code is working when I send a separate POST or GET request from the template. I want to avoid that extra reload that's taking place to filter the table of information. Here's the view: def search(request): dynamic_filter = [f.name for f in Controlpanel._meta.get_fields()] class UserFilter(django_filters.FilterSet): class Meta: model = Controlpanel fields = dynamic_filter user_list = Controlpanel.objects.all() user_filter = UserFilter(request.GET.get("filters[]"), queryset=user_list) chart = list(user_filter.qs.values()) return JsonResponse(chart, safe=False) Here's the AJAX code that calls this above view: $('#filter-data').on('submit', function (event) { event.preventDefault(); var dynamic = $('#filter-data').serialize(); console.log($('#filter-data').serializeArray()) $.ajax({ url: '/search/', type: 'GET', data: { filters : dynamic }, dataType: 'json', success : function(json) { console.log(json); // log the returned json to the console console.log("success"); // another sanity check }, // handle a non-successful response error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); The request.GET(or POST) currently stays empty even if I add a CSRF token and make it a POST request. I came across some question on SO stating that use of request.body solves the issue but even that was a fail. -
Filter the queryset based on the domain making the request
I'm building a SaaS that will manage several websites on the frontend with NextJS (Universal react framework) using Django Rest Framework. I want to filter the data based on the domain making the request, on the frontend I'm sending through the headers the domain and on the backend I'm filtering the data based on the domain, the problem is that when I try to return the data with the code below I get: AttributeError: 'Response' object has no attribute 'model' Here is my code: class ListProperties(generics.ListAPIView): queryset = models.Property.objects.all() serializer_class = frontend.PropertyCard filter_class = filters.PropertyFilterset pagination_class = pagination.PropertyPageNumberPagination def get_queryset(self): domain = self.request.META['HTTP_DOMAIN'] qs = self.filter_queryset(self.queryset.filter(company__domain=domain)) serialized = self.get_serializer(qs,many=True) return Response(serialized.data) The expected result should be the data that corresponds to the domain passed through the headers. Filtered (if filters are applied) and paginated. -
how can i pass id from view to button widget form template
I need to send custom emails to users after verifying their applications are correct in django admin.The emails are to be sent to a single user .so i have to pass id of current user from view to form because rendering template is via form button widget views.py def emails(request): subject = 'leave confirmation' message = ' your leav application approved' email_from = settings.EMAIL_HOST_USER x=leavdb11.objects.all() for i in x: if i.id: recipient_list=[i.email] send_mail( subject, message, email_from,recipient_list) return HttpResponse("send") forms.py class ButtonWidget(forms.Widget): template_name = 'auth_button_widget.html' def renders(self, name, value, attrs=None): context = { 'url': '/', } return mark_safe(render_to_string(self.template_name, context)) class leavapprv(forms.ModelForm): sendmail = forms.CharField(widget=ButtonWidget) this code will send email for all registered user.i want to send email for current selected user -
How to redirect login to different pages for different users in Django?
I am working on a project that requires multiple users. How am I supposed to send the users to different pages based on their roles? Here is the code for models and view related to login. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. Roles = ( ('sales', 'SALES'), ('operations', 'OPERATIONS'), ('cashier', 'CASHIER'), ('frontdesk', 'FRONTDESK'), ('client', 'CLIENT'), ) class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles, default='client') def __str__(self): return self.user.username view for login: def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username = username , password = password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("ACCount not active!!") else: print("someone tried to login and falied!") print("Username : {} and Password : {}".format(username,password)) return HttpResponse("Invalid credentials!") else: return render(request , 'NewApp/login.html' , {}) -
How to rename files while uploading multiple files in Django, through modelformset_factory()?
I am trying to read 3 files simultaneously in Django using modelformset_factory(). And these is only one model with while these files are being saved. I want to rename these three files while uploading into three different specific name.(e.g.: "mapping.csv", "tu_video.csv" and "tu_lo.csv") How can I do that? I am new to Django. Please help. -
curl command with -d converted to Python (django) POST request
I have curl command which hits API and POST message. It works perfectly if i run this from command line Generally i have similar curls (but GETs, not POSTs)i have managed to make it work, but this one (which is build similary) has "-d" option and i can't figure out how to pass this. curl -X POST "https://hostname.com:1769/v1/transfers/messages?part=PARTNER_SSL&idm=TEST" -H "accept: application/json" -H "authorization: Basic xxxxxxxxxxxxxxxxxxx" -H "Content-Type: application/json" -d "{ \"msg\": \"test\"}" my views.py looks like this: [...] send = requests.post( 'https://{}:1769/v1/transfers/messages?part={}&idm={}'.format(hostname, *form), verify='O:\\cert\cacerts.pem', headers={'Accept': 'application/json', 'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json'}, data = {'msg': 'test'} ) [...] can't make it work from level of application. Works fine when pasted curl command into command line. When launched from application i get Bad request 400 -
Create personnel code in django profile model
I want to create unique Personnel code for my users. I should consider this pattern in this code: Code length : 7 digit. first char from left side: get from USER_TYPE : user_type_code The next two char: current year example- 19 for 2019: year_code Four remaining char .create as count_code I wrote whole generate but it don't work because of this error: ImportError: cannot import name 'Profile' from 'base.models' This is my profile model and generator: class Profile(models.Model): USER_TYPE = ( (1, 'student'), (2, 'teacher'), (3, 'co-worker'),) user = models.OneToOneField(User, on_delete=models.CASCADE) Personnel_code = models.PositiveIntegerField(null=True, blank=True) created_date = models.DateField(editable=False) user_type = models.CharField(max_length=10, default=USER_TYPE[0][0],choices=USER_TYPE) def personnel_code_generator(self): user_type_code = self.user_type year_code = datetime.datetime.now().strftime("%y") last_user = self.objects.latest('created_date') year_user = self.objects.filter(created_at__year=datetime.datetime.now().year) if year_user == 0: count_code = '0001' else: count_code = str(int(last_user.Personnel_code) + 1)[3:] generated_id = int(str(user_type_code) + str(year_code) + count_code) return generated_id def save(self, *args, **kwargs): if not self.id or not self.created_date: self.personnel_code = personnel_code_generator() self.created_date = datetime.datetime.now() super(Profile, self).save(*args, **kwargs) -
populate table with initial data
I want to prepopulate some tables with initial data and also modify certian fields. Im currently doing this by writing custom management commands and populating database using python manage.py . Recently i read about fixtures and came to know its used for the same purpose .Which is the right way to do this and why or why not this should be done using the management commands? Example code in management/commands/init_test_data.py class Command(BaseCommand): help = 'Initializes test data' @transaction.atomic def handle(self, *args, **kwargs): __location__ = os.path.realpath(os.path.join( os.getcwd(), os.path.dirname(__file__))) fname = os.path.join(__location__, 'init_test_data.json') with open(fname) as f: parsed = json.load(f) for tenant in parsed.get('tenants'): self.create_tenant(tenant) def create_tenant(self, tenant): tenant_obj = Tenant() tenant_obj.name = tenant["name"] tenant_obj.subdomain = tenant["subdomain"] tenant_obj.identifier = tenant["identifier"] tenant_obj.save() for org in tenant.get('organisations'): self.create_org(tenant_obj, org) admin_email = "sysadmin_" + tenant_obj.name + "@exza.com" admin_roles = ["tenant_system_admin", "tenant_admin"] self.create_user(None, tenant_obj, admin_email, admin_roles, True, True) for asset in tenant.get('assets'): self.create_dummy_asset(tenant_obj, asset.get('name')) -
How to display file using DataTables with Django?
I am working on a project where I am retrieving data using AJAX call from django views. Then I am showing the data using jquery plugin DataTables. However I want to show or link to stored pdf file in my models but I am not able to do so. I want the file to be displayed as a hyperlink to. Here is my code: html table = $('#table_id').DataTable({ data:data, columns: [{data:'slip_id'},{data:'paid_at'},{data:'salary_slip', "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { $(nTd).html("<a href='"+oData.salary_slip+"'>"+oData.salary_slip+"</a>");}}] }); Here salary_slip is a field in models which stores pdf file. I want that whenever user clicks that link in the table cell, it will take him to the stored file. -
Django form not displaying with Multiple forms rendered to a template in a single view
I have a view which renders 2 forms to a template, but only one renders, the other doesnt display and it doesnt give me any error, but I can see that the form display when I print it in my console. This is my model for the form not showing class Organization(models.Model): name = models.CharField(max_length=255, null=True) This is the form for the model class OrganizationForm(forms.ModelForm): name = forms.CharField(max_length=255) class Meta: model = Organization fields = ['name'] This is the view which I am calling the multiple forms def signup(request): if request.method == 'POST': adminForm = AdminSignUpForm(request.POST) orgForm = OrganizationForm(request.POST) if adminForm.is_valid() and orgForm.is_valid(): adminForm.save() orgForm.save(commit=False) username = adminForm.cleaned_data.get('username') raw_password = adminForm.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('myapp:home') else: adminForm = AdminSignUpForm() orgForm = OrganizationForm() print(orgForm) return render(request, 'registration/signup_form.html', {'OrgFrom': orgForm,'Adminform': adminForm}) And this is the template I am rendering the multiple forms <form enctype="multipart/form-data" method="post" > {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{Adminform.as_p }} {{ Orgform.as_p }} <button type="submit" class="btn btn-success">Sign up</button> </form> I expect both forms to be displayed but only the Adminform displays and it gives me no error to work with -
Django urls dont work redirects to single url
All my urls in the app "products" redirects to products_list urls.py from django.conf.urls import url from .views import( product_list, search, add_product, category_single, manage_product_image, edit_product, download_product, single, ) app_name = 'products' urlpatterns = [ url(r'^', product_list, name='product-list'), url(r'^search/',search, name="search"), url(r'^add/',add_product,name='add_product'), url(r'^category/(?P<slug>.*)/$',category_single,name="category"), url(r'^(?P<slug>.*)/images/',manage_product_image,name="manage_product_image"), url(r'^(?P<slug>.*)/edit/',edit_product,name="edit_product"), url(r'^(?P<slug>.*)/download/(?P<filename>.*)$',download_product,name="download_product"), url(r'^(?P<slug>.*)/$',single,name="single_product"), ] if i type http://localhost:8000/products it sends me to the list of products which is perfect ,but typing http://localhost:8000/products/add/ also sends me to the product list which is not perfect it should be to the form to add products. views.py def add_product(request): form = ProductForm(request.POST or None) if form.is_valid(): product = form.save(commit=False) product.user = request.user product.slug = slugify(form.cleaned_data['title']) product.active = False product.save() return HttpResponseRedirect('/products/%s'%(product.slug)) context = { 'form':form, } return render(request,"products/edit.html",context) I have tried to comment all lines of code in the view.py just to render the template still does not come through ,just brings the product list. -
Django base.html responsive hamburger nav bar not functioning
i am developing simple blogging site , the problem i am facing is my navbar is not responsive , below is my navbar seen in desktop but as i decrease the size of browser , nav bar gets hidden what i need is hamburger icon on left top when i decrease the size of the screen on clicking that all navbar menu items should be visible vertically. below is my code: {% load static %} <!doctype html> <html lang="en"> <head> {% if title %} <title>{{ title }}</title> {% else %} <title>Young Minds</title> {% endif %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'blog/css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/animate.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/fonts/ionicons/css/ionicons.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/fonts/fontawesome/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/fonts/flaticon/font/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/style.css' %}"> <link href="https://fonts.googleapis.com/css?family=Hind&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Patrick+Hand&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Merienda&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Theme Style --> <!-- jquery functions --> </head> <body> <header role="banner"> <nav class="navbar navbar-expand-md navbar-light bg-light"> <div class="collapse navbar-collapse" id="navbarMenu"> <ul class="navbar-nav" style="font-family: 'Hind', sans-serif;margin-left:198px;"> {% with url_name=request.resolver_match.url_name %} <li class="nav-item" style="margin-right:15px;margin-left:-20px;"> <a class="nav-link active" href="{% url 'blog-home' %}" style="margin-top:-3px;"> <span style="font-size: 18px;">Blog </span></a> … -
Overriding save() on many-to-many fields with a 'through' field
With the code below, when performing set_instance.items.add() how can I have SetMeta.order to default to len(set.items.all()) I've tried over riding save() on SetMeta but save doesn't get called when performing add(). Also tried signals with SetMeta as the sender, but SetMeta sends a Set instance rather than a SetMeta instance. Seems like it should be simple but I can't figure it out. Ultimately, every item within a set should have an order equal to len(set_instance.items.all() models.py class Item(models.Model, AdminVideoMixin): title = models.TextField(max_length=5000) **** LOTS OF OTHER FIELDS **** class Set(Item): front_page = models.BooleanField(max_length=300, blank=False, default=False, null=False) items = models.ManyToManyField(Item, related_name='in_sets', through='SetMeta', max_length=5000,) class SetMeta(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='itemOrder', max_length=5000, ) set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name='setOrder', max_length=5000,) order = models.IntegerField(default=0, null=True,) UPDATE. Could also set order to set.items.count() -
django integration tests on microservice architure
i have to don integration testing of my django project . now it has a microservice architure where front end is in one microservice and backend is in django and is made over various microservices like let's say one microservice for authentication , one of handling some data , etc . How can i write integration test cases for this