Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework benchmarking [closed]
I want to know, how many requests can Django REST framework handle per second? And how much RAM does it use per session? -
How to change "transport" url in django celery config
I have django 3.2.7, celery 5.2.1, redis 3.5.3 I have next celery settings. (REDIS_PASSWORD) is env variable: CELERY_BROKER_URL = f'redis://:{REDIS_PASSWORD}@redis:6379/4' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = f'redis://:{REDIS_PASSWORD}@redis:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] But when I start my docker-compose app, it shows me celery | --- ***** ----- celery | -- ******* ---- Linux-5.11.0-34-generic-x86_64-with-glibc2.31 2021-09-16 10:20:11 celery | - *** --- * --- celery | - ** ---------- [config] celery | - ** ---------- .> app: project:0x7f5cd0df0880 celery | - ** ---------- .> transport: redis://redis:6379/0 <==== NO CHANGES HERE celery | - ** ---------- .> results: redis://:**@redis:6379/1 celery | - *** --- * --- .> concurrency: 16 (prefork) celery | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) celery | --- ***** ----- How can I set it? -
How to get user in Django forms?
Hello I have 2 different models: models.py class User(AbstractUser): class Roles(models.IntegerChoices): OWNER = 1, 'OWNER' BUYER = 2, 'BUYER' role = models.PositiveSmallIntegerField('ROLE', choices=Roles.choices, null=True, blank=True, default=None) other model class Book(core.BaseModel): book_number = models.PositiveIntegerField('Book number', validators=[ MinValueValidator(1), MaxValueValidator(MAX_TAG_NUMBER), ]) In model Book I have Book Form: forms.py class BookForm(AllBookForm): def __init__(self, user=None, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user def clean(self): cleaned_data = super().clean() book_number = cleaned_data['book_number'] user = cleaned_data['user'] if self.user == User.Roles.OWNER: if book_number != None: raise forms.ValidationError(some error......) elif self.user == User.Roles.BUYER: if number == None: raise forms.ValidationError(some error.....) return cleaned_data I want to initialize User role in this form. How to initialize user Role in other model? Form. -
docker-compose with NGINX not serving Django at localhost
I'm trying to serve a simple Django app over NGINX using Docker Compose. I'm not really sure where the problem is coming from but the build was successful. Any idea why is not serving correctly? This is the setup: ├── app │ ├── templates │ ├── webapp │ │ ├── asgi.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── Dockerfile │ ├── Dockerfile.prod │ ├── entrypoint.sh │ ├── entrypoint.prod.sh │ └── requirements.txt ├── nginx │ ├── Dockerfile │ └── nginx.conf ├── .env ├── docker-compose.ci.yml ├── docker-compose.prod.yml └── docker-compose.yml app/webapp/settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'webapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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', ], }, }, ] WSGI_APPLICATION = 'webapp.wsgi.application' DATABASES = { 'default': { 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), 'NAME': os.environ.get('SQL_DATABASE', os.path.join(BASE_DIR, 'db.sqlite3')), 'USER': os.environ.get('SQL_USER', 'user'), 'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'), 'HOST': os.environ.get('SQL_HOST', 'localhost'), 'PORT': os.environ.get('SQL_PORT', '5432'), } … -
how to get the unique result using django queryset?
I have something like this data in my DB. I want to get the result like class DateRange(models.Model): id = models.... date = models.... 1 is present from 01-01-2021 - 09-01-2021 2 is present from 01-02-2021 - 07-01-2021 1 is present from 01-03-2021 - 02-03-2021 How to achieve this using the django queryset. 01-01-2021 1 02-01-2021 1 03-01-2021 1 04-01-2021 1 05-01-2021 1 06-01-2021 1 07-01-2021 1 08-01-2021 1 09-01-2021 1 01-02-2021 2 02-02-2021 2 03-02-2021 2 04-02-2021 2 05-02-2021 2 06-02-2021 2 07-01-2021 2 01-03-2021 1 02-03-2021 1 -
Django No Reverse Match, Context is breaking my code
I've narrowed it down to when i add context to my return render(request) line is when my code breaks, but i can't figure out why. I'm not sure what errors to give or what parts of my code you need, but here you go. NoReverseMatch at /gallery/gallery Reverse for 'photo' with arguments '(2,)' not found. 1 pattern(s) tried: ['gallery/photo'] Request Method: GET Request URL: http://127.0.0.1:8000/gallery/gallery Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'photo' with arguments '(2,)' not found. 1 pattern(s) tried: ['gallery/photo'] Exception Location: C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\mustache', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\ScrillaGorilla\AppData\Local\Programs\Python\Python38', 'C:\Users\ScrillaGorilla\PycharmProjects\Mustache Website\venv', 'C:\Users\ScrillaGorilla\PycharmProjects\Mustache ' 'Website\venv\lib\site-packages'] Server time: Thu, 16 Sep 2021 06:49:31 +0000 and this is my code. if that helps. this is my views.py file. from django.shortcuts import render from .models import Category, Photo from django.db import models # Create your views here. def photogallery(request): categories = Category.objects.all() photos = Photo.objects.all() context = {'categories': categories, 'photos': photos} return render(request, 'picturegallery/pictures.html', context) def viewPhoto(request, pk): photo = Photo.objects.get(id=pk) return render(request,'picturegallery/photo.html', {'photo': photo}) def addPhoto(request): return render(request,'picturegallery/ADD.html') and this is my models.py file. from django.db import models # Create your models here. class … -
Django-filter foreign key could not get in drop down
filter.py class StudentFilter(django_filters.FilterSet): # SchoolName = django_filters.ModelMultipleChoiceFilter(queryset=MasterSchool.objects.all()) class Meta: model = Student fields = ['StudentId', 'School', 'Division'] Here I have tried School__SchoolName, but it does not show the dropdown list. model.py class MasterSchool(models.Model): SchoolName=models.CharField(max_length=100, null=False, blank=False, unique=True) Active = models.BooleanField(default=True) class Meta: db_table='master_schools' class MasterDivision(models.Model): DivisionName=models.CharField(max_length=100, null=False, blank=False, unique=True) Active = models.BooleanField(default=True) class Meta: db_table='master_divisions' class Student(models.Model): StudentId=models.CharField(max_length=20, null=True, blank=True) StudentName=models.CharField(max_length=100, null=False, blank=False) Phone = models.CharField(verbose_name="Phone number", null=True, blank=True, max_length=10, validators=[validate_digit_length], default='1234567890') School = models.ForeignKey(MasterSchool, on_delete=models.CASCADE, null=True, blank=True, db_column='SchoolId') Division = models.ForeignKey(MasterDivision, on_delete=models.CASCADE, null=True, blank=True, db_column='DivisionId') StudentPhoto= models.ImageField( null=True, blank=True, default="default.png", upload_to='studentphoto/resgistred_photos/') PhotoMatrix=models.CharField(max_length=100, null=True, blank=True) class Meta: db_table='students' ordering = ['id'] view.py def StudentDetail(request): if(request.session.has_key('uid')): stud = Student.objects.all() schools = MasterSchool.objects.all() divisions = MasterDivision.objects.all() tableFilter = StudentFilter(request.GET, queryset=stud) students = tableFilter.qs page = request.GET.get('page', 1) paginator = Paginator(students, settings.PAGE_LIMIT) try: student_list = paginator.page(page) except PageNotAnInteger: student_list = paginator.page(1) except EmptyPage: student_list = paginator.page(paginator.num_pages) context = { 'student_list':student_list , 'students': students, 'tableFilter':tableFilter, 'root_url':settings.ROOT_URL, 'schools': schools, 'divisions': divisions } return render(request, 'web_api/student_details.html', context) html <form method="get" class="forms-sample" autocomplete="off" > {{tableFilter.form}} <button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button> </form> <div class="table-sorter-wrapper col-lg-12 table-responsive"> <table id="sortable-table-2" class="table table-striped"> <thead> <tr> <th>ID</th> <th>Student Name</th> <th>School Name</th> <th>Division</th> <th>Image</th> <th>Option</th> </tr> </thead> <tbody> {% for … -
i dont know why it has error with catalog/url.py?
https://github.com/Angelheartha/ruci this is my github the erroe is the below raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'catalog.urls' from 'C:\Users\user\PycharmProjects\pythonProject28\locallibrary\cat alog\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. i dont know the reazon because i already wrote in catalog/url.py path, and i wrote views.py what is the issue? -
Registration of an anonymous DRF user
I'm writing an API questionnaire on the Django Rest Framework, when passing the survey, I collect the id of an authorized user. But what about an anonymous user who has passed the survey, how do I get his unique id? -
expected str, bytes or os.PathLike object, not InMemoryUploadedFile?
I upload the excel file and insert the file in VBA_Parser of oletools but I am getting an error expected str, bytes or os.PathLike object, not InMemoryUploadedFile def upload(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] result = [] vba_parser = VBA_Parser(file) # this is where error occur vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros(): result.append("Caution, macros has been found in your excel file.") vba_parser = VBA_Parser(file) # this is where error occur. I couldn't figure out how to solve the issue. -
How To get text editor in django frontend
In my front end of django templates i want to use a text field editor like How to achive something like this -
(Django) How to keep input values after form submit
I have the following view (truncated): def scheduler( request, year=None, month=None, event_id=None, delete_id=None, ): # Handle the event form if request.POST: event_form = EventForm(request.POST, instance=event) if event_form.is_valid(): event = event_form.save() dfkl_number = event_form.cleaned_data['dfkl_id'] Event.objects.filter( id=event.id, ).update(dfkl_number=dfkl_number) start_time = event_form.cleaned_data['start_time'] start_time = user_tz.localize(start_time.replace(tzinfo=None)) end_time = event_form.cleaned_data['end_time'] end_time = user_tz.localize(end_time.replace(tzinfo=None)) # if the end time is before the start time, try setting it to the same day if end_time < start_time: end_time = end_time.replace( year=start_time.year, month=start_time.month, day=start_time.day) # if the hour is also before, just use the start time if end_time < start_time: end_time = start_time Event.objects.filter( id=event.id, ).update(start_time=start_time) Event.objects.filter( id=event.id, ).update(end_time=end_time) return HttpResponseRedirect('/events') What I want is that whenever I submit a form (if request.POST) whether the form is valid or not, the values of the inputs do not disappear. scheduler.html: {% if event_id %} <form action="{% url 'cal:event' event_id %}" method="post" class="form needs-validation to-do-form"> {% else %} <form action="{% url 'cal:events' %}" method="post" class="form needs-validation to-do-form"> {% endif %} {% csrf_token %} {% bootstrap_form_errors event_form type='non_fields' %} {% bootstrap_field event_form.title layout='horizontal' size='small' %} {% bootstrap_field event_form.description layout='horizontal' size='small' %} {% bootstrap_field event_form.event_type layout='horizontal' size='small' %} {% bootstrap_field event_form.dfkl_id layout='horizontal' size='small'%} <!-- start time --> <div class="form-group {% if event_form.start_time.errors %}is-invalid{% … -
Django ModelForm update function returning error
I currently have a settings model for my Django app which saves a set of settings for the rest of the program to read from. I have tried to create a way to update these settings on the app, as per the below code. When the update button is clicked, however, the app returns the 'error':'Bad info' variable instead of updating the database. Does anyone know what could be causing it because I cannot seem to find any errors in the code? Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: try: form = SettingUpdateForm(request.POST, instance=setting) form.save() return redirect('settingsHome') except ValueError: return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form, 'error':'Bad info'}) Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) #Income Statement Year To Date Income_Statement_Year_to_date=models.BooleanField(default = False) isytd_Only_use_main_accounts=models.BooleanField(default = False) isytd_Sort_by_account_name=models.BooleanField(default = True) isytd_Print_null_values=models.BooleanField(default = False) … -
how to process the return value of status=status.HTTP_400_BAD_REQUEST
In Django view, I have a view like this: @api_view(['POST']) def change_log(request): ...... return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then call it: def post_to_change_log(): try: requests.post(INNO_API_URL + '/change_log_add/', json=log_data) except: In main, I need to check the return value of post_to_change_log(true of false) main(): if(post_to_change_log): return 200 else: return error+return value from post_to_change_log The question is, how could I process the return value in the 3 functions, then when error happened, I can return the serializer.errors, status=status.HTTP_400_BAD_REQUEST) in main? Thank you. -
Can't login to django admin page Server Error (500)
Good work everyone, I'm trying to build a website using django, nginx and gunicorn. Everything works fine on the django development server and I can also open the front page of my site using nginx. Since the project is the project of the company I work for, I had to censor some parts due to company policy. Thank you for your understanding However, repeatedly sudo systemctl restart gunicorn When I try to login to the admin page or use my own custom login page, I get a Server error (500) despite running the command. Can someone tell me what I'm doing wrong? settings.py: enter image description here nginx: enter image description here -
How to cache ClassBasedAPIViews in Django Rest Framework?
I am serving list of products in DRF and I tried to use cache in ClassBasedApiViews, urls.py path('',ProductListAPIView.as_view(), name='products') views.py: class ProductListAPIView(ListAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer_class = ProductSerializer serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' depth = 1 There is no function like def get() ... So I can not use conventional decorator before the function to cache. What I have tried is path('', cache_page(300)(ProductListAPIView.as_view()), name='products') this works. In case of multiple decorators path('', vary_on_headers('Authorization')(cache_page(300)(ProductListAPIView.as_view())), name='products') works as well. Is there a better way to use both decorators cache_page and vary_on_headers for ClassBasedAPIView? -
How can I bulk create Django Model objects using xml iterparse?
I want to insert thousands of rows into postgres db. I plan to do this using bulk_create() in django. Since I am working in a low memory ssh terminal, I want to use iterparse() in xml python library My XML file looks like this <playerslist> <player> <fideid>25121731</fideid> <name>A C J John</name> <country>IND</country> <sex>M</sex> <title></title> <w_title></w_title> <o_title></o_title> <foa_title></foa_title> <rating>1063</rating> <games>0</games> <k>40</k> <birthday>1987</birthday> <flag>i</flag> </player> <player> . . . </player> . . . </playerlist> Here are my models class Player(models.Model): fide_id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=50, null=False) sex = models.CharField(max_length=2, null=False) birthday = models.IntegerField(null=True) class Ratings(models.Model): fide_id = models.ForeignKey(Player, on_delete=models.CASCADE) month = models.CharField(null=False, max_length=15) federation = models.CharField(max_length=15, null=False) title = models.CharField(max_length=4, default=None, null=True) w_title = models.CharField(max_length=4, default=None, null=True) o_title = models.CharField(max_length=4, default=None, null=True) foa_title = models.CharField(max_length=4, default=None, null=True) rating = models.IntegerField(null=True) games = models.IntegerField(null=True) k = models.IntegerField(null=True) flag = models.CharField(max_length=3, null=True) I want to insert the respective fields into their tables. I could do this on a normal computer but i am not sure how to parse this incrementally. Thank you. Edit : I think iterparse approach would require more transactions than bulk_create. I don't think we can use bulk_create() here. -
How to upload file and redirect to another page in django?
I showed up upload.html page after I log in. When I submit the upload file button I want to show upload or some other pages. it doesn't redirect to upload.html or any other pages. It redirects to the login page again. May I know what's the bug in my code? Here is the View.py login is strictly required. As soon as the user login I showed up upload.html page. I have two groups: (New user) and administration. @login_required(login_url='/registration/login/') def login_request(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return render(request, "upload.html") form = AuthenticationForm() return render(request = request, template_name = "registration/login.html", context={"form":form}) @unauthenticated_user def login(request): """ Creates login view Returns: rendered login page """ return render(request, 'registration/login.html') @allowed_users(allowed_roles=["administrator", "New user"]) def upload(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] workbook = load_workbook(filename=file, data_only=True) xls = workbook[workbook.sheetnames[0]] result = [] # macros check vba_parser = VBA_Parser(file) vba_modules = vba_parser.extract_all_macros() if vba_parser.detect_vba_macros(): result.append("Caution, macros has been found in your excel file.") count = 0 # check .exe, url for i in range(1, xls.max_row+1): … -
how to get id of the input text field in Django Views?
Currently in my form i have this <input type="text" name="textAnswer" maxlength="50" id="ed57a954-7afd-47ac-b6d4-979198455aa5" class="textinput textInput form-control"> I want the id of this input in views when form is submitted. I know how to get the value typed by user in textinput in views but dont know how to extract id of that input as well Currently i'm extracting Value with this code userTypedValue = request.POST.get('textAnswer') -
Date format for Django Admin
I have a Model with DateField. In Django admin when I try to enter the date in Django Admin in format "%d-%m-%Y" it throws error as Enter a valid date.. Since the default pattern is "%Y-%m-%d" I tried the following but couldnt find a satisfied solution over the docs: Change the format type with strftime in model. Add DATE_INPUT_FORMATS in settings. Change language code to "en-IN" Is there any way to save the date in "%d-%m-%Y" format. -
Browser is making an HTTP call after reloading an angular webpage
Hello I’m working on an angular project and I’ve few APIs to call.. I’ve set up the API Url as const SERVER_URL = https://api.example.com And it’s working perfectly fine unless and until I reload the page after some successful API Calls and then make an API call again.. I’m getting CORS error that: [blocked] The page at https://staging.example.com was not allowed to display insecure content from http://api.example.com Do anyone know where I’m doing things wrong? Because I’ve few other projects and I use same coding practices in them as well but they are working perfectly fine.. PS: Backend is in Django -
how to return doc file as response in django views?
i have my .doc file created in a django views. Now i want to return that doc file as response. how can i do this? this is my view def post(self, request, *args, **kwargs): with tempfile.TemporaryDirectory() as tem_dir: doc.save(tem_dir + '/' + template_name) f = open(tem_dir + '/' + template_name, 'r') response = HttpResponse(f, content_type='application/msword') response['Content-Disposition'] = 'attachment; filename='+template_name return response I am saving my doc file in a temporary directory. Also can the response will be visible using postman request? -
vs code autocompletes not working properly in Django
vs code doesn't suggest request in views.py , I've test pylance,jedi.. all off language server but didn't work. How can I get a better autocompleting in vs code? -
Django submission button doesn't link with view function
I am trying to create a small subscription input form on top of my page that allows users to enter their email, click "submit" and then it will call the subscribe function on the back-end. I am putting the form code in one of my template html file: <div class="container"> <div class="wrapper d-flex align-items-stretch" style="margin-bottom: 100px;"> {% include 'Reddit_app/sub_list.html' %} <div id="content" class="mr-4"> <div class=" lt-area"> <div class="tr-inner"> <form action="{% url 'subscribe' station.slug %}" method="POST" class="subscribe-form"> <div class="form-group d-flex mb-1"> <div class="icon"><span class="icon-paper-plane"></span></div> <input type="email" name="email" class="form-control" placeholder="Subscribe us"> </div> <button type="button" class="btn btn-primary t-btn">Submit</button> </form> </div> </div> {% block content %} {% endblock %} </div> </div> </div> Here is my urls.py urlpatterns = [ ... path('<slug:slug>/subscribe/', views.subscribe, name='subscribe'), ] and here is my subscibe function, but right now when I click submit, this function is currently not even called def subscribe(request, slug): station=get_object_or_404(Station, slug=slug) post_data = request.POST.copy() email = post_data.get("email", None) try: validate_email(email) except ValidationError as e: print("bad email, details:", e) return redirect('post_list', slug=station.slug) -
Django: Could not load model - NOT NULL constraint failed
how are you all? We are not able to insert the fixures data into our SQLite3 database. We are using UUid as our model id. Using the comand python.exe .\manage.py loaddata start.json Model class Estadual(models.Model): # Fields id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) estado = models.CharField(max_length=50) sigla = models.CharField(max_length=2, unique=True) valor = models.PositiveSmallIntegerField() created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) # Relationships user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: pass start.json [ { "model": "app.estadual", "pk": "59472bb0-7f6e-4026-a900-727b7cdd647f", "fields": { "estado": "AC", "sigla": "AC", "valor": 12, "user": ["4a695e40-6b3a-49fa-8beb-eed853ce17b0"] } },{ "model": "app.estadual", "pk": "5b321ca7-e8be-4580-8d36-080c663d5397", "fields": { "estado": "AL", "sigla": "AL", "valor": 12, "user": ["4a695e40-6b3a-49fa-8beb-eed853ce17b0"] } } ] Error Problem installing fixture 'C:...fixtures\start.json': Could not load app.Estadual(pk=59472bb0-7f6e-4026-a900-727b7cdd647f): NOT NULL constraint failed: app_estadual.created