Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a table of events which are summarized daily
I have a model for user hours: class Hours(models.Model): project = models.ForeignKey(Project, related_name='project',on_delete=models.DO_NOTHING) owner = models.ForeignKey(User, related_name='owner', on_delete=models.DO_NOTHING, default=1) quantity = models.DecimalField(max_digits=10, decimal_places=2, default=1) product = models.ForeignKey(Product, related_name='product', on_delete=models.DO_NOTHING) inserted_at = models.DateTimeField(default=datetime.now, blank=True) date = models.DateTimeField(default=datetime.now, blank=True) and I want to display the hours in a django template as a table so that the hours are grouped and summed up daily. I understand that I cannot do the math in template, so I need to do it in view, but can you please give me some hints for that? Indrek -
How to filter class fields using objects.filter and the id=pk in django
Good evening I would like to ask for some assistance am trying to filter the title of a post so I can write the title into a file to track user activity. This is my code for writing in the file: ''' def cover(request,pk): text = coverposts.objects.get(id=pk) thistime = datetime.datetime.now() Name = coverposts.objects.get(title__id=pk) articlefile = open('useractivity.txt','a') articlefile.write('\n'+ str(Name) + ', '+ str(thistime)) articlefile.close() return render(request,'cover.html',{'text':text}) ''' And this is the class I wish to get information from : ''' class coverposts(models.Model): title = models.CharField(max_length=100) visual = models.ImageField(upload_to='images') subtitle = models.CharField(max_length=100) body = models.CharField(max_length=100000000) created_at = models.DateTimeField(default =datetime.now(), blank= True) ''' Kindly advise where am going wrong -
Celery Child Tasks Don't Run in Correct Queues on ECS
I have a django project that uses celery for task management and rabbitmq for the broker. The tasks are divided into multiple queues and in production these queues run in separate ECS containers. All the period tasks defined in celery.py scheduled via celery-beat run in the correct queues however when defining the queue inside a task using apply_async they always spawn in the default. 'default_task': { 'task': 'webapp.tasks.default_task', 'schedule': crontab(minute="*/1"), }, 'parent_task': { 'task': 'webapp.tasks.parent_task', 'schedule': crontab(minute="*/1"), 'options': {'queue' : 'secondary'} }, @shared_task(ignore_result=True) def parent_task(): qs = SomeModel.Objects.filter(status='in progress') task_expiration = 3600 for sm in qs: child_task.apply_async((sm.id,), expires=task_expiration, queue='secondary') I can confirm that the tasks are running just not on the specified queue which creates issues with timing due to potential noisy neighbors on the default queue container. Versions: django: 3.0.1 celery: 5.0.0 rabbitmq: 3.8.11 python: 3.8 -
Django dates calculator
this application should take a date from the user, store it in the database then count 9 days after it and show those 10 days in a list, I managed to make two views one to count the 10 days and show them in a list. The other view is to take the day from the user and store it in the database, now I want to connect both so by the end of the process I want the user to select the date then the application automatically stores the date and counts them and show the list. Models: from django.db import models from django.db.models.fields import DateField from datetime import datetime from django.db.models import CharField, Model # Create your models here class Event(models.Model): title = models.CharField(max_length=40) start = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) end = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) def __unicode__(self): return self.title class PeriodDate(models.Model): per_date = models.CharField(max_length=15) serializer: from dataclasses import fields from rest_framework import serializers from .models import PeriodDate class PeriodDateSerializer(serializers.ModelSerializer): class Meta: model = PeriodDate fields = '__all__' URLs: from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('CalendarCount', views.CalendarCount, name= 'index' ), path('form', views.form), ] Views: @api_view(['GET']) def CalendarCount(request): #Taking date … -
Why does Celery task autodiscovery never trigger under Django?
I've got Celery 5.2.6 and Django 3.0.6. Everything is working except task autodiscovery under Django. If I run celery worker, the worker triggers autodiscovery, finds all my tasks, and displays them in a list as part of it's startup process. However, if I run my Django app or Django shell, this never happens. Additionally, even though the docs promise that accessing the task registry will trigger autodiscovery, it does not. I print app.tasks, I call app.tasks.keys(), and still no autodiscovery - it only shows the tasks that are built-in or were registered when the module containing them happened to be imported for other reasons. What do I need to do to trigger task autodiscovery? PS - If I try adding force=True to app.autodiscover_tasks(), it fails because the Django app registry hasn't finished loading at that time. -
Django image does not duplay
I'm new to Django, and I encounter this problem with images that I can't solve... The path is like this: Django-Project, Profiles, static, media, profileIMG. Here is my model. from django.db import models from accounts.models import NewUser class UserProfile(models.Model): user = models.OneToOneField(NewUser, on_delete=models.CASCADE) profile_pic = models.ImageField(default='Untitled.png', upload_to='profileIMG') def __str__(self): return self.user.username settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' MEDIA_URL = '/media/' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('', include('profiles.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) form.py from django.forms import ModelForm from .models import UserProfile class ProfileForm(ModelForm): class Meta: model = UserProfile fields = '__all__' exclude = ['user'] view.py function @login_required(login_url='login_user') def profiles(request): indexID = request.user form = ProfileForm(instance=indexID) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=indexID) if form.is_valid(): messages.success(request, ("The file is valid")) form.save() else: messages.success(request, ("Invalid File.")) context = {'form': form} return render(request, "profiles/profiles.html", context) And my template profiles.html. {% load static %} <div class="main"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <img class="profile-pic" src="{{ request.user.UserProfile.profile_pic.url }}"/> <p>This is profile page </p> <span>Hello, {{request.user}} </span> <p>{{ form }}</p> <input class="imgBTN" type="submit" name="imgBTN"> <span><a href="{% url … -
warnings.warn("DateTimeField %s received a naive datetime (%s)"
I use django simple-history to get history on my models I then search the history results by date but I get the error below. How can I format the date? RuntimeWarning: DateTimeField HistoricalIssue.history_date received a naive datetime (2022-04-13 10:34:32) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" def SearchByDate(request): date_search = request.POST['date-search'] if date_search: admin_hist_search_results = Issue.history.filter(history_date=date_search) -
can you help to find a mistake?
Terminal says that i didn't defined DJANGO_SETTINGS_MODULE but i tried as i thought every method to do it and so far nothing helper (coding on windows) Can someone help me out please? I am stuck and dont know what to do Maby this will help - i run my virtual env through Anaconda - conda activate djangoenv raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from faker import Faker from app.models import AccessRecrod, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get topic for entry top = add_topic() # create fake data for entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # create new webpage entry webpg = Webpage.objects.get_or_create( topic=top, url=fake_url, name=fake_name)[0] # create fake access record acc_rec = AccessRecrod.objects.get_or_create( name=webpg, date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete!') -
Error 500 on Websocket, deploying Django-app on Heroku
I'm having some problems with websockets that I don't have locally. The problem is that heroku is telling me that there is a 500 error. My settings on prod: ASGI_APPLICATION = 'config.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis_url")] }, }, } My ASGI.py import django from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from my_app.chat import ( routing, ) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings") django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) I'm ready using wss instead of ws, and that not the problem. Thanks! -
How to use Django Filter with Arrayfield
Is it possible to use django-filter BaseInFilter with with django ArrayField? Here is a sample of what I am trying to do; models.py class Stays(models.Model): best_describes_house = ArrayField( models.CharField(max_length=500, blank=True, null=True), default=list, ) filterset.py class ItemInFilter(filters.BaseInFilter, filters.CharFilter): pass class StayFilter(filters.FilterSet): best_describes_house__in = ItemInFilter( field_name="best_describes_house", lookup_expr="in" ) class Meta: model = Stays fields = [ "best_describes_house__in", ] I am trying to make a request to http://127.0.0.1:8000/api/v1/stays/best_describes_house__in=villa,lake. I keep getting; operator does not exist: character varying[] = text[] LINE 1: ...ays" WHERE "lodging_stays"."best_describes_house" IN (ARRAY[... Am I doing something wrong? I have also tried doing this using IntegerField as stated from this example in the documentation - BaseInFilter, and it works fine -
Why Web server like apache/nginx cant directly server web apps made in django or flask framework?
I would like to know what's the need of this middle man- application servers like uwsgi, gunicorn. why cant a web server like Apache and Nginx directly serve a web app built in Django or flask. if your answer is that the uwsgi converts the request into a python understandable language. please elaborate on what kind of request python needs which it will understand. -
how do i get the highiest occured user in a table in Django
please I need help with this, am building an app that allows users to send out invites, and I want to get the user with the highest sent out invitations, how do I go about it. my model is as below. class Invite(models.Model): host_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL) invite = models.CharField(max_length=200, null=True,blank=True) def __str__(self): return self.name``` -
Issue migrating on m1 mac: geos incompatible architecture
I have run through a setup and I'm having issues migrating my app (within my venv). When I run python manage.py migrate I recevie this error: OSError: dlopen(/opt/homebrew/opt/geos/lib/libgeos_c.dylib, 0x0006): tried: '/opt/homebrew/opt/geos/lib//libgeos_c.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/opt/geos/lib/libgeos_c.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/opt/geos/lib//libgeos_c.1.16.0.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/opt/homebrew/Cellar/geos/3.10.2/lib/libgeos_c.1.16.0.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')) I've tried the answers to this question (missing libgeos_c.so on OSX), but none of them are working for me. I've also tried adding export DYLD_LIBRARY_PATH=/opt/homebrew/opt/geos/lib/ to my ~/.bash_profile. The output of file /opt/homebrew/Cellar/geos/3.10.2/lib/libgeos.dylib = /opt/homebrew/Cellar/geos/3.10.2/lib/libgeos.dylib: Mach-O 64-bit dynamically linked shared library arm64 The output of file $(which python3) = /Users/danieljohnson/Documents/code/project/venv/bin/python3 (for architecture x86_64): Mach-O 64-bit executable x86_64 /Users/danieljohnson/Documents/code/project/venv/bin/python3 (for architecture arm64): Mach-O 64-bit executable arm64 I'm not sure where to go from here. -
Google Drive API, Python, Django
I have some csv files that I want to generate everytime I run the script and upload them directly to google drive. When you have the files locally, it is easy to upload them. But, when I want to upload them I can't do that. I got this error instead : TypeError: expected str, bytes or os.PathLike object, not _csv.writer I am using googleapiclient.MediaFileUpload to upload the files, and the method Create_Service from Google. Here is a snippet of my code: from datetime import datetime from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload from .Google import Create_Service @api_view(['GET']) def uploadFile(request): current_date = datetime.today().strftime("%d-%m-%y") content_disposition = 'attachment; filename=' + \ 'solde_quotidien_' + str(current_date) + '.csv' response = HttpResponse() response['Content-Disposition'] = content_disposition writer = csv.writer(response) writer.writerow(['Date', 'Compte', 'Nom du client', 'Solde', 'Hold Balance', 'Type client']) client = ['2022', '34995277', 'Mehfoud', '1000000', '500'] writer.writerow(client) # Upload a file # Le nom sur le cloud file_metadata = { 'name': 'test.csv', 'parents': ['1QXu_mk5lWbNQyk-EiBnRSIQYmXqNmAdm'] } media_content = MediaFileUpload(writer, mimetype='text/csv') file = service.files().create( body=file_metadata, media_body=media_content ).execute() print(file) return response Apparently, the problem is with MediaFileUpload. What should I do in this situation? Thanks in advence. -
Error - type object '' has no attribute '' when calling class method
So I'm having a pretty weird issue with my Django app. I have a model called acsUser with a class method called getAcsMgr that should return a list of managers who have employees with access to the system. When running the app using the runserver management command this works just fine, but when running the server using Gunicorn and Nginx and navigating to the view being served the list as context I get type object 'acsUser' has no attribute 'getAcsMgr'.I'm not sure why this works locally but not when running it on the server. Please see the model and information below. Model: class acsUser(models.Model): # Everything but the adAcct field is information pulled directly from ACS using it's API call description = models.CharField(max_length=200, null=True) acsId = models.CharField(max_length=20, null=True) identityGroupName = models.CharField(max_length=200, null=True) acsName = models.CharField(max_length=20, null=True) fullName = models.CharField(max_length=200, null=True) jobTitle = models.CharField(max_length=200, null=True) supervisor = models.CharField(max_length=200, null=True) location = models.CharField(max_length=200, null=True) userDefEmail = models.CharField(max_length=200, null=True) userDefManagerId = models.CharField(max_length=200, null=True) legacySystem = models.CharField(max_length=20, null=True) created = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) enabled = models.CharField(max_length=20, null=True) lastModified = models.CharField(max_length=200, null=True) maxFailureEnabled = models.CharField(max_length=20, null=True) adAcct = models.ForeignKey('employee', null=True, blank=True, on_delete=models.CASCADE, related_name='ACSadAccount') # What to return when an instance is called … -
Why can't find or install home module in Django?
I am new to Django and is learning it from a youtube video. In the video the tutor does this from home import views. Now when i try to do the same thing i get an error saying "Unresolved reference home". So i tried installing home using pip installer but is constantly getting the following error:- Collecting uwsgi>=2.0 Using cached uwsgi-2.0.20.tar.gz (804 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\clash\AppData\Local\Temp\pip-install-gpajfqiw\uwsgi_5085974451e542118156b6196d19b2cf\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\clash\AppData\Local\Temp\pip-install-gpajfqiw\uwsgi_5085974451e542118156b6196d19b2cf\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname'. Did you mean: 'name'? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. Can somebody please tell me why this is happening and what is the solution to this error. … -
Python got error "NameError: name '_mysql' is not defined"
With Python 3.7.9, Django 3 and MariaDB, the application always fails with the error "NameError: name '_mysql' is not defined". Please see the exception trace and pip package list attached in the Details section below, and let me know if you need to see the yum package information. We highly appreciate your help. Details: 1. The full exception trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/data/app/venv3.7/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libperconaserverclient.so.21: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/data/app/venv3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/data/app/venv3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/data/app/venv3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/data/app/venv3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/data/app/venv3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/data/app/venv3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/data/app/venv3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/data/app/venv3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", … -
How to make static directory in Django
I created static directory which included css and image files in my Django project. When I run my project the css do display("GET /static/website/barber.css HTTP/1.1" 200 69) but the images do not("GET /static/website/images/balloons.gif HTTP/1.1" 404 1840), -
Uploading story to user story field without creating new story object ,but rather add to already upload stories of that user
Okay I have been stack in trying to have user create stories and add to their already uploaded stories in the backend database, but my current challenge is each time that a user uploads a story it doesn't add the story to the already existing field for that user, but rather create a new story object for that user! Is there a way that i could let users upload their new stories to add to already uploaded stories of that user ? My view for creating stories. def create_story(request): if request.method == "POST": form = StoryImageForm(request.POST, request.FILES) videos =request.FILES.getlist('video') images = request.FILES.getlist('image') title = request.POST['title'] # slug = str(title).lower().replace(" ", "-") story_data = Story(user=request.user,title=title) story_data.save() if form.is_valid(): data = form.save(commit=False) for image in images: data = StoryImage(post=story_data,user=request.user,images=image) data.save() return redirect('feed:feed') return render(request,"story/create_story.html") -
django admin panel healthcheck
I want to create a healthcheck endpoint for my django admin panel. I want to register it via admin.site.register_view (I am using the adminplus package) but I can't figure out how to made it accessible to the public, without the need to authenticate first. Any ideas? -
DRF Serialize subset of fields on nested serializer based on URL parameters
I am trying to allow the user to choose a subset of the fields in DataSerializer to be serialized instead of all fields. The serializers are as followes and the two models have a OnetoOne relation. class DataSerializer(serializers.ModelSerializer): class Meta: model = MeasurementsBasic fields = ['temp', 'hum', 'pres', 'co', 'no2', 'o3', 'so2'] def to_representation(self, instance): representation = super().to_representation(instance) return {'timestamp': instance.time_taken, **representation} return representation class NameSerializer(serializers.ModelSerializer): measurements = DataSerializer(source='measurements_basic', read_only=True) class Meta: model = Microcontrollers fields = ['measurements'] def to_representation(self, instance): representation = super().to_representation(instance) return {'station': instance.name, **representation} return representation From what i understand the way the serializers are now i have a field "measurements" instead of each individual field of DataSerializer. I want to know whether i am wrong and if i am how i could go about allowing the user to choose only certain of those fields to appear in the response. -
Django: 'Method \"PATCH\" not allowed.' 405 after adding a foreign key
I am doing a project for uni and it decided to make it in Django to learn something new. I start to regret that... and I hope that you can help. I am creating a simple API that performed well previously, but after adding the related class into a model, it allows me only to perform GET & POST operations, and I don't know why it happens and how to fix that - I have specified http methods in viewsets. I want to perform PUT, PATCH & DELETE operations as well. models.py: from django.db import models class Author(models.Model): id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=60,blank=True,null=True) last_name = models.CharField(max_length=60,blank=True,null=True) description = models.CharField(max_length=1000,blank=True,null=True) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Quote(models.Model): id = models.AutoField(primary_key=True) content = models.CharField(max_length=1000) author = models.ForeignKey(Author, on_delete=models.SET_NULL,related_name='quotes',null=True) source = models.CharField(max_length=60,blank=True,null=True) context = models.CharField(max_length=1000,blank=True,null=True) year = models.IntegerField(blank=True,null=True) def __str__(self): return self.content serializers.py: from rest_framework import serializers from .models import Quote, Author class QuoteSerializer(serializers.ModelSerializer): class Meta: model = Quote fields = ('id','content','author','source','year','context') lookup_field = 'author' class AuthorSerializer(serializers.HyperlinkedModelSerializer): quotes = QuoteSerializer(many=True, read_only=True) class Meta: model = Author fields = ('id','first_name','last_name','description','quotes') urls.py: from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'authors', views.AuthorViewSet,basename='authors') router.register(r'quotes', … -
Open the Client's Desktop Application using a button Click from Browser - Python/HTML
I want to open the desktop application(For eg: Notepad/Powerpoint/Putty). Attaching an image of how it works on sharepoint. Example image of how Microsoft Teams gets opened on the Click of the button is attached. I need this exact replica. On Clicking Open Microsoft Teams. Teams opens the meeting. Similarly I want to open an already installed desktop app on client's System. Similarly, I also want to open the Desktop Application of my company which is already installed. I used Os.Popen module of Python which works locally but, when hosted does not work. Note: OS and webbrowser module were tried. -
Spatial join in Django
I am trying to do a spatial join (as explaind here) using PostGIS within Django. The Django spatial lookups do not help. My best clue is to use custom SQL but I would really prefer to keep using a QuerySet query. In plain english my query would be: Select all estates which contains at least one building with type "heavy" Here are my two models: class Building(models.Model): type = models.CharField(max_length=255, null=True, db_index=True) footprint = models.IntegerField(null=True, blank=True) perimeter = models.PolygonField(null=True, spatial_index=True) class Estate(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) area = models.IntegerField(null=True, validators=[MinValueValidator(1)]) perimeter = models.PolygonField(null=True, validators=[estate_val.perimeter], spatial_index=True) Is there any way to do something like: estates = Estate.objects.filter(CUSTOM_JOIN_FILTER) -
Django set User for ForeignKey field in another model
I have a model like this: class File(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False, unique=True) name = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) size = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE) I'm using Django rest framework so, I created a view for this model: class FileCreate(CreateAPIView): def get_queryset(self): return File.objects.all() serializer_class = FileSerializer and I need to set user automatically for File object in view or serializer, but I don't know how... I want, when one user sends a request to create a file, "user" field in the file object automatically add request.user.