Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Allauth saving profile information with signup form
I am new in Django, I am using allauth app to create a user registration. There are some extra field I wish to have in my signup form. Not only (username, first_name, last_name) I which to include(info) to registration form. When I submit the registration form only the first_name and the last_name are saved in database, info do not save, I guess it should be saved in Profile Model, but not there. class Profile(models.Model): user = models.OneToOneField(User) info = models.CharField(max_length=128) class CustomSignUpForm(Signup Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) info = forms.CharField(max_length=50) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() user.profile.info = self.cleaned_data['info'] user.profile.save() ACCOUNT_FORM = 'signup' 'myapp.forms.CustomSignupForm' -
Is SQL or NoSQL a better choice for a beginner Django project?
When it comes to actually deploying a Django project, is SQL software, like PostegreSQL, or NoSQL, like MongoDB, a better option? To evaluate which might be a better choice, you can consider: requires less changes to the actual code of the already existing project - for example having to re-do the models structure, has correct integration with the backend, i.e.: some years ago MongoDB wouldn't integrate with the Django backend, is more beginner friendly. -
Extend Django base.html in multiple separate sections?
My base.html divides the page into two equal columns. <body> <div class="column-left"> <\div> <div class="column-right"> <\div> </body> On homepage.html, I would like to extend these columns separately and add some html content to each column e.g. an image. *Extended base.html column-left* <img src=image_left /> *Extended base.html column-right* <img src=image_right /> Is it possible to extend base.html's columns separately on the homepage.html? -
Django : Compress image from form, then upload it to S3 (creates multiple images...)
I spent the day at trying to make image compression and upload to S3 to work. I feel disappointed, and I hope that you can help me. Ok, I'm creating an ecommerce platform where users can sell things. They need to upload images. I created a modelForm based on my Thing model. I was saving files on the disk before but I need to use S3 for better performances. I have this for the moment : class Thing(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True, null=True, blank=True) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField(max_length=240, null=True) state = models.ForeignKey('State', related_name='state', on_delete=models.CASCADE) shipping_carrier = models.ForeignKey('Carrier', related_name='carrier', on_delete=models.CASCADE) shipping_weight = models.FloatField() # Price Auto-Calculation upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='thing_upvotes') downvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='thing_downvotes') image1 = models.ImageField(upload_to='things', blank=False, default='image1.jpg') image2 = models.ImageField(upload_to='things', blank=True) image3 = models.ImageField(upload_to='things', blank=True) # max res 1020,573 created_date = models.DateTimeField(default=timezone.now, verbose_name="Publication date") category = models.ForeignKey('Category', related_name='category', on_delete=models.CASCADE) class Meta: verbose_name = "thing" ordering = ['created_date'] # Self method, gives a fast title string of the thing def __str__(self): return self.title # Gives the thing url after creating it for example def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): super().save(*args, **kwargs) im = Image.open(self.image1) in_mem_file = io.BytesIO() im.save(in_mem_file, quality=30, … -
Why is my BeautifulSoup text search with special characters failing to retrieve my element?
I'm using Python 3.7, Django 2 and Beautiful Soup 4. I have this snippet of HTML ... <p class="tagline ">submitted&#32; on 2/20/2019</p> I would like to retrieve this element and so I have created the below code ... bs = BeautifulSoup(html, features="lxml") ... pattern = re.compile(r'^submitted\&\#32\;') submitted_elt = bs.find(text=pattern) Unfortunately, the submitted_elt is always None. What else do I need to do to tweak my regular expression to search for this element? I don't want to have the word "submitted" all by itself, because that will return too many elements. -
How can I get id="demo" value of html range slider in my django app?
I'm creating my first django app. I want to interactively show some plots. here is the link for my app(hosted on pythonanywhere): https://physics.pythonanywhere.com I have created a slider in my home.html <!DOCTYPE html> <html> <head> <h1><p><font style="font-family:verdana;">Unit Intensity Plots</font></h1> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .slidecontainer { width: 35%; } .slider { -webkit-appearance: none; width: 100%; height: 15px; border-radius: 5px; background: #d3d3d3; outline: none; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s; } .slider:hover { opacity: 1; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 25px; height: 25px; border-radius: 50%; background: #4CAF50; cursor: pointer; } .slider::-moz-range-thumb { width: 25px; height: 25px; border-radius: 50%; background: #4CAF50; cursor: pointer; } </style> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} <p><font style="font-family:verdana;size=5">&emsp;&emsp;&emsp;&emsp;&emsp;Angle Range Slider</font></p> <div class="slidecontainer"> <input type="range" min="0" max="360" value="0" class="slider" id="myRange"> <p><font style="font-family:verdana;"> Value: <span id="demo"></span>&#176;</p> </div> <script> var slider = document.getElementById("myRange"); var output = document.getElementById("demo"); output.innerHTML = slider.value; slider.oninput = function() { output.innerHTML = this.value; } </script> </body> </html> Now i want to use this slider to change the x axis range as the slider is moved. For this I need to get the value of slider in my django-views.py as … -
This field is required. Error with ImageField django
I'm getting 'This field is required' error while uploading image. I don't understand why I get this error, my model is very basic, but I don't know why and where i'm getting error. Some help would be apreciate. my models is class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) 'my views is' class PostCreateViews(CreateView): model = Post fields = ['title','img','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and html code <div class="blog_list"> <form method="POST"> {% csrf_token %} <h2 class="blog_heading">New Post</h2> <fieldset class="form-group" id="new"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> can anyone plz help me with this????? -
whenever i go the next class hide id=q2 in multistep form it redirects me only when i click ctrl and press next it goes to the part in new tab
this is my code applyonline.html basically after the beneficicary part is completed the husband part should be shown but when i click next after filling up the form it redirects me back to beneficiary and only when i click ctrl+next it goes to the husband details but in a new tab <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/" enctype="multipart/form-data"> <div class="group"> <div class="hide" id="q1"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <!--Beneficiary Details--> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="[0-9]{4}[0-9]{4}[0-9]{4}" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <input type="file" name="adhaarcopy" /> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Give consent to collect adhaar card data </label> <div class="invalid-feedback"> You … -
How to close a popup when another popup is open using JavaScript?
I'm working on a Python/Django web application, and I don't have much knowledge of JavaScript yet. The answers I've googled suggest a bit of a different approach, and I can't adjust those solutions to my code due to my yet little knowledge of JS. Will be grateful for helping me out. Thanks in advance! So, I have a few popup windows, which have different IDs and they're all opened and closed with the same two JavaScript functions by passing thir IDs as a $target variable. I also want to close any opened popup window if another popup is opened by the user, so only one can be opened at the same time, and also close a popup window if the user clicks a glyphicon button (the same that opened that popup window with the first click). Here's my code: html template <script> function popup($target) { document.getElementById($target).style.display = "block"; } function closepopup($target) { document.getElementById($target).style.display = "none"; } </script> Example of where these functions are called (same template): <a class="btn btn-default" onclick="popup('add')" style="position: absolute; right: 2%; bottom: 10%; padding: 6px;"><span class="glyphicon glyphicon-pencil"></span></a> <div class="form-popup popupfont" id="add-important"> <form action="{% url 'add-general' %}" method="post" class="form-container"> {% csrf_token %} <label for="task_text">Add a task:</label> <input type="text" … -
Need to make api in djnago , provided with json file
Provided the JSON structure of a search result for one the location, you are requested to make an API that will expect three mandatory parameters : a. Latitude b. Longitude c. Type of service (Business, Couples, Solo travel, Family, Friends getaway) Based on the provided inputs the API should return the hotels present in the radius of 100 Kms of provided latitude and longitude. Attachments area { "0-4": { "HotelSearchResult": { "no_of_nights": 5, "no_of_hotels": 71, "no_of_adults": 2, "more_results": false, "CheckInDate": "23/04/2020", "CheckOutDate": "28/04/2020", "NoOfRooms": 1, "TraceId": "5l4jwkkzoke3ls3l3tw5ihsnka", "CityId": null, "PreferredCurrency": "INR", "RoomGuests": [ { "ChildAge": null, "NoOfAdults": 2, "NoOfChild": 0 } ], "ResponseStatus": 1, "HotelResults": [ { "HotelPicture": "https://www.tratoli.com/grn_mask/?path=H!0144442/2fae1d4b89a5e336f63b64c9f6803b1f.jpg", "ResultIndex": 0, "Latitude": 25.10882966, "Longitude": 55.18319964, "TripAdvisor": { "address_obj": { "street1": "Sheikh Zayed Road", "street2": "", "city": "Dubai", "state": "Emirate of Dubai", "country": "United Arab Emirates", "postalcode": "450011", "address_string": "Sheikh Zayed Road, Dubai 450011 United Arab Emirates" }, "latitude": "25.1086", "rating": "4.0", "trip_types": [ { "name": "business", "value": "477", "localized_name": "Business" }, { "name": "couples", "value": "409", "localized_name": "Couples" }, { "name": "solo", "value": "294", "localized_name": "Solo travel" }, { "name": "family", "value": "238", "localized_name": "Family" }, { "name": "friends", "value": "265", "localized_name": "Friends getaway" } ], "longitude": "55.183365", "review_rating_count": { … -
How to get list from QuerySet[]
If I have a QuerySet [Language: fifty, Language: grey, Language: shade] in my console API,How do I get [Language: fifty, Language: grey, Language: shade] .. So that the QuerySet is remove and I get a list -
Authenticate a Django/Appengine project using Firebase
I currently have google and facebook authentication for my application. I would like to add firebase-auth as the backend for my Django/appengine backend. The tutorial i followed (https://cloud.google.com/appengine/docs/standard/python/authenticating-users-firebase-appengine) only show how to use it for a python Flask backend. Does anyone know how to set up firebase in a Django backend that uses appengine? -
Many_to_many --> FieldError: Related Field got invalid lookup: contains
I have a two two models: Doctor and Patient. Doctor is defined as follows: class Doctor(models.Model): patients = ManyToManyField('patients.Patient', related_name="%(class)ss", blank=True) I want to get all the doctors that have a specific patient. I tried: doctors = Doctor.objects.filter(patients__contains=patient) it doesnt' seem to work...any idea? -
"MultipleObjectsReturned" from db on template
if there are two db entries for "Anhang" or more then i get the ERROR: "all() takes 1 positional argument but 2 were given" views.py @login_required() def anhang_view(request, id=None): contextoo = {} item = get_object_or_404(Kunden, id=id) kontaktform_form = KontaktForm(request.POST or None, instance=item) creatorform_form = CreateANform() contextoo['creatorform_form'] = creatorform_form if Kunden.objects.filter(KN=item.KN).exists(): item14 = Kunden.objects.get(KN=item.KN) editkontakto_form = InfoKontaktoForm(request.POST or None, instance=item14) contextoo['editkontakto_form'] = editkontakto_form if Anhang.objects.filter(KN=item.KN).exists(): item15 = Anhang.objects.all(Anhang.objects.filter(KN=item.KN)) ANform_form = ANform(request.POST or None, instance=item15) contextoo['ANform_form'] = ANform_form if request.method == 'POST': creatorform_form = CreateANform(request.POST) if creatorform_form.is_valid(): cre = creatorform_form.save(commit=True) cre.save() return redirect('/Verwaltung/KontaktAnlegen') else: return render(request, 'blog/anhang.html', contextoo) ERROR: all() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/Verwaltung/Anhang/10 Django Version: 3.0.1 Exception Type: TypeError Exception Value: all() takes 1 positional argument but 2 were given anhang.html . . . {% if ANform_form %} <table class="table" width="100%" border="0" cellspacing="0" cellpadding="0"> <thead class="thead-light"> <tr> <td width="11%" border="0" cellspacing="0" cellpadding="0"> <b> {% csrf_token %} {{ ANform_form.instance.Thema }} </b> </td> <td width="15%" border="0" cellspacing="0" cellpadding="0">Username</td> <td width="19%" border="0" cellspacing="0" cellpadding="0">Password</td> <td width="18%" border="0" cellspacing="0" cellpadding="0">E-Mail</td> <td width="37%" border="0" cellspacing="0" cellpadding="0">Anhang</td> <td> </td> </tr> </thead> <tbody> <td></td> <td> {% csrf_token %} {{ ANform_form.instance.Username }} </td> <td> {% csrf_token %} {{ ANform_form.instance.Password … -
Django saving a form with unique constraint
I have a simple Profile model linked to Djang user model that keep alias. Alias has a unique constraint in the model. To update the alias, I created a model form, but can't figure out how to exclude the unique constraint when the user just push the submit button with no change to the alias. The form raise an error because of unique constraint. Here's the model and form definition with part of the view that handle the form: models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) alias = models.CharField( "Alias", max_length=50, unique=True, null=True ) forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ['alias', ] And the views.py def membership(request): if request.method != 'POST': profile = Profile.objects.get(user=request.user) form = ProfileForm(initial={'alias': profile.alias, 'user': request.user}) elif request.POST.get('profile_update', None) == 'profile_update': form = ProfileForm(request.POST) if form.is_valid(): form.save() -
How can i use loop to create list of fields
Recently, I start project using django 3 i face the problem with model I wanna create the modelform and the field is a list: Like answer1, answer2, ..., answer10,... ''' class Quiz(models.Model): question = models.CharField(max_length=30) def __str__(self): return self.question quiz = Quiz.objects.all() class Answer(models.Model): answer1 = models.CharField(max_length=20) answer2 = models.CharField(max_length=20) answer3 = models.CharField(max_length=20) ... answer10 = models.CharField(max_length=20) ... How i use loop or something to declare this answer field Can i set my table collum name of answer1 = qiz[0].question ''' -
Postgresql is not getting data from form
I'm learning django now, and i'm facing a problem, I create a form to submite data in my database, but the problem is when i click on submit button, postgres isn't receiving data, I cant understand the problem. This is my contact form This is my database This is my html code <form action="." method='post' class="p-5 bg-white"> <h2 class="h4 text-black mb-5">Contact Form</h2> {% csrf_token %} <div class="row form-group"> <div class="col-md-6 mb-3 mb-md-0"> <label class="text-black" for="fname">First Name</label> <input type="text" id="fname" class="form-control rounded-0"> </div> <div class="col-md-6"> <label class="text-black" for="lname">Last Name</label> <input type="text" id="lname" class="form-control rounded-0"> </div> </div> <div class="row form-group"> <div class="col-md-12"> <label class="text-black" for="email">Email</label> <input type="email" id="email" class="form-control rounded-0"> </div> </div> <div class="row form-group"> <div class="col-md-12"> <label class="text-black" for="subject">Subject</label> <input type="subject" id="subject" class="form-control rounded-0"> </div> </div> <div class="row form-group"> <div class="col-md-12"> <label class="text-black" for="message">Message</label> <textarea name="message" id="message" cols="30" rows="7" class="form-control rounded-0" placeholder="Leave your message here..."></textarea> </div> </div> <div class="row form-group"> <div class="col-md-12"> <input type="submit" value="Send Message" class="btn btn-primary mr-2 mb-2"> </div> </div> </form> This is my models.py from django.db import models class Form(models.Model): fname=models.CharField(max_length=300) lname=models.CharField(max_length=300) email=models.EmailField() subject=models.CharField(max_length=300) message=models.TextField() This is my views.py from django.shortcuts import render from .models import Form def test(request): if request.method == 'POST': request.POST.get('fname') request.POST.get('lname') request.POST.get('email') request.POST.get('subject') request.POST.get('message') … -
Error: expected pk value, received list for foreignkey field
I cannot save multiple values for the Foreignkey field when adding instances to the database. I don't understand exactly what the problem is: in my code or in the format of the JSON object being passed. models.py class VendorContacts(models.Model): contact_id = models.AutoField(primary_key=True) vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE) contact_name = models.CharField(max_length=45, blank=True) phone = models.CharField(max_length=45, blank=True) email = models.CharField(max_length=80, blank=True, unique=True) class Meta: db_table = 'vendor_contacts' class VendorModuleNames(models.Model): vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE, primary_key=True) module = models.ForeignKey(Modules, models.DO_NOTHING) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'vendor_module_names' unique_together = (('vendor', 'module'),) class Vendors(models.Model): COUNTRY_CHOICES = tuple(COUNTRIES) vendorid = models.AutoField(primary_key=True) vendor_name = models.CharField(max_length=45, unique=True) country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT) timestamp = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'vendors' unique_together = (('vendorid', 'timestamp'),) serializers.py class VendorsSerializer(serializers.ModelSerializer): class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda', 'parent_vendor',) class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( 'contact_name', 'phone', 'email',) class VendorModulSerializer(serializers.ModelSerializer): class Meta: model = VendorModuleNames fields = ('module',) views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" serializer_class = (VendorsSerializer) def post(self, request, *args, **kwargs): vendor_serializer = VendorsSerializer(data=request.data) vendor_contact_serializer = VendorContactSerializer(data=request.data) vendor_modules_serializer = VendorModulSerializer(data=request.data) try: vendor_serializer.is_valid(raise_exception=True) \ and vendor_contact_serializer.is_valid(raise_exception=True) \ and vendor_modules_serializer.is_valid(raise_exception=True) \ vendor = vendor_serializer.save(user_id=request.user) vendor_contact_serializer.save(vendor=vendor) vendor_modules_serializer.save(module= … -
How to Save Slug Automatic in Django?
Here is my code for saving slug automatically. But it doesn't work and I don't know why! I can't be totally wrong. Help me to get out. from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class Article(models.Model): title = models.CharField(max_length=50) body = models.TextField() slug = models.SlugField(null=False,unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) But in django Admin panel I have to save slug manually But I want to save it automatically. Help me to understand this. Thanks Good People. -
Can I add a search function on a Django template to search all templates in the app
I have 100's of pages of templates within my app. I want to add a search bar on my home page so someone can search for something and it returns the URLs to potential results (or something similar). Is this possible? Any help whatsoever is appreciated. -
Django email subject "EMAIL_SUBJECT_PREFIX" is ignored
I'm using Django + Wagtail + Allauth and I want to change the subject when a user register or forget her/his password: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_SUBJECT_PREFIX = '[Django] ' While I set EMAIL_SUBJECT_PREFIX to '[Django] ', I'm having '[example.com] ' instead. web_1 | Content-Type: text/plain; charset="utf-8" web_1 | MIME-Version: 1.0 web_1 | Content-Transfer-Encoding: 7bit web_1 | Subject: [example.com] Password Reset E-mail web_1 | From: webmaster@localhost web_1 | To: me@me.com web_1 | Date: Wed, 26 Feb 2020 15:04:41 -0000 web_1 | Message-ID: <158272948175.190.1882653498152410368@69079ce78170> Do you know why ? And if there is another way to change the prefix ? -
Django: use on_delete on certain conditions
I have this model with a Foreign Key and three values that can be null, if I want to delete the Ind model, I would only be able to do it if these values are, in fact, null, if not, I can't delete it. I've searched a bit and couldn't find anything that would help me, is it doable? class Det(models.Model): ind = models.ForeignKey(Ind, on_delete=models.PROTECT) y_1 = models.CharField(max_length=80, null=True) y_2 = models.CharField(max_length=80, null=True) y_3 = models.CharField(max_length=80, null=True) -
Pycharm HTML syntax colour coded not working
Been following a tutorial on Youtube about building an app on Django. In pictures below you can see in his IDE that the same piece of HTML code is formatted, and I think this is why I'm running into issues when running my server. Anyone know how to fix this please? The code on the tutorial: My version: Would be really grateful for any help! -
Django get random objects from database
I have a database with a million+ columns and I want to return a 100 random objects from that database. After searching the web for a solution I saw that there is a big argument about the order_by['?'] approach and it's alternatives(Even in the Django official documentation!), In addition, most of the discussions about this issue are from 2010+-. So, I'm wondering what is the best practice to generate random objects from my Djando model. I saw in the Django documentation that it might based on the database itself, so is it matter if it MySQL or PostgreSQL or something else? or if it depends on the backend itself (AWS RDS or their competitors) Here's my model: class BasicPost(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) published = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=False) body = models.TextField(max_length=999) media = models.ImageField(blank=True) def get_absolute_url(self): return reverse('basic_post', args=[str(self.pk)]) def __str__(self): return self.title Thanks! -
django-tenant and django resframework testing
I'm trying to switch to test driven development. But for that I need to understand unit test :) I got the following problem. I'm using Django rest framework and django-tenants in combination. So far so good. However to test anything you need to make a tenant. class Test1(TenantTestCase): def setUp(self): super().setUp() self.client = TenantClient(self.tenant) Once you do so your tenant is setup. But if I was to test the API the client is the TenantClient and not the APIClient. The testcase is TenantTestCase. So my question. How do you combine the two?