Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Private Object Field in Django Admin
I'm wondering what the best way to have an editable field (by admins) for some object in Django admin that can't be viewable on the public site. For example, a notes section for content authors with conventions or instructions that a front-end dev can't accidentally render in a template. Something like: class SomeModel(Model): internal_notes = CharField(max_length=1024, public=False) So some object, o, can't be rendered in a template: {{ o.internal_notes }} -
How to add more fields to an UpdateView using model: User?
I need to add more fields to my "edit profile" page because when someone registers they only have to fill in 2 fields (inputs) but when they go to "edit profile" they appear as 8 fields in the form. Does anyone have an idea how to add more fields such as: social media, country, address etc. to the "User" model (it's the one I'm using) it comes from here: from django.contrib.auth.models import User views.py class EditProfilePageView(generic.UpdateView): model = User template_name = 'Usuarios/edit-profile.html' fields = '__all__' success_url = reverse_lazy('profile') def get_object(self): return self.request.user -
Django How to properly upload image to form?
This is my code associated with the form: models class Date(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=64, null=True) class Photo(models.Model): date = models.ForeignKey('Date', on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') # form class DateForm(forms.ModelForm): image = forms.ImageField() class Meta: model = Date exclude = ('user',) # view class CreateDateView(LoginRequiredMixin, CreateView): template_name = 'app/date/form.html' form_class = DateForm def form_valid(self, form): form.instance.user = self.request.user form.save() # by the way why do I save this form? Is it okay to save it in form_valid method? photos = self.request.FILES.getlist('image') for photo in photos: Photo.objects.create(image=photo) return super().form_valid(form) The issue is how to save Photo objects if it requires a Date model id. It raises NOT NULL constraint failed: app_photo.date_id As I understand I have to write something like: Photo.objects.create(date=date_from_the_form, image=photo) But how to get the pk from the Date model? Hope you understand my problem, if any questions don't hesitate to write them down below in the comments section. Thanks in advance! Error -
django ajax project- basket - collecting values in array
in my django store i have basket wich in views.py have class : class BasketAddView(View): def post(self, request, *args, **kwargs): basket = Basket(request) product_id = str(request.POST.get('productid')) product_size = str(request.POST.get('productsize')) product_qty = str(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) #it was id and should be p basket_size_table = [] basket_size_table.append(product_size) basket.add(product=product, size=product_size, qty = product_qty) basketqty=basket.__len__() response = JsonResponse({'size': basket_size_table,'product' : product_id, 'qty': basketqty, }) return response web inspector in output in console show that i have only last size in array [] 1 but i would like to have a collections of sizes in one array. -
Trying To Retrieve Name Instead of Primary Key, But DRF complains of Value Error. If I try to fix it, I got other errors too
My Models: def upload_to(instance, filename): return 'images/{filename}'.format(filename=filename) class StreamPlatform(models.Model): name = models.CharField(max_length=200) about = models.TextField(max_length=2000) website = models.URLField(max_length=2500) def __str__(self): return self.name class WatchList(models.Model): title = models.CharField(max_length=250) image = models.ImageField(_('Image'), upload_to=upload_to, default='images/default.jpg') storyline = models.TextField(max_length=2000) platform = models.ForeignKey(StreamPlatform, on_delete=models.CASCADE, related_name='watchlist') active = models.BooleanField(default=True) avg_rating = models.FloatField(default=0) number_rating = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title My Serializers: class WatchListSerializer(serializers.ModelSerializer): platform = serializers.CharField(source='platform.name') class Meta: model = WatchList fields = '__all__' extra_kwargs = {'avg_rating': {'read_only': True}, 'number_rating': {'read_only': True}} def create(self, validated_data): return WatchList.objects.create(**validated_data) class StreamPlatformSerializer(serializers.ModelSerializer): watchlist = WatchListSerializer(many=True, read_only=True) class Meta: model = StreamPlatform fields = '__all__' My View: class WatchListAV(generics.ListCreateAPIView): permission_classes = [AdminOrReadOnly] parser_classes = [MultiPartParser, FormParser] queryset = WatchList.objects.all() serializer_class = WatchListSerializer pagination_class = WatchListLimitOffsetPagination filter_backends = [filters.SearchFilter, filters.OrderingFilter] search_fields = ['title', 'platform__name'] ordering_fields = ['avg_rating'] The issue I got is that Django Rest Framework complains in PostMan that: ValueError at /watch/list/ Cannot assign "{'name': '8'}": "WatchList.platform" must be a "StreamPlatform" instance. When I try to fix it like this in the WatchListSerializer: platform = serializers.PrimaryKeyRelatedField(queryset = StreamPlatform.objects.all(), source='platform.name',) I got a new error instead: ValueError at /watch/list/ Cannot assign "{'name': <StreamPlatform: Blah>}": "WatchList.platform" must be a "StreamPlatform" instance. When I commented out the error-prone code bits, … -
Get django username before editing it
Im using a django signal to post to an API based on the users username. If the user doesnt exist it creates a new one and posts to API . If im editing the user I cant acess the old username to change the API . I've also tried with pre_save but with no result . Lets say for example username is Nick if user does not exist it creates the API, if nick changes his username to NickyXX when i do username = instance.username i get the NickyXX therefore i cant acess the API .I know my approach is incorrect but I dont know how to get the original username. @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): username = instance.username if created: Profile.objects.create(user=instance) ### API SCRIPT ### .............. ################### CREATE A NEW USER ################### url = 'http://...' myobj = { "organization": { "canHaveGateways": True, "displayName": instance.username, "name": instance.username } } x = requests.post(url,json = myobj) x = x.json() print(x) orgID = x["id"] print(orgID) else: instance.profile.save() ################### FIND USERNAME ################### url = '...&search=' + username x = requests.get(url) x = x.json() print(x) ################### EDIT ################### myobj = { "organization": { "displayName": username, "name": username } } x = requests.put(url, json … -
Django rest framework wont display data when doing a filter
I haven't used Django RF in a while and I ran into a problem. I was trying to do an object.get() and I got an error that said It returned more than 1 (returned 2) so I changed the .get to .filter and It fixed my error issue but it won't show any data when going to the endpoint, even though when printing in the console it shows that I've received a queryset (but its an array, [, ]). Heres my ViewSet: class TeamViewSet(ModelViewSet): queryset = Team.objects.all() serializer_class = TeamSerializer permission_classes = [IsAdminUser] @action(detail=False, methods=['GET','PUT'], permission_classes=[IsAuthenticated]) def me(self, request): # return Response(request.user.id) try: team = Team.objects.filter(leader__user_id=request.user.id) print(team) except Team.DoesNotExist: team = None if request.method == 'GET': serializer = TeamSerializer(team) return Response(serializer.data) elif request.method == 'PUT': serializer = TeamSerializer(team, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) It's problem an easy fix, I've just haven't used Django RF in a while, Thanks for any help :) -
Input type doesn't shown when use models form - DJANGO
so i was copy modelsform code from website https://ordinarycoders.com/blog/article/django-file-image-uploads but when i run my code, there's no input type="file" on my developer tools. but when i tried print class at models.py and forms.py, it's work. I don't know why no input type="file". this is what must be shown this is what shown by my web but when i tried to give print to my function upload at views.py, suddenly it doesn't want work and error print here's my views.py code : from django.shortcuts import render, redirect from django.views.decorators.csrf import ensure_csrf_cookie from .forms import AudioForm from .models import Audio_store from MusicLockApp.forms import AudioForm @ensure_csrf_cookie def homepage(request): # return HttpResponse('homepage') return render(request, 'homepage.html') def decode(request): # return HttpResponse('about') return render(request, 'decode.html') def upload(request): if request.method == 'POST': form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('main:upload') form = AudioForm() audio = Audio_store.objects.all() return render(request=request, template_name='homepage.html', context={'form':form, 'audio':audio}) urls.py : from django.contrib import admin from django.conf.urls import url from . import views from django.urls import path, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path("upload", views.homepage, name="upload") ] if settings.DEBUG: #add this urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <div class="col-md-6"> {% block content %} {% … -
Python - Object of type 'ManyRelatedManager' is not JSON serializable
I'm trying to modify the open source project AWX Ansible and I'm getting this error and I'm not sure what it means? I'm not defining any new functions or serializing anything. I'm only modifying some functions to accept extra parameters. I modified a couple of files so I'm not sure which file is causing the error. I just want to understand what this error means? 2022-05-12 16:29:13,115 ERROR django.request Internal Server Error: /api/v2/workflow_job_templates/13/launch/ Traceback (most recent call last): File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/rest_framework/response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/rest_framework/renderers.py", line 724, in render context = self.get_context(data, accepted_media_type, renderer_context) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx/api/renderers.py", line 61, in get_context return super(BrowsableAPIRenderer, self).get_context(data, accepted_media_type, renderer_context) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/rest_framework/renderers.py", line 655, in get_context raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx/api/renderers.py", line 75, in get_raw_data_form return super(BrowsableAPIRenderer, self).get_raw_data_form(data, view, method, request) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/rest_framework/renderers.py", line 567, in get_raw_data_form content = renderer.render(data, accepted, context) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/rest_framework/renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/rest_framework/utils/json.py", line 25, in dumps return json.dumps(*args, … -
How to launch function every time part of page reloads
i am making app in Django and i would like to launch function every time that i reload calendar. When user clicks arrows on the side of calendar it reloads division with calendar and shows new month. When user clicks on one of the days new content should show up (this is done by assigning content to each day using setAttribute("onclick", ...) function). Content showing works until i change month. From what i understand it is because i assign function to only existing DOM elements and not the new ones. I tried assigning it to new elements in various ways but it never worked. Is there some way to do it? Month changing is done by ajax load function. for (var x=0; x < days.length; x++) { days[x].setAttribute("onclick", `setDay( "${String(days[x].innerHTML)}", "${(month[1].innerHTML)}" ) `)} $('#right').click(function () { let mth = $('.month')[1].innerHTML.split(" ") let month = parseInt(monthsObj[mth[0]])+1 let year = parseInt(mth[1]) if (month == 13) { month = 1 year += 1 $('#newCal').html('').load( "{% url 'calendarChange' monthNumber=4 yearNumber=2022 %}".replace("4", month).replace("2022", year) ); } else { $('#newCal').html('').load( "{% url 'calendarChange' monthNumber=4 yearNumber=2022 %}".replace("4", month).replace("2022", year) ); } }) I tried putting that for cycle in function and putting it into ajax click. Ajax … -
Django How to Upload an Image to Form
This is my code associated with the form: # models class Date(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=64, null=True) class Photo(models.Model): date = models.ForeignKey('Date', on_delete=models.CASCADE) image = models.ImageField(verbose_name='Photos', upload_to='media/date/photos/') # view class CreateDateView(LoginRequiredMixin, CreateView): template_name = 'app/date/form.html' form_class = DateForm def form_valid(self, form): form.instance.user = self.request.user form.save() # by the way why do I save this form? Is it okay to save it in form_valid method? photos = self.request.FILES.getlist('image') for photo in photos: Photo.objects.create(image=photo) return super().form_valid(form) The issue is how to save Photo objects if it requires a Date model id. It raises NOT NULL constraint failed: app_photo.date_id As I understand I have to write something like: Photo.objects.create(date=date_from_the_form, image=photo) But how to get the pk from the Date model? Hope you understand my problem, if any questions don't hesitate to write down below in comments section. Thanks in advance! -
Django submit form POST not valid
I am attempting to submit a form to populate the database. I can't get the POST working. It doesn't look valid, but I can't figure out what I need to do to correct it. I have put some debugging on to see what happens when I click submit & the POST gets sent. I can't figure out how to send created_at or created_by. I assume these are the reason why the POST is not valid and the database is not populating. models.py from django.db import models from django.contrib.auth.models import User from django.forms import ModelForm class Order(models.Model): order_name = models.CharField(max_length=100, unique=True, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) def __str__(self): return self.order_name class Ce_Base(models.Model): ce_hostname = models.CharField(max_length=15) new = models.BooleanField() location = models.TextField() order_reference = models.ManyToManyField(Order) forms.py from django.forms import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = ['order_name'] views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Order from .models import Ce_Base from .forms import OrderForm @login_required def home(request): form = OrderForm() if request.method == 'POST': form = OrderForm() form.instance.created_by = request.user print(request.POST) if form.is_valid(): form.save() context = { 'order': Order.objects.all(), 'form': form, } return render(request, 'orchestration/order_create.html', context) … -
Upgrading from Django 1.9 to 1.11 throws TemplateSyntaxError (and I don't know why)
I have this if statement in my template: {% if user = active_user %}class="active"{% endif %} and I get Could not parse the remainder: '=' from '=' did anything change template-wise in Django 1.11? Why am I getting this and how can I fix it? Thanks. -
Django project is not running on browser
I am following a basic django project, mainly so I can see it run on the browser, because I have another django project where it says it runs on http//127.0.0.1:8000/ but on my browser it shows errors. I am working linode in cmd on windows laptop, I have edited my firewall on linode to allow ssh, http and https. https://docs.djangoproject.com/en/4.0/intro/tutorial01/ this is the tutorial I am following. This is what my code says in cmd. This is what my browser says. -
I cut/pasted a folder into a local repository mid-clone - the clone failed and the folder disappeared. Is the folder I pasted gone forever?
I wanted to put my local code into a GitHub repository. I created a repo on GitHub and tried cloning with HTTPS. The clone was taking a moment but the folder was created on my laptop so I decided to cut/paste my local code into the local repo folder. Well, the clone ended up failing and the repo folder just disappeared, along with all of its contents. The folder I added to the local repo also disappeared. I can't even find it in the recycling bin. Is it gone forever? -
Upgrading from django-activity-stream 0.6.3 to 0.6.4 breaks my app
For some reason, after I've done this upgrade, it has broken my app. I get KeyError at /analyzer/central-dev/demoproject/dossiers/6/detail/ 'request' Error during template rendering It throws this error on this piece of code <span class="label label-{{ action.data.new_status|get_status_mood }}">{% as_display action.data.new_status %}</span> If I remove {% as_display action.data.new_status %} it works, but it won't show the desired data. Why am I getting this error and how can I fix it? Thanks. -
my run button isn’t active for Python code to use Django
I’m using windows version 10, the latest Python version and the latest pip version as well, with visual studio code 2022. I’m following an online class from two years back and anytime I enter my py file my run/ debug button goes mute and I can’t click it. -
this a django ORM & drf serializers problem
The data structure I need is like this。 demo: "name": "groupname", "key": "grouping1", "base_templates": [ { "identity": "123456", "name": "createxxx", },{ "identity": "112233", "name": "deletexxx", } ] }, { "name": "groupname2", "key": "grouping2", "base_templates": [ { "identity": "123999999", "name": "runxxxx", "descr": "....." } ] } model: class TicketCategory(Model.models): name = models.CharField(verbose_name="name", max_length=100, unique=True) key = models.CharField(verbose_name="key", max_length=100, unique=True) class BaseTemplate(Model.models): identity = models.UUIDField(verbose_name="tag", default=uuid.uuid4, editable=False) category = models.ForeignKey( TicketCategory, verbose_name="grouping", on_delete=models.CASCADE ) name = models.CharField( verbose_name="name", max_length=100, default="", db_index=True ) serializers class BaseTemplateSerializer(serializers.ModelSerializer): class Meta: model = BaseTemplate fields = "__all__" class TicketCategoryDashboardSerializer(serializers.ModelSerializer): basetmplate = BaseTemplateSerializer() class Meta: model = TicketCategory fields = "__all__" class TicketCategoryDashboard(APIView): def get(self, request: Request): r = TicketCategory.objects.all().last() serializer = TicketCategoryDashboardSerializer(r) return Response(serializer.data, status=200) How to generate sample data structure through reverse query?:) -
Django - Data from view not rendered in template
I'm having quite some troubles understanding how variables are passed to templates in Django, I'm new so keep this in mind. My problem is that, when the URL is loaded data from databases can't be rendered except for the user(request.user.username) which is strangely loaded. I even tried to declare variables inside the view's def but even them are not rendered The model is imported inside the views.py. My idea is that, since the user from request.user is loaded, there must be some problem with loading the database model, but this doesn't explain why even freshly declared variables inside the view's def are not passed. In the /admin page all the models work fine. Below are the fragments of my code, they should be enough to understand the problem, if not I can upload other parts. Thank you in advance. views.py: def load_main(request): diet_list = DietTable.objects.all() return render(request, 'main/main.html', { 'diet_list': diet_list, 'user': request.user.username, }) part in the main.html: <body> ... <header> ... </header> ... {% block content %} <strong> {{ user }} {% for element in diet_list %} {{ element }} {% endfor %} </strong> {% endblock %} ... </body> urls.py: from django.urls import path, include from main import views … -
Dependency on unknown app: django.contrib.sites when trying to override sites fields
As per THIS I am trying to change the default example.com to my own values using migrations. I created a new app sites_migrations with no model, nothing basically, obviously added to installed apps. I now created empty migration file: python manage.py makemigrations --empty sites_migrations I added some code, so now it looks like this: from django.contrib.sites.models import Site from django.db import migrations def configure_sites_framework(apps, schema_editor): site: Site = Site.objects.first() site.domain = 'my-domain-name.com' site.name = 'my-domain-name.com' site.save() class Migration(migrations.Migration): initial = True dependencies = [ ('django.contrib.sites', '__latest__'), ] operations = [ migrations.RunPython(configure_sites_framework), ] I expect that django.contrib.sites migrations will now run BEFORE my app's migrations, right? When I run ./manage.py migrate I get the below error: ValueError: Dependency on unknown app: django.contrib.sites I also tried changing django.contrib.sites to sites, which produces: AttributeError: 'NoneType' object has no attribute 'domain' Interestingly, if I remove my migration file, apply all other migrations and then add my new migration file, it will be applied. But I want this to happen even on new DB. I read some posts that is should delete *.pyc files and __pycache__, which I did, but no luck. Any clue what am I doing wrong here? -
button function doesn't work without any error - django
So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it's not work. there's no error message in terminal or console too. when i clicked button audiotrack, what my terminal shown just [12/May/2022 22:11:00] "POST / HTTP/1.1" 200 8928 console my website frontend please help me to fix it. i will give my code : views.py: from django.shortcuts import render, redirect from django.views.decorators.csrf import ensure_csrf_cookie from .forms import AudioForm from .models import Audio_store from MusicLockApp.forms import AudioForm @ensure_csrf_cookie def homepage(request): # return HttpResponse('homepage') return render(request, 'homepage.html') def decode(request): # return HttpResponse('about') return render(request, 'decode.html') def upload(request): if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("main:upload") form = AudioForm() audio = Audio_store.objects.all() return render(request=request, template_name="homepage.html", context={'form':form, 'audio':audio}) urls.py : from django.contrib import admin from django.conf.urls import url from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import path, re_path from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), ] urlpatterns += staticfiles_urlpatterns() models.py: from django.db import models class Audio_store(models.Model): record=models.FileField(upload_to='media/mp3') forms.py: from django import forms from .models import Audio_store class AudioForm(forms.ModelForm): class Meta: model = Audio_store fields=['record'] add settings.py: INSTALLED_APPS … -
How to add an "Example Value" in Swagger UI using Django Rest Framework?
I want to add "Example Value" like this one enter image description here coreapi.Document( title='Flight Search API', url='https://api.example.org/', content={ 'search': coreapi.Link( url='/search/', action='get', fields=[ coreapi.Field( name='from', required=True, location='query', description='City name or airport code.' ),coreapi.Field( name='to', required=True, location='query', description='City name or airport code.' ), coreapi.Field( name='date', required=True, location='query', description='Flight date in "YYYY-MM-DD" format.' ) ], description='Return flight availability and prices.' ) } ) https://django-rest-framework-old-docs.readthedocs.io/en/latest/api-guide/schemas/ -
How do I get X-Amz-Security-Token param with boto or django-storages?
It's a Django project, I use django-storages and boto3. I use Amazon S3 to store files. Files are private, so a presigned URL is needed to access them. How do I get X-Amz-Security-Token param with boto3 or django-storages? This is the code is use to get presigned url: client = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name="eu-north-1") file_path = "private/0001.dcm" // copied directly from Amazon bucket account on key value response = client.generate_presigned_url('get_object', Params={'Bucket': BUCKET_NAME, 'Key': file_path}, HttpMethod="GET", ExpiresIn=EXPIRES_IN) The URL I get with this code is short, X-Amz-Security-Token and it doesn't work. The presigned URL I get on my Amazon account is very long and it works fine. How do I get presigned url with X-Amz-Security-Token in Python? -
Django ckeditor is removing space around <a> tags
I'm using django-ckeditor with this config: 'enterMode': 2, 'forceEnterMode': 'true', 'basicEntities': 'false', 'fillEmptyBlocks': 'false', 'tabSpaces': 0, 'entities': 'false', When the original text look like this: word1 <a>word2</a> word3 The final result after saving looks like this: word1<a>word2</a>word3 I tried almost all possibilities when it comes to basicEntities, fillEmptyBlocks, tabSpaces and other configurations, but no way, ckeditor is always removing spaces around tags. After several trials, I stopped searching for a solution. Your help will be appreciated. -
Django TypeError: Field 'id' expected a number but got <User: >
I've migrated my database and I got the error of IntegrityError at /add/ NOT NULL constraint failed: base_notebook.user_id when trying to add a note. I put the camps of null and blank but still have this error: File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'User' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Gustavo\notepad\manage.py", line 22, in <module> main() File "C:\Users\Gustavo\notepad\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\Gustavo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field self._remake_table(model, …