Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django tag { % block content % } isn't working
so i just started learning django, i understand the basic tag blocks but it didn't works well on my page. i have page called index.html and question.html i write like this in index.html <body> <div> <div> sum content </div> <div> { % block content % } { % endblock % } </div> </div> </body> and like this in question.html : { % extends 'index.html' % } { % block content % } <<my content>> { % endblock % } but the content in question.html didn't show up in index.html. i've checked my setting and didn't have django-stub like in other case. and if you want to know the structure, it goes like : djangoProject1 >djangoProject1 >myweb >static >templates -index.html -question.html Thank you in advance! -
Add attribute to admin model Django
I'm trying to add an attribute to my user admin model, but it doesn't work, here is what I succeded to do (I want to add inactivity field): from django.contrib import admin from .models import User class usersAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'inactivity') admin.site.register(User, usersAdmin) Here is my model code: class User(models.Model): username = models.TextField(max_length=140, default='uid', primary_key=True) first_name = models.TextField(max_length=140, default='cn') last_name = models.TextField(max_length=140, default='givenName') inactivity = models.IntegerField(default=500) def _str_(self): return self The error occurs when I'm trying to access to my added field from my views: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) data['username'] = self.user.username data['first_name'] = self.user.first_name data['last_name'] = self.user.last_name data['inactivity'] = self.user.inactivity print(self.user) return data the error says: Traceback (most recent call last): File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\oussa\.virtualenvs\SYNEIKA-v3YFud-O\lib\site-packages\rest_framework_simplejwt\views.py", line 27, in post serializer.is_valid(raise_exception=True) … -
Updating FileField Or ImageField In Django, Django-Ninja?
enter image description here How can I assign The New Image In The ImageField ????? -
How to get current user in models.py?
I have a model like this class Orders(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) The logic is the companies to send offers to get the specific travel. When you send an offer you will not have access to that travel anymore untill the base company accept or reject your offer. So when the specific company logged in I want to show them if they sent an offer or not. The company name is saved in the user that is logged in. What I tried to do is this class Order(models.Model): @property def has_sent_offer(self): Offer.objects.filter(order=self.pk, company=request.user.company) But in the models.py I don't have access to request.user -
Django - How do you email a completed create view form
I'm working on a property management app where users can fill out an online application for a property. I want to set it up so when someone fills out an application the form gets emailed to the admin formatted with the form labels. Is there a way to email an entire formatted form with labels or am I going to have to make an email template and tag it according to how I want it to look? My example code: class ApplicationView(CreateView): redirect_field_name = '' form_class = ApplicantForm model = Applicant template_name = 'base/application.html' def form_valid(self, form): form.instance.created_by = self.request.user subject = 'New Application - {} {}'.format( form.cleaned_data.get('first_name'), form.cleaned_data.get('last_name'), ) message = '{} {}'.format( form.cleaned_data.get('first_name'), form.cleaned_data.get('last_name'), ) Application_Alert(subject, message) return super().form_valid(form) -
django CSRF_TRUSTED_ORIGINS not working as expected
Im having trouble in understanding why a post from a third party site is being rejected even though the site is added to CSRF_TRUSTED_ORIGINS list in settings.py. Im receiving a 403 error after the post stating the the csrf check has failed. I thought that adding the site to CSRF_TRUSTED_ORIGINS should make the site exempt from csrf checks. Is there something else I should have done in order to receive post requests from external origins? Im running django 3.2 CSRF_TRUSTED_ORIGINS = ['site.lv'] request headers: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,lv;q=0.8,ru;q=0.7 Cache-Control: no-cache Connection: keep-alive Content-Length: 899 Content-Type: application/x-www-form-urlencoded Host: cvcentrs-staging.herokuapp.com Origin: https://www.site.lv Pragma: no-cache Referer: https://www.site.lv/ sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" Sec-Fetch-Dest: document Sec-Fetch-Mode: navigate Sec-Fetch-Site: cross-site Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62 -
ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred while creating a Google Cloud Storage bucket
I was following this tutorial : link This is the google cloud version i used : (venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud --version Google Cloud SDK 367.0.0 bq 2.0.72 core 2021.12.10 gsutil 5.5 During the deploy process I was getting the following error: (venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud app deploy Initializing App Engine resources...failed. ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred while creating a Google Cloud Storage bucket. I've searched from various sources and they suggest running this: gcloud config set app/use_deprecated_preparation True But when I run the error appears: (venv) C:\Users\user\Desktop\python-docs-samples\appengine\standard_python3\django>gcloud config set app/use_deprecated_preparation True ERROR: (gcloud.config.set) Section [app] has no property [use_deprecated_preparation]. I running it in the project directory folder. Can anyone help me? -
Why this search doesn't work for another entry but CSS?
So I'm currently working for Harvard CS50 Project1:Wiki and I have a difficulty for this project. In my search box, it doesn't want to direct to that particular entry instead it takes me to search.html file. But when I typed CSS in the search box, it takes me to CSS entry page. Can you guys help to mend this? Thank you, here's the code I use. If it doesn't tell you enough, feel free to ask the rest of the code! Oh and by the way I use Django for this one. def search(request): if request.method == 'GET': input = request.GET.get('q') html = convert_to_HTML(input) entries = util.list_entries() search_pages = [] for entry in entries: if input.upper() in entry.upper(): search_pages.append(entry) for entry in entries: if input.upper() == entry.upper(): return render(request, "encyclopedia/entry.html", { "entry" : html, "entryTitle" : input }) elif search_pages != []: return render(request, "encyclopedia/search.html", { "entries" : search_pages }) else: return render(request, "encyclopedia/nonexistingpage.html", { "entryTitle" : input }) -
Django DRF - Sending email with html template - html template appears as plain text
I'm trying to send emails from django using a html template. It does send the email but the html is sent as plain text. How can I make the email appear as html to the receiver? I'm using Django 4.0 views.py # import file with html content html_version = 'activate_email.html' html_message = render_to_string(html_version, {'context': context }) email = EmailMessage( 'Website email verification', html_message, 'info@example.co', [user.email], ) email.send() activate_email.html {% autoescape off %} <h1>Test</h1> {% endautoescape %} -
Extract error message from django html and display in console
In debug mode, and when exceptions are not being handled, django sends a typical error in html format, is it possible in any way to capture the error message from the html to be able to print it on the console? For example, the error is: in JS, do something like: console.log(error.message) and print out: CUDA out of memory. Tried to allocate 3.14 GiB (GPU 0; 9.78 GiB total capacity; 4.28 GiB already allocated; 2.89 GiB free; 5.57 GiB reserved in total by PyTorch) -
How To Create An Article Parser Loop With Apscheduler in Django
I have a script in Django that helps me parse RSS feeds for my own daily consumption. It gets the jobs done so far. Its made 3 models: class Categories(models.Model): category_name = models.CharField(max_length=50, verbose_name='Categories') ''' Categories = ['Business', Sports, Politics, Tech] ''' class FeedSource(models.Model): feed_url = models.URLField(verbose_name='RSS Feed Link') ''' FeedSource = ['http://rss.cnn.com/rss/edition.rss', ''https://www.espn.com/espn/rss/news, 'http://rss.politico.com/politics.xml'] ''' class Posts(models.Model): ... source = models.ForeignKey(FeedSource, on_delete=models.CASCADE, verbose_name='Source') category = models.ForeignKey(Categories, on_delete=models.CASCADE, verbose_name='Category') The Apscheduler command is as follows. As you can see, there is a bit of repetition in the fetch_articles functions that parse different links because each link belongs to a different Feedsource & Category. The same applies to Handle function. Each fetch_articles function has its own scheduler. import logging from django.conf import settings from django.core.management.base import BaseCommand from apscheduler.schedulers.blocking import BlockingScheduler from django_apscheduler.jobstores import DjangoJobStore from Posts.models import Posts, FeedSource, Categories import time logger = logging.getLogger(__name__) def save_new_articles(feed, source_id, category_id): """Function that parses & saves new articles to DB""" ... if not Posts.objects.filter(guid=item.guid).exists(): post = Posts( ... guid = item.guid, source_id = selected_source_id category_id = selected_category_id ... ) post.save() def fetch_siteA_articles(): """Fetches news artices from siteA""" feed = feedparser.parse("siteA") source = FeedSource.objects.get(pk=1) source_id = int(source.pk) category = Categories.objects.get(pk=3) category_id = int(source.pk) … -
Django using a Query in a Query does not work
so I have this model : class Student(models.Model): id = models.AutoField(primary_key=True) first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) title=models.CharField(max_length=30,default="",blank=True) tel=models.CharField(max_length=50,default="",blank=True) e_mail=models.CharField(max_length=50,default="",blank=True) social_media=models.CharField(max_length=50,default="",blank=True) social_media2=models.CharField(max_length=50,default="",blank=True) social_media3=models.CharField(max_length=50,default="",blank=True) street=models.CharField(max_length=50) postal=models.CharField(max_length=50) city=models.CharField(max_length=50) country=models.CharField(max_length=50) graduation_uni=models.DateField(null=True,default=None,blank=True) graduation_ikomt=models.DateField(null=True,default=None,blank=True) certificate_no=models.CharField(max_length=50,default="",blank=True) def __str__(self): return str(self.id) + " - " +self.first_name + " " + self.last_name class Course(models.Model): id = models.AutoField(primary_key=True) course=models.CharField(max_length=50) description=models.CharField(max_length=50,null=True,default=None,blank=True) start_date=models.DateField(null=True,default=None,blank=True) end_date=models.DateField(null=True,default=None,blank=True) def __str__(self): return str(self.id) + " - " +self.course + " | " + self.start_date.strftime("%d.%m.%y") + " - " + self.end_date.strftime("%d.%m.%y") class StudentInCourse(models.Model): StudentId = models.ForeignKey(Student, on_delete=models.CASCADE) CourseId = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return str(Student.objects.get(id=self.StudentId.id)) + " in " + str(Course.objects.get(id=self.CourseId.id)) And I'd like to Display only the Students in a specific course using Queries like this (in my views.py): students_in_course=StudentInCourse.objects.filter(CourseId=id) latest_student_list = Student.objects.filter(id__in=students_in_course) Sadly, I only get an empty result. Any Ideas what I'm doing wrong? I thought with the Primary/Foreign Key relation the Filter should just work this way? Any advice will be appreciated. Greetings -
How to use variable to get attributes of another another variable in Django templates
I am trying to populate a CSS grid in a Django template with specified columns and rows. To my best understanding, I need to do something like “nested variables” in the Django template to achieve what I’m looking for. I tried this, but it does not work: {% for parent_row in parent_rows %} {{ parent_row }} <div>p1</div> <div>p2</div> {% for child_row in children_rows %} <div> {{ child_row}} </div> {% for guy in guys %} <input type=”text” value=”{{guy}}.{{child_row}}”></input> {% endfor %} {% endfor %} {% endfor %} The {{guy}}.{{child_row}} neither some of the similar variants I tried do not work. I manage to get the result I'm looking for by just writing the whole HTML open, and then by looping through each guy on separate rows, as I can use for example guy.name to get the desired value to each row, but this means lots of repetition. parent_rows could look something like this for example: “names”, “contact_information”, “hobbies” children_rows could look something like this for example: “forename”, “family_name”, “phone_number”, “mail”, “favourite_hobby” and two records in the guys would be like this (both identical, to ease illustration): “forename”: “Mike” “family_name”: “McMediocre” “phone_number”: “123” “mail”: “mike@mediocre.com” “favourite_hobby”: “tennis” I am trying to populate … -
Django custom model manager for derived class - filtering on base class attribute
I am using Django 3.2 I have the following models: class AuthoriseableApprovedManager(models.Manager): def get_queryset(self): return super(AuthoriseablePendingManager, self).get_queryset().filter(computed_status=AUTHORISATION_STATUS_APPROVED) class Authorisable(models.Model): # various fields ... approved_objects = AuthoriseableApprovedManager() class ApprovedPublishedArticlesManager(models.Manager): def get_queryset(self): return self.approved_objects.filter(is_published=True) class Article(Authorisable, # Other base classes ): # various fields # .... objects = models.Manager() # The default manager. approved_published_articles = ApprovedPublishedArticlesManager() class Meta: ordering = ('-created_at', ) I have the following code in my views.py class ArticleListView(ListView): model = Article def get_queryset(self): return self.model.approved_published_articles.all() # <- Barfs here ... I get the error message: 'ApprovedPublishedArticlesManager' object has no attribute 'approved_objects' Which makes sense, since ApprovedPublishedArticlesManager does not derive from Authorisable. How do I create a custom manager that allows me to filter based on base class properties - does my custom manager have to derive from models.Manager and the relevant base class (Authorisable in this case)? -
Django app is crashing Chrome browser on Android
I have hosted a Django app on pythonanywhere.com . It works fine on desktop but crashes Chrome on Android. It works fine on another Android browsers and Safari too. It just a simple Django application with a single html page. One thing I found out was, it crashes only when I turn on 'Forced HTTPS' on pythonanywhere. If I turn it off it works fine. It's the bug with only this app. My other hosted apps works fine. Hosted app: https://shantanu2k17.pythonanywhere.com/ CAUTION : don't open it on Android chrome, your browser will crash. Open it in incognito mode instead. Code : https://github.com/Shantanu2k19/testing2.git Please help me find the bug. -
Django DRF - Send email with html template - django.template.exceptions.TemplateDoesNotExist
I've added sending emails in my Django project and now I want to use html templates for the content of these emails. I've created a templates folder and put my template in there. Then I added the template path to TEMPLATES in settings.py. (See code below) But now I'm getting the following error. django.template.exceptions.TemplateDoesNotExist: activate_email.html Even though the template exists: views.py # import file with html content html_version = 'activate_email.html' # 'templates/activate_email.html' also doesn't work html_message = render_to_string(html_version, {'context': context, }) email = EmailMessage( 'MySubject', html_message, 'info@example.co', [user.email], ) email.send() settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'django_backend/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Can anyone point me in the right direction what I'm doing wrong? I'm using Django 4.0 and DRF 3.13.1 -
Bootstrap 5 get rid of big number input fields
I have a table that can be used as a form, which all quite works well, but I do not manage to reduce the space a number input takes: here is a view from when it is not a form: What argument can I put in th class or td so the green areas get minimized? Fixed width in pixels would be an option (is this possible?). I already tried <th class="w-25"> or <td class="w-25"> (and both). I achieved adding a class="w-50" argument to the number input fields, so this seems to work. <table class="table table-striped table-hover"> <thead class="thead-dark"> <tr> {% for col in header %} {% if col == "number" %} <th>{{ col }}</th> {% else %} <th>{{ col }}</th> {% endif %} {% endfor %} <th class="text-end">action</th> </tr> </thead> <tbody id="table"> <tr> {% for key, value in product.data.items %} <td>{{ value }}</td> {% endfor %} </tr> </tbody> </table> -
How to add attributes in admin user model in django
I'm trying to add an attribute to my user admin model, but it doesn't work, here is what I succeded to do (I want to add inactivity field): from django.contrib import admin from .models import Patient, User,Group class usersAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name', 'inactivity') fieldsets = admin.ModelAdmin.fieldsets + ( ('Extra Fields', {'fields': ('favourite_colour',)}), ) -
Django form class widget with drop down populated from database
I am using Django 3.2 and I am trying to create a form class that has a field (category) populated from a database model. This is a snippet of my form class: class ArticleForm(forms.ModelForm): # ... class Meta: model = Article fields = ['title', 'teaser', 'category', 'guest_author','content', 'tags', 'is_published'] categories = [] #forms.ModelChoiceField(queryset=ArticleCategory.objects.all().order_by('name')) widgets = { 'guest_author': forms.TextInput(attrs={'class': 'form-control input'}), 'title': forms.TextInput(attrs={'class': 'form-control input'}), 'teaser': forms.Textarea(attrs={'class': 'form-control input'}), 'category': forms.Select(choices=categories, attrs={'class': 'form-control input'}), 'content': forms.Textarea(attrs={'class': 'form-control input'}), 'tags': forms.TextInput(attrs={'class': 'form-control input'}), 'is_published': forms.CheckboxInput(attrs={'class': 'form-control-input'}) } I found out if I created the field as an instance attrribute like this: category = forms.ModelChoiceField(queryset=ArticleCategory.objects.all().order_by('name')) Then I am able to use the form (with no errors raised). But I want to be able to specify the widget to use for that field, using the above declaration - is there anyway to do this - or am I restricted to simply declaring the field as an instance variable of the form? -
javascript passed string itself instead of index lenght, whats wrong with my code?
I am trying to pass the item id and item id index when a button is clicked. But the code is throwing different result. For your reference, I have attached expected result and obtained result. Any help will be highly appreciated if(localStorage.getItem('cart')==null){ var cart={}; } else{ cart = JSON.parse(localStorage.getItem('cart')); } $(document).on('click','.btn-cart',function(c){ c.preventDefault(); console.log("Add to Cart Button clicked"); var item_id = this.id.toString(); console.log(item_id); if(cart[item_id]!=undefined){ cart[item_id] =cart[item_id] + 1 } else{ cart[item_id]= 1 } console.log(cart); localStorage.setItem('cart',JSON.stringify(cart)); console.log(Object.keys(cart).length); }); I am expecting this: But it happened this: -
How to implement the function, I forgot the password and send an email to change it in Django
I would like to implement a "forgot password" function, and at that point an email would be sent so that she would be able to change her own password. I have not found documentation on this. Someone could show me a way. Thanks for listening! -
Cannot install psycopg2 with Github Actions due to distutils
I am trying to setup CI/CD for my Django project on Github. I deploy it to Heroku, which requires django-heroku package, which in turn depends on the psycopg2 package. When I'm trying to run this workflow: build-django: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.10' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Django Tests run: | python manage.py test I get a huge error log which culminates in this: Copying psycopg2.egg-info to /opt/hostedtoolcache/Python/3.10.1/x64/lib/python3.10/site-packages/psycopg2-2.9.2-py3.10.egg-info running install_scripts Traceback (most recent call last): <...> ModuleNotFoundError: No module named 'distutils.command.bdist_wininst' Everything checks out on my machine. Why would I get this message? The requirements.txt file is setuptools~=44.1.1 wheel~=0.37.1 django~=3.2.9 djangorestframework~=3.12.4 pip~=20.3.4 pytz~=2021.3 sqlparse~=0.4.2 asgiref~=3.4.1 h11~=0.12.0 attrs~=21.2.0 trio~=0.19.0 outcome~=1.1.0 sniffio~=1.2.0 sortedcontainers~=2.4.0 cffi~=1.15.0 idna~=3.3 six~=1.16.0 cryptography~=36.0.1 certifi~=2021.10.8 urllib3~=1.26.7 selenium~=4.1.0 pycparser~=2.21 wsproto~=1.0.0 gunicorn~=20.1.0 django-heroku -
Get the Entire Tree Data using Tree query sets and Querysets from Django
I was trying to get the data from all the tree query set and query set using django ORM and Django MPTT. The Hierarchy of the DB tables is as follows: T1 (MPTT Model) T2 (MPTT Model) T3 (Django Model) T4 (Django Model) T5 (Django Model) T6 (Django Model) I have two MPTT models from which I can get the tree Query sets using logged in user filter, however, for retrieving all the other tables data, need to evaluate from other django models. Is it Possible to get all the data in single Queryset Evaluation set so that it will reduce the load on the Request? The Required Data : { key1: t1.value1, key2: t2.value2, key3: t3.value1, key4: [t4.values_list], key5: [t5.values_list], key6: t6.value3 }, { key1: t1.value1, key2: t2.value2, key3: t3.value1, key4: [t4.values_list], key5: [t5.values_list], key6: t6.value3 }, { key1: t1.value1, key2: t2.value2, key3: t3.value1, key4: [t4.values_list], key5: [t5.values_list], key6: t6.value3 } -
reCaptcha Enterprise in django forms without django-recaptcha
How can I implement new reCaptcha Enterprise within django on the form without using old django-recaptcha? -
test complex django method containing multiple ManyToMany field using pytest
my app : account_engine has following models: class Company(models.Model): name = models.CharField(max_length=200) class Location(models.Model): name = models.CharField(max_length=200) class Client(models.Model): name = models.CharField(max_length=200) class CustomPermission(models.Model): url_name = models.CharField(max_length=200) url = models.CharField(max_length=200) class CustomRole(models.Model): name = models.CharField(max_length=200) class RoleSpecificPermission(models.Model): role = models.ForeignKey(CustomRole, on_delete=models.CASCADE) permission = models.ManyToManyField(CustomPermission, blank=True) class GroupSpecificPermission(models.Model): group = models.ForeignKey(CustomGroup, on_delete=models.CASCADE) permission = models.ManyToManyField(CustomPermission, blank=True) class UserDetail(models.Model): mobile = models.CharField(max_length=10) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) client = models.ManyToManyField(Client, blank=True) role = models.ManyToManyField(CustomRole, blank=True) group = models.ManyToManyField(CustomGroup, blank=True) special_permission = models.ManyToManyField(CustomPermission, blank=True) def get_all_permissions(self): # adding all permissions in set to remove duplicates final_set = set() role_level_prem = RoleSpecificPermission.objects.filter(role__in = list(self.role.all())) group_level_prem = GroupSpecificPermission.objects.filter(group__in = list(self.group.all())) for each_permission_set in role_level_prem: for each_permission in each_permission_set.permission.all(): final_set.add(each_permission) for each_permission_set in group_level_prem: for each_permission in each_permission_set.permission.all(): final_set.add(each_permission) for each_permission in self.special_permission.all(): final_set.add(each_permission) return list(final_set) I want to test the method get_all_permissions or model UserDetail class using pytest, pytest-django and mixer my test is as follows: class TestUserDetail: def test_method_get_all_permissions(self): roles = mixer.cycle(10).blend('account_engine.CustomRole') groups = mixer.cycle(10).blend('account_engine.CustomGroup') permissions = mixer.cycle(5).blend('account_engine.CustomPermission') special_permissions = mixer.cycle(5).blend('account_engine.CustomPermission') obj = mixer.blend('account_engine.UserDetail', role=mixer.sequence(*roles), group=mixer.sequence(*groups), permission=mixer.sequence(*permissions), special_permission=mixer.sequence(*special_permissions),) assert obj.get_all_permissions() == all_the_possible_permissions_for_which_i_need_your_inputs I'm just lost and not able to write test to verify if my method works …