Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom user, cant login to django admin panel
I created my custom user which uses phone number as username. but for some reason, I can't log in to the admin panel. Note: I can create a superuser through cli successfully. custom User model: class User(AbstractBaseUser, PermissionsMixin): """ Custom user model """ phone = PhoneNumberField(unique=True) full_name = models.CharField(max_length=255) verification_code = models.CharField(default="", max_length=5) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "phone" def __str__(self): return self.full_name custom user Manager: class UserManager(BaseUserManager): def create_user(self, phone, full_name, password=None, **extra_fields): validate_international_phonenumber(phone) if not phone: raise ValueError("a phone number must be provided.") user = self.model( phone=phone, full_name=full_name, verification_code = generate_verification_code(), **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): validate_international_phonenumber(phone) user = self.create_user(phone, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user user serializer class: class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = ["id", "phone", "full_name"] extra_kwargs = { "id": {"read_only": True} } -
Python-Django: Add permissions to specific groups after a model is created
I have this group known as "administrator" and its suposed to have permissions to create, view, change and delete any model. So the thing is that I want to, after a new model is created (not instanced) that my system automatically detect this new model and give all permissions to my group. -
I am unable to retrieve content of ace editor in django
I am working on app which runs the c++ code in webpage. For that I am trying to use Ace editor as code editor. I am able to write code in it. I used django-ace here. But how to retrieve content in my views.py file. Below is the forms.py file from .models import Snippet from django import forms from django_ace import AceWidget class SnippetForm(forms.ModelForm): class Meta: model = Snippet widgets = { "text": AceWidget(mode='c_cpp', theme='twilight',width="800px", height="600px",), } exclude = () below is views.py file : from .forms import SnippetForm from .models import Snippet from django.shortcuts import render, redirect def simple(request): if request.method == 'POST': form = SnippetForm(request.POST) print('This is form : ', form) if form.is_valid(): form.save() return render(request, "snippets.html", { "form": form, "snippets": Snippet.objects.all() }) else: form = SnippetForm() return render(request, "snippets.html", { "form": form, "snippets": Snippet.objects.all() }) below is html file: <!DOCTYPE html> <html> <head> <title>An simple example with django-ace</title> {{ form.media }} </head> <body> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"/> </form> </body> </html> when I am printing form in views.py file I am getting output like this: This is form : <tr><th><label for="id_text">Text:</label></th><td><div class="django-ace-editor"><div style="width: 800px" class="django-ace-toolbar"><a href="./" class="django-ace-max_min"></a></div><div class="django-ace-widget loading" data-behaviours="true" data-mode="c_cpp" … -
Django ORM query returns wrong number of items
In my application users can create lists and add influencers to them. My User and InfluencerList models have M2M relation. InfluencerList model have also M2M relation with InstagramInfluencer, YoutubeInfluencer, ... Here is my query for getting users all lists and influencer counts in it, which works finely: users_all_lists = request.user.lists.all().annotate( instagram_count=Count('influencers', distinct=True), youtube_count=Count('youtube_influencers', distinct=True), tiktok_count=Count('tiktok_influencers', distinct=True), twitch_count=Count('twitch_influencers', distinct=True), clubhouse_count=Count('clubhouse_influencers', distinct=True) ).values( 'id', 'name', 'instagram_count', 'youtube_count', 'tiktok_count', 'twitch_count', 'clubhouse_count', ).distinct().order_by('created_at') I also want to return those influencers usernames, so I added foreign key lookups to .values() function: users_all_lists = request.user.lists.all().annotate( instagram_count=Count('influencers', distinct=True), youtube_count=Count('youtube_influencers', distinct=True), tiktok_count=Count('tiktok_influencers', distinct=True), twitch_count=Count('twitch_influencers', distinct=True), clubhouse_count=Count('clubhouse_influencers', distinct=True) ).values( 'id', 'name', 'instagram_count', 'youtube_count', 'tiktok_count', 'twitch_count', 'clubhouse_count', # ADDED THIS ONE LINE BELOW 'influencers__username', 'tiktok_influencers__username', 'youtube_influencers__channel_title', 'twitch_influencers__username', 'clubhouse_influencers__username' ).distinct().order_by('created_at') When a User has one InfluencerList with 2 influencers in it, this query returns 2 items which is not what I expected. Here is my InfluencerList model if it's necessary: class InfluencerList(models.Model): name = models.CharField('Name:', unique=True, max_length=40, blank=False, null=False) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') influencers = models.ManyToManyField('Influencer', related_name='lists', blank=True) tiktok_influencers = models.ManyToManyField('TiktokInfluencer', related_name='lists', blank=True) youtube_influencers = models.ManyToManyField('YoutubeInfluencer', related_name='lists', blank=True) twitch_influencers = models.ManyToManyField('TwitchInfluencer', related_name='lists', blank=True) clubhouse_influencers = models.ManyToManyField('ClubhouseInfluencer', related_name='lists', blank=True) I have spent much time in Django … -
Serializing specific fields from another model
I was trying to serialize policy_length, coverage_amount from Policy model and use it in a serializer that was using Insuree model. I'm using Policy and Insuree models: Policy model class Policy(TimeStampedModel): policy_length = models.FloatField(max_length=2, blank=True, null=True) coverage_amount = models.FloatField(max_length=256, blank=True, null=True) Insuree model class Insuree(TimeStampedModel): user = models.OneToOneField( 'User', related_name='insuree', null=False, on_delete=models.CASCADE, primary_key=True) coverage_amount = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=256, blank=True, null=True) policy_length = models.ForeignKey(Policy, on_delete=models.CASCADE, max_length=2, blank=True, null=True) class PolicySelectionSerializer(serializers.ModelSerializer): class Meta: model = Insuree fields = ('age', 'gender', 'disposable_income') #Current fields fields = ('age','gender',disposable_income', 'policy_length', 'coverage_amount') #The field I need and want to do -
How to get a sing tweet info?
I am trying to get the information of a tweet through a Django(Django-rest) app. I mean the number of likes, number of mentions, number of retweets, and impressions. I need something like a "Get" request, and the response to this request includes the information that I need. I really appreciate any help you can provide. -
Django DRF nested serializer
I'm new to DRF and trying to write a prototype of API for storing rectangle labels on a photo. my models: class Image(models.Model): file = models.FileField(blank=False, null=False) class Label(models.Model): image = models.ForeignKey(Image, blank=True, on_delete=models.CASCADE) start_x = models.IntegerField(default=0) start_y = models.IntegerFIeld(default=0) end_x = models.IntegerField(default=0) end_y = models.IntegerField(default=0) my serializers: from rest_framework import serializers class LabelSerializer(serializers.ModelSerializer): class Meta: model = Label fields = ['id', 'image', 'start_x', 'start_y', 'end_x', 'end_y'] class ImageSerializer(serializers.ModelSerializer): labels = LabelSerializer(many=True, read_only = True) class Meta: model = Image fields = ['id', 'file', 'labels'] When creating new image object in the following view I get image object, but no Labels objects created : from .serializers import ImageSerializer class ImageView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): serializer = ImageSerializer(data=request.data) if serializer.is_valid(): serializer.save() response_data = {'id': serializer.data['id']} return Response(response_data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) API call: curl -i -X POST -H "Accept: application/json" -H "Content-Type: multipart/form-data" -F "file=@~/test.jpg" --form-string 'labels={[{"start_x": 0, "start_y": 0, "end_x": 100, "end_y": 200}]}' http://127.0.0.1:8000/api/create/ How should I modify ImageSerializer for making possible to create image with labels with one API call? -
Django Rest Framework APITestCase does not use JSON datatypes for all fields
Using DRF's APITestCase, I expect the results of an API test to be serialized to JSON datatypes. An object with a property size = decimal.Decimal('20.0') is correctly sent through the API endpoint as size: 20.0 (with the COERCE_DECIMAL_TO_STRING parameter set to True). However, when testing the endpoint with the APITestCase, the original data type is kept. APIClient.get(url).response.data.get("size").__class__ = decimal.Decimal The same happens with other complex types. Why is this? And can it be changed to seeing what the API client would receive? -
Import django models to custom python script
I am trying to create a custom python script within my Django application. This script requires the use of my app models. I am unable to figure out how to import the models appropriately to be used within this script. My project directory: -my_proj(name:ais) -my_app(name:pages) -__init__.py -models.py -urls.py ... -utils -__init__.py -custom_script.py So if I wanted to access the pages.models from the custom_script.py how might I do this? I have attempted various imports such as from django.core.management import settings and from django.core.wsgi import get_wsgi_application but I still get an error stating the following: ModuleNotFoundError: No module named 'pages' -
MySQL Similar Query in Django ORM
I have following query which is written in SQL I want to know how can I write same in Django ORM SELECT target_id, parameter_id, rating, value_date, id from gsrm_paramvalue a1 inner join ( SELECT `target_id` as target, `parameter_id` as parameter, MAX(`value_date`) as maxdate from gsrm_paramvalue WHERE `parameter_id` in (900, 919, 957, 981, 1002, 1029, 1049, 1092) AND `target_id` in (20, 21, 22, 23, 25, 29, 30, 31, 55, 60, 99, 107, 109, 110, 111, 113, 115, 117, 119, 124, 127, 128, 135, 136, 162, 219, 220, 221) AND `status` = 'A' AND `value_date` <= '2019-03-31' GROUP BY `target_id`, `parameter_id` order by parameter_id, target_id ) a2 on a1.target_id = a2.target AND a1.parameter_id = a2.parameter AND a1.value_date = a2.maxdate WHERE `parameter_id` in (900, 919, 957, 981, 1002, 1029, 1049, 1092) AND `target_id` in (20, 21, 22, 23, 25, 29, 30, 31, 55, 60, 99, 107, 109, 110, 111, 113, 115, 117, 119, 124, 127, 128, 135, 136, 162, 219, 220, 221) AND `status` = 'A' AND `value_date` <= '2019-03-31' GROUP BY `target_id`, `parameter_id` order by parameter_id, target_id -
Distinct on mysql with all items returned
I used PostgreSQL with Django in a query like this: Price.objects.filter(**converted_filters) .order_by( "tyre__ean", "updated_at" ) .distinct("tyre__ean") But i need to switch to MySQL and change this query. I know you can get 1 value returned by using this query: Price.objects.values( "tyre__ean", ) .distinct() .filter(**converted_filters) This works quite much the same. But i don't want just that value i need all of them and i prefer to make 1 query instead of 2. Is that possible and how can i do that? -
Django update template div with success data from Ajax
I have select option and selecting option I run ajax to fetch filtered data from my model. The following are my view: my template with script and console log also I updated below: I need help how to update my list in the template with new list fetched by success(books) ajax. ( $('#stock_list').html([books]) is not updating the list ) View.py def get_stock_list(request): if request.method == "GET": book_type = request.GET.get('book_type') books = list(TextBook.objects.filter(type=book_type).values()) return JsonResponse({"books": books}) stock_report.html: {% extends 'wstore_base_generic.html' %} {% block content %} <div class="row"> <div class="col-lg-12 mt-4"> <div class="card shadow" id="stock_report"> <div class="card-header text-center"> <h3 class="display-5"> Stock Report </h3> <div class="text-right"> <h5> <select id="book_type" name="book_type" > <option value="" selected="selected">---SELECT---</option> {% regroup books by type as type_list %} {% for type in type_list %} <option value="{{ type.grouper }}">{{ type.grouper }}</option> {% endfor %} </select> </h5> </div> </div> <div class="card-body" id="stock_list"> <table id="customers" > <thead> <tr> <th>Item Code</th> <th>Item Description</th> <th>Open Qty</th> <th>Received qty</th> <th>Return Qty</th> <th>Issue Qty</th> <th>Adj Qty</th> <th>Balance Qty</th> </tr> </thead> <tbody> {% if books %} {% for book in books %} <tr> <td> <a href="{% url 'select_stock_report' book.id %}">{{ book.code }}</a></td> <td>{{book.name}}</td> <td>{{book.open_qty}}</td> <td>{{book.recived_qty}}</td> <td>{{book.return_qty}}</td> <td>{{book.issue_qty}}</td> <td>{{book.adj_qty}}</td> <td>{{book.bal_qty}}</td> </tr> {% endfor %} {% else %} <tr … -
Django ArrayField - Error binding parameter 0 - probably unsupported type
I want to store an array in my database. For that I use ArrayType of this type in my model: [[[0.12, 48.58]]]. I would like to use a serializer to create my GET, POST and PUT requests. Here is my model: models.py class Area(models.Model): osm = ArrayField( ArrayField( ArrayField( models.FloatField(), size=2, ), ), ) Here is my serializer : serializer.py class AreaSerializer(serializers.ModelSerializer): class Meta: model = Area fields = ['osm', ] And here is my view : views.py class ShopAreaList(ShopCustomListView): """Get or create areas for a shop""" queryset = Shop.objects.all() lookup_field = 'path' def get(self, request, path): """Depends on mustBeLogged to get areas of a shop""" shop = self.get_object() areas = Area.objects.filter(shop=shop) serializer = AreaSerializer(areas, many=True) return Response(serializer.data) def post(self, request, path): """For admin or shop owner to create areas""" shop = self.get_object() serializer = AreaSerializer(data=request.data) if serializer.is_valid(): serializer.save(shop=shop) return Response(serializer.data) return Response(serializer.errors) Here is the data I get: { "osm": [[[0.12, 48.58]]] } When I try to run my POST method I get this error: Error binding parameter 0 - probably unsupported type. I don't know what can I do to fix this error. Thank you in advance for your help -
How to save uploaded files to C: in Django?
I have a PDF model in my Django project. I want to save these files to my C: directory instead of my project directory. ( Save to C:\otc ) I don't have to file it as in the model (customer_customer_name), I just want to save it in a file named otc in C: And How can I add a timestamp to the uploaded PDF file's name? models.py def customer_directory_path(self, filename): return 'customer_{0}/{1}'.format(self.owner.customer_name, filename) class Pdf(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path) type = models.CharField(max_length=200, default='Select', choices=CHOICES) year = models.CharField(max_length=200, default='Select') created_date = models.DateTimeField(default=datetime.now()) -
how to force users to edit just their own record of model in django admin panel
i want to force users to edit just their own record of model in Django admin panel with permissions for example they can just see their comments and edit them only or their posts as well,i want to use Django admin panel only and i don't want to create A separate panel what should i do? -
my code is adding every object related to that user into a model with many to many relationship
So I'm trying to add specfic items/objects which the user asked for but instead it is adding every item related to that user, for example order 1 is Item 1 and Item 2 then if second order is placed then it will add item 3, item4, item1 and item 2 while item 1 and item 2 were not requested by the user. My code is like this: specificItems = [] for item in data: product = Product.objects.get(pk=itemId) user = UserLogin.objects.get(token=userToken).user specificItems.append(OrderItem.objects.create(user=user, product=product)) userObject = UserLogin.objects.get(token=finalUserToken).user FinalOrder = Order.objects.create(user=userObject, order_id=another_token) FinalOrder.products.add(*specificItems) FinalOrder.save() Also I have a many to many relationship with Order to OrderItems -
Django redirect from login to a view doesn't execute the function
I am trying to get that when a user logs in correctly, the execution continues in another view. I've tried with redirect, calling the function (as in the example)... and it returns a 302, but if I put a breakpoint on the view, it never stops. Why? This is my structure: App/ views.py urls.py login/ views.py app2/ views.py login/views.py @csrf_exempt @api_view(["POST"]) def auth(request): try: data = request.body.decode('utf-8') received_json_data = json.loads(data) username = received_json_data['username'] password = received_json_data['password'] user = authenticate(username=username, password=password) if user is not None: token, _ = Token.objects.get_or_create(user=user) is_expired, token = token_expire_handler(token) login(request._request, user) return home(request) else: logger.error('User does not exist: ' + username) return None except User.DoesNotExist: raise except views.py @login_required def home(request): if user == 1: return one() elif user == 2: return two() urls.py urlpatterns = [ path('home/', views.home, name='home'), path('login/', login.auth, name='login'), path('one', app2.one, name='one') path('two', app2.two, name='two'), ] There is something that I am doing wrong or I am not understanding. Thanks for your help -
Connect to OneDrive in python
I'm using onedrivesdk_fork to connect with the onedrive. I've created the application in azure, click on the link to view the application detail my_application I'm using the following code from the github: https://github.com/OneDrive/onedrive-sdk-python#download-an-item import onedrivesdk_fork as onedrivesdk from onedrivesdk_fork.helpers import GetAuthCodeServer redirect_uri = 'http://localhost:8080/' client_secret = 'your_app_secret' scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite'] client = onedrivesdk.get_default_client(client_id='your_client_id', scopes=scopes) auth_url = client.auth_provider.get_auth_url(redirect_uri) code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri) client.auth_provider.authenticate(code, redirect_uri, client_secret) When I run the above code to get the code from the url, the url open up the login page and ask for login below is the auth url: https://login.live.com/oauth20_authorize.srf?client_id=client_id&response_type=code&redirect_uri=redirect_uri&scope=wl.signin+wl.offline_access+onedrive.readwrite the page I get from the url Please help me to get the code from the url and after that how can i download the file from onedrive. -
How can I save data in Redis then aggregate them in SQLite?
I'm building a blog using Django and I want to track user activity. I'm trying to store specific data in Redis and then, after an hour, aggregate them in my SQLite. I built a model called SingleAction that collects infos about the user and the related activity and another model (AggregateAction) that is meant to count and aggregate similar activities. Then I was thinking to create a function like the following that saves single actions and, just before the expiration, gathers them in an AggregateAction instance and save it in SQLite. def create_action(user, verb, target=None): r = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB) dt = datetime.now() action = SingleAction(user=user, verb=verb, target=target) r.lpush('last_actions', f'{dt.strftime("%m/%d/%Y, %H:%M:%S")} - {action.user} {action.verb}') r.expire('last_actions', 3600) if r.ttl('last_actions') < 10: agg_actions = AggregateAction(user=user, n_actions=r.llen('last_actions')) agg_actions.save() I cannot make it work, is there any better solution? -
Which method is better for tagging in Django? ManyToMany or ArrayField?
I'm building a new project in Django. This project contains Users and Paintings. One User owns many Paintings. And I want the Users to be able to tag their Painting, and later be able to sort them using the tags. A User needs to be able to search by n tags at the same time. Also, the API will return tags compatible with their query. Say, for example, I have the following schema: { "User#1": { ... "paintings": { "Mona Lisa": { "tags": ["Da Vinci", "Gioconda", "Portrait", "Color"] }, "Ginevra de' Benci": { "tags": ["Da Vinci", "Portrait", "Color"] }, "The Last Supper": { "tags": ["Da Vinci", "Landscape", "Color"] }, } } } Is the User wants to get all the Paintings with the tag "Portrait", the API will first return compatible tags ("Da Vinci", "Color", "Gioconda"), and then it'll return the Paintings with "Portrait" ("Mona Lista", "Ginevra de' Benci"). I want to offer the user an intuitive way to compose a long query of tags. My question is: What's better? Using a "Tag" model and relate it to the Painting model with a ManyToMany? Or adding a "tags" ArrayField to the Painting model? I'm asking about security, performance, and resource … -
How to correctly annotate a QuerySet with the number of elements in a Many2Many relation?
I'm modelling amateur soccer Games where two teams of players play against each other. I'm trying to annotate the QuerySet with the number of players in each team to then identify games with different number of players in each team. The models I have are pretty straight forward: class Player(models.Model): nickname = models.CharField(...) class Team(models.Model): players = models.ManyToManyField(Player) class Game(modeos.Model): team1 = models.ForeignKey(Team) team2 = models.ForeignKey(Team) When I go to the shell (python manage shell) and execute the following command to get the number of players of the teams in each match I got the expected results: [(game.team1.players.count(), game.team2.players.count()) for game in Game.objects.all()] [(7, 7), (7, 10), (7, 7), (7, 7), (7, 7)] However, when I try to do the same with annotations: Game.objects.annotate(t1c=Count('team1__players'), t2c=Count('team2__players')).values('t1c','t2c') I got incorrect results: <QuerySet [{'t1c': 49, 't2c': 49}, {'t1c': 70, 't2c': 70}, {'t1c': 49, 't2c': 49}, {'t1c': 49, 't2c': 49}, {'t1c': 49, 't2c': 49}]> Which are the multiplication of both values. What am I doing wrong? -
Whether to place the Django project files inside a venv or not
I'm fairly new to Django and I was reading about the best practice of using virtual environments for Django projects. I have created a virtual environment called 'venv' and now I'm wondering whether I should place my new Django project under the 'venv' folder or in a separate folder. For example, which of the following would be better? Option A (the project folder being inside the venv folder): venv/ my_new_django_project/ Option B (the venv and the project folders being in the same folder): venv/ my_new_django_project/ -
Django React - cannot load static files from static folder
I am trying to deploy Django-React app, but If I try to connect on the 127.0.0.1:8000 it loads only title tag and then the page is blank. In console I can see it cannot load GET http://127.0.0.1:8000/static/css/main.4f7faf6a.chunk.css net::ERR_ABORTED 404 (Not Found) and all the other files and I have no idea why. Folder structure: backend: app frontend Relevant code from settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build') ] in TEMPLATES I have: 'DIRS': [ os.path.join(BASE_DIR, 'build') ], urls.py: urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) First I build the npm run build and copy the build into backend folder. Then I run python manage.py collectstatic and runserver. It loads only title tag and blank page.. Any idea what is wrong? -
Output_field exists in local version but not on website, version of python and django is the same
I have a Django website locally and as a hosted version (local version for tests and development). It uses the same version for everything (Python 3.9, Django 3.1.3). I never had any problems with features working in one of the instances and not the other. I am trying to multiply two attributes for every object and then add it together. (it calculates the total weight so: weight*quantity+weight*quantity+.... The problem appeared when I tried using ExpressionWrapper. Everything works great locally but not on hosted version. Here's the line that causes error and the error itself. waga = Produkt.objects.filter(zamowienie=138).aggregate(sum=ExpressionWrapper(Sum(F('waga') * F('ilosc')), output_field=DecimalField()))['sum'] Error: Exception Type: FieldError Exception Value: Expression contains mixed types: DecimalField, IntegerField. You must set output_field. Exception Location: /usr/home/stolarz/.virtualenvs/venv/lib/python3.9/site-packages/django/db/models/expressions.py, line 303, in _resolve_output_field As you can see the error states I did not use output_field but i clearly did. I'm a bit confused. What could possibly cause this situation? -
Django Tests - User Factory with create_batch
Ok I've faced interesting problem with my tests files. I'm using this simple code to check User's created by UserFactory UserFactory.create_batch(4) for u in User.objects.all(): print(u.email) UserFactory - this works fine Creates 4 users in create_batch(4) process from django.contrib.auth import get_user_model from factory import Faker from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): email = Faker("email") password = Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ) class Meta: model = get_user_model() django_get_or_create = ["email"] UserFactory - this one doesn't work Creates only 1 user in create_batch(4) process from django.contrib.auth import get_user_model from faker import Faker from factory.django import DjangoModelFactory fake = Faker() class UserFactory(DjangoModelFactory): email = fake.email() password = fake.password() class Meta: model = get_user_model() django_get_or_create = ["email"] The only difference is the way I generate user's email. factory.Faker("email) works fine but faker.email() doesn't. Maybe someone had the same issue? factory_boy docs: https://factoryboy.readthedocs.io/en/stable/index.html faker package docs: https://faker.readthedocs.io/en/master/index.html