Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm working on Django project Asynchronous with Uvicorn async view
python==3.11.3 asgiref==3.6.0 Django==4.1.8 I'm working on Django project Asynchronous with Uvicorn async view. all the building books is fine but when I call the post build it create the book but show's this problem but after refreshing the page again it showin TypeError at /builds/ sync_to_async can only be applied to sync functions. ` import re from subprocess import check_output from asgiref.sync import sync_to_async from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.db.utils import IntegrityError from django.shortcuts import get_object_or_404, render, redirect from django.views.generic import View from crayon.books.models import Book from crayon.builds.models import Build from crayon.core.mixin import AsyncViewMixin class AsyncViewMixin: async def __call__(self): return super().__call__(self) def build_book(book_id: int, user_id: int) -> str: global document, build # step 1: Get the book book = Book.objects.get(id=book_id, creator_id=user_id) # step 2: compile the book's contents build = Build.objects.create(builder_id=user_id, book_id=book_id) build.status = Build.STATUS.IN_PROGRESS build.save() document_list = [] for chapter in book.chapter_set.all(): document_list.append(f"# {chapter.title}") # If a "reges" finds an markdown H1 if re.search(r"\n\#\s", chapter.body) or re.match("\#\s", chapter.body): chapter.body = add_pound_to_headers(chapter.body) document_list.append(chapter.body) document = "\n\n".join(document_list) # step 3: render as something using pandoc # Pandoc -o book.html input.md with open("input.md", "w") as f: f.write(document) commands = ["pandoc", "-o", "book.html", "input.md"] output = check_output(commands) return output … -
Django adding related field with multiple databases
I have a Django project with two databases, each has a game model and a language model that are connected with Many2Many relationships. When saving each object with: game.save(using=db) I’m able to save to the desired database, but when I attempt to add the related field: game.add(language) It doesn’t work for the second database. Any idea why? *from research I think it might be a problem in my routers.py but I took it from the Django documentation.. -
django-tailwind: doesnt start upon running 'python manage.py tailwind start'
i followed the docs and it says that after the command 'python manage.py tailwind start' the development server should start. however im getting this and its stuck on the 'rebuilding phase' and doesnt continue Node.js: v18.10.0 django: 4.2 django-tailwind: 4.5 > my_theme@3.5.0 start > npm run dev > my_theme@3.5.0 dev > cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w Rebuilding... Done in 1143ms. anyone encountered a similar problem? -
PyReportJasper connection error with a report with null values
i'm trying to create a Django Rest app and im trying to create reports, since pip doesn't support Crystal Reports or viceversa i'm trying to use Jasper Studio, the problem here is this: def generar_reporte(self, request): REPORTS_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '') input_file = os.path.join(REPORTS_DIR, 'CuentasXCobrarSL.jrxml') output_file = os.path.join(REPORTS_DIR, 'CuentasXCobrarSL') conn = { 'driver': 'com.microsoft.sqlserver.jdbc.SQLServerDriver', 'username': 'sa', 'password': 'sa123*', 'host': 'IBM2', 'database': 'Futuro', 'port': '1433' } try: pyreportjasper = PyReportJasper() pyreportjasper.config( input_file, output_file, output_formats=["pdf"], parameters={ 'FI': "19/04/23 00:00:00", 'FF': "20/04/23 00:00:00", 'Directorio': 0, 'TipoCtaId': 0, }, ) pyreportjasper.process_report() with open(output_file + '.pdf', 'rb') as f: data = f.read() response = HttpResponse(data, content_type='application/pdf') response['Content-Disposition'] = 'filename=CuentasXCobrarSL.pdf' return response except Exception as e: print(f"Error: {e}") return Response("Error generando el reporte.", status=status.HTTP_500_INTERNAL_SERVER_ERROR) here are the parameters that this report needs, FI and FF are dates, Directorio, TipoCtaId and MonedaType are integers This is a test report, when it finally works i'll use request params but for now, i'm using static params, but... when i call this function without the connection to the database, it returns me a pdf with all values in null, but when i put the connection it returns me a NullPointerException, i think the problem is in the connection, i dont know … -
Pipenv shell won't open an environment in current directory
When I create a new directory and change to it, I try to start a new pipenv environment and it opens to my root directory. I was messing with my path, adding geckodriver, and that seemed to have thrown it off. Here's my terminal: christopherchough@Christophers-MacBook-Pro ~ % cd ~/Desktop christopherchough@Christophers-MacBook-Pro Desktop % mkdir superlists && cd superlists christopherchough@Christophers-MacBook-Pro superlists % pipenv install django Installing django... Resolving django... Installing... Adding django to Pipfile's [packages] ... ✔ Installation Succeeded Installing dependencies from Pipfile.lock (c91b9a)... To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. christopherchough@Christophers-MacBook-Pro superlists % pipenv shell Launching subshell in virtual environment... . /Users/christopherchough/.local/share/virtualenvs/christopherchough-PpcwrOBl/bin/activate christopherchough@Christophers-MacBook-Pro ~ % . /Users/christopherchough/.local/share/virtualenvs/christopherchough-PpcwrOBl/bin/activate (christopherchough) christopherchough@Christophers-MacBook-Pro ~ % I was expecting it to show: (superlists) christopherchough@Christophers-MacBook-Pro superlists ~ % -
Styling showing different on 2 separate apps with exact same style sheet
I am having an issue currently and I have no idea how to debug it so I'm hoping some one else may have encountered this or may point me in a direction to look. I have 2 django apps.... both identical HTML and Styling... But on one of them it is right and one is wrong... Please see screen shots and any ideas are welcome. EDIT when i remove the block in image below the styling goes to normal. -
Deploying a Django app with azure Web Service
I want to deploy a Django 3.2.18 app to the Azure cloud. I use the Azure DevOps pipeline to pull changes from the GitHub master branch and deploy them to the Azure web service. Here below is my Yaml file. # Python to Linux Web App on Azure # Build your Python project and deploy it to Azure as a Linux Web App. # Change python version to one thats appropriate for your application. # https://docs.microsoft.com/azure/devops/pipelines/languages/python trigger: - master variables: # Azure Resource Manager connection created during pipeline creation azureServiceConnectionId: '8b946b7b-8609-45ea-992d-ab1dadcbfcd0' # Web app name webAppName: 'ELaden' # Agent VM image name vmImageName: 'ubuntu-latest' # Environment name environmentName: 'ELaden' # Project root folder. Point to the folder containing manage.py file. projectRoot: $(System.DefaultWorkingDirectory) # Python version: 3.7 pythonVersion: '3.7' stages: - stage: Build displayName: Build stage jobs: - job: BuildJob pool: vmImage: $(vmImageName) steps: - task: UsePythonVersion@0 inputs: versionSpec: '$(pythonVersion)' displayName: 'Use Python $(pythonVersion)' - script: | python -m venv antenv source antenv/bin/activate python -m pip install --upgrade pip pip install setup pip install -r requirements.txt workingDirectory: $(projectRoot) displayName: "Install requirements" - task: ArchiveFiles@2 displayName: 'Archive files' inputs: rootFolderOrFile: '$(projectRoot)' includeRootFolder: false archiveType: zip archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip replaceExistingArchive: true - upload: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip … -
Render image into django template
I am struggling to render an image into django template when I have paginator on. Here are my models: class BlogPost(models.Model): title = models.CharField(max_length=100, default="",) published = models.BooleanField(default=False) slug = models.SlugField() class BlogPostImage(models.Model): post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to="blogposts/", validators=[validate_file_size]) HTML: {% for post in page.object_list %} {% if post.published %} <picture> {% for post_image in post.images.all %} <img class="blog--box__image" src="{{post_image.image.url}}" alt=""> {% endfor %} </picture> {% endif %} {% endfor %} -
Filter by reverse lookup count of related field in django query
In my Django project, I have models for User, Player, and Game. A User can be a Player in any number of Games. There is a user statistics view (in this case, we are talking about finished games), that can be filtered and ordered by many different attributes. Example: each Game is played on a specific map. In the view, the map can be filtered; then, for each user, only the games are considered that were played on the filtered map. I want to do the same thing for number of players in the game; consider only the games played with e.g. 2 players in the statistics. There is no attribute players in the model Game; it's a reverse foreign key from model Player. To build the statistics per User: I start with User.objects.all() Create a player_filter containing the set parameters, e.g. player_filter = Q(player__game__map='O') Then apply annotations (e.g. users.annotate(high_score=Max('player__score', filter=player_filter)) Then display these values somehow in the view. However, to filter player from games with X number of players, I would need to do something like player_filter = Q(COUNT(player__game__player_set)=2) (not a working syntax of course). How can I do this? I kind of need to annotate the related player__game … -
Why the django signal receiver is not being executed?
I have the following code: signals.py: from django.dispatch import Signal, receiver new_device_signal = Signal() src/controller.py: from django.dispatch import receiver from domotic.signals import new_device_signal class Controller(MQTTClient): @receiver(new_device_signal) def handle_new_device_signal(self, sender, name, is_sensor, **kwargs): print('Añadiendo nuevo dispositivo: ' + name) if is_sensor == True: self.sensors.append(name) else: self.switches.append(name) def __init__(self, host, port): super().__init__(host, port, CONTROLLER_ID) self.rules = [] self.switches = [] self.sensors = [] #Lee todos los devices que hay registrados en la base de datos for device in Device.objects.all(): if device.is_sensor == True: self.sensors.append(device.name) else: self.switches.append(device.name) #Lee y procesa todas las normas que hay en la base de datos for rule in RuleText.objects.all(): self.rules.append(loadRule(rule.name)) new_device_signal.connect(self.handle_new_device_signal) views.py: from domotic.models import Device, RuleText from domotic.signals import new_device_signal class DeviceCreateView(CreateView): model = Device template_name = 'app/device/new.html' fields = ['uid', 'name', 'is_sensor'] success_url = reverse_lazy('app:devices') def form_valid(self, form): response = super().form_valid(form) new_device_signal.send(sender=self.__class__, name=self.object.name, is_sensor=self.object.is_sensor) return response apps.py: from django.apps import AppConfig class DomoticConfig(AppConfig): name = 'domotic' def ready(self): import domotic.signals settings.py: INSTALLED_APPS = [ "domotic.apps.DomoticConfig", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', init.py: default_app_config = 'domotic.apps.DomoticConfig' I don't understand why even though the send in views.py is being executed the handler is not I tried to follow every post regarding this matter but i could not solve … -
Why clean_data works with or without self?
Why clean_data works with or without self ? Because I tested my project and whether I put a self or not, it doesn't change anything at all thks with def clean(self): cleaned_data = super().clean() quantity = self.cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data without def clean(self): cleaned_data = super().clean() quantity = cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data **Complete code : ** class OrderForm(forms.ModelForm): # je modifie le widget utilisé # modifier la qté dans le panier : quantity = forms.IntegerField(max_value=100, min_value=1) # supprimer un article du panier : delete = forms.BooleanField(initial=False, required=False, label='supprimer') class Meta: model = Order fields = ["quantity", 'delete'] def clean(self): cleaned_data = super().clean() quantity = self.cleaned_data.get("quantity") if quantity > self.instance.ticket.stock: raise forms.ValidationError(f"Il ne reste que {self.instance.ticket.stock} tickets en stock") return cleaned_data # relier le delete avec save def save(self, *args, **kwargs): # récupérer les données de mon formulaire : # avec cleaned_data qui est un dictionnaire, données de mon formulaire après qu'il ait été validé if self.cleaned_data['delete']: # if self.cleaned_data['delete'] is True: return self.instance.delete() return super().save(*args, **kwargs) I just know and understand why self is optionnal. thks -
Not able to send the comment to db and getting "IntegrityError at /add-comment NOT NULL constraint failed: core_comment.post_id"
models.py This was the model I created : class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) user = models.CharField(max_length=100) image = models.ImageField(upload_to='post_images') caption = models.TextField() created_at = models.DateTimeField(default=datetime.now) no_of_likes = models.IntegerField(default=0) def __str__(self): return self.user class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.user, self.name) views.py I am not able to create object at the backend. would be helpful if anyone knew how to call post and add it to the views. @login_required(login_url='signin') def add_comment(request): if request.method == 'POST': # import pdb # pdb.set_trace() user = request.user.username comment = request.POST['comment'] new_comment = Comment.objects.create(name=user, body=comment) new_comment.save() return redirect('/') else: return redirect('/') index.html : along with forms <!-- Comment section --> <form action="add-comment" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> <!-- Comment section typing box --> <div class="bg-gray-100 bg-gray-100 rounded-full rounded-md relative "> <!-- <a href="/add-comment?post_id={{post.id}}"> --> <input type="text" placeholder="post a comment" class="bg-transparent max-h-10 shadow-none" name="comment" id="comment"> <div class="absolute bottom-0 flex h-full items-center right-0 right-3 text-xl space-x-2"> <button class="button bg-blue-700" type="submit">submit</button> </div> </div> </form> I am not able to bring the comment to the backend as I am new to django. comment section looks like this tracebackcall -
How to do type checking while using Django?
There are linters that support type checking, however they become a mess in a Django project. Is there any way to have type checking for where I define type hints, but not do it for all the Django bits and pieces? I'm using Conda and VS Code. -
In DRF's generics.UpdateAPIView perform_update, why are changes to the instance still reflected if those changes happen after the instance is saved?
I'm a little confused about why this code block is still updating the database correctly, despite us not saving the instance after the changes were made. In fact, the changes happened after the instance was saved. What gives? class ProductUpdateAPIView(generics.UpdateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_fields = 'pk' def perform_update(self, serializer): instance = serializer.save() if not instance.content: instance.content = instance.title # why do we not save it here? This code was taken from https://youtu.be/c708Nf0cHrs?t=7030 and the author, unfortunately, did not expand upon it. Can someone explain it, please? Thank you in advance! -
I am unable to upload big file with NGINX, NGINX max upload has no effect
I'm learning Django, Docker and Nginx. For this, I am using nginx proxy but it is throwing 413 Request Entity Too Large when uploading images but the image size is not significant. I added client_max_body_size 1024M; in htttp, server and location in nginx.conf and default.conf but it did not solve my problem Do I need to do any thing to uwsgi? -
Internal Server Error: TypeError in Django Rest Framework viewset
I am building an API using Django Rest Framework for managing assignments. I have a viewset for Assignment model that allows to create new assignments via a POST request to /api/assignment/Assignment/. However, when I make the request, I get an "Internal Server Error" with the following traceback: Internal Server Error: /api/assignment/Assignment/ Traceback (most recent call last): File "D:\project\Assignments-Api\.venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\project\Assignments-Api\.venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\project\Assignments-Api\.venv\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\project\Assignments-Api\.venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception return int(value) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'DeferredAttribute' It seems that the error occurs in the views.py file of Django Rest Framework, but I cannot figure out the root cause of the issue. What could be causing this error and how can I resolve it? But Data saved in the model as expected. -
Django dataabse problem: (fields.E300) and (fields.E307)
Could you help me to fix this problem? I know i can't import abstract class into database, but i have no idea how to fix my code :) https://github.com/ichecinski/chess_guide i have an error: chess.Ruch.figura: (fields.E300) Field defines a relation with model 'Figura', which is either not installed, or is abstract. chess.Ruch.figura: (fields.E307) The field chess.Ruch.figura was declared with a lazy reference to 'chess.figura', but app 'chess' doesn't provide model 'figura'. your text I tried to delte abstract class or change the ForeignKey, but it didn't work for me. -
Read one side of the association
Let's say we have two models in our Django app: class Member(models.Model): name = models.CharField() class Project(models.Model): name = models.CharField() Normally, for a many to many field I would make an intermediary table and just query that: class ProjectMember(models.Model): project = models.ForeignKey(Project) member = models.ForeignKey(Member) Is there a way to retrieve a queryset to list only the projects for a member? I tried ProjectMember.objects.filter(member=member).only('project') but I still get the ProjectMember object list with only the project field populated. I was wishing to retrieve a list of Project objects. -
Unable to create a sqllite test database in django
I am building a laboratory management software right now as a passion project, and I am getting stuck trying to test the Django backend of my application. I am trying to create a test database to use with pytest. I am using MySQL on PlanetScale as the default database, but if I were to create a second database for testing, I would have to upgrade from the free version. If possible, I want to avoid this, so I'm trying to use a SQLite database for testing. I need to figure out how to run my pytests using a second sqlite database. To begin, I run pytest using my dockerfile FROM python:3.11-alpine ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add --no-cache mariadb-dev RUN pip install -r requirements.txt RUN apk del build-deps COPY . /code/ RUN pytest -v Once it starts running the pytests I receive an error, and all errors I receive from any test are the same. An example test would be @pytest.mark.django_db def test_create_user_serializer_save(valid_user_data): serializer = CreateUserSerializer(data=valid_user_data) assert serializer.is_valid() == True user = serializer.save() assert User.objects.filter(email=valid_user_data['email']).exists() == True assert user.name == valid_user_data['name'] … -
Using Django-simple-history with postgresql
So i was django simple history on my local server and using sqlite to test it out to see how I liked it. I decided to keep it for production, but I'm wondering if there is anything special needed to use simple history with postgress as that is what I am using for production. I migrated my changes with simple history over but it doesnt seem to want to show any kind of history for changes made. Is there something I need to do like save it? Reading documents online but I am not seeing much -
RegisterUserView creates user but doesn't log in user
I am trying to make a class-based registration view equivalent of my old function based registration view. When I register as a new user, a user is created but is not logged in after registration, and this bug only happens when I use class-based registration view. Form doesn't return any errors also. So views.py class-based (doesn't log in after registration) from django.contrib import messages from django.contrib.auth import login from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import NewUserForm class RegisterUserView(CreateView): form_class = NewUserForm success_url = reverse_lazy('home') template_name = 'users/register.html' def form_valid(self, form): user = form.save() login(self.request, user) return super().form_valid(form) def form_invalid(self, form): messages.error(self.request, form.errors) return super().form_invalid(form) views.py function-based (does log in after registration) from django.contrib import messages from django.contrib.auth import login from django.shortcuts import redirect, render from .forms import NewUserForm def register_user(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') messages.error(request, form.errors) form = NewUserForm(request.POST) context = { "form": form } return render(request, "users/register.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import CustomUser class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model … -
Paginating Django query results in a table
I am having issues with paginating my query results. When I use the query without pagination it works as intended, but once I add the pagination to the query I am seeing results on the last page that do not match what was defined in the search. For example, if I search a date like april 5th, 2023 I get 53 as my last page, after clicking on 53 to view the page 54 appears in the pagination as the last page. If you navigate to 54 it has items from later dates. Also I noticed if you navigate to a page in the query then try to navigate back to the first page the table then shows results from earlier dates. I have tried researching and fixing this but I am at a loss, any help would be greatly appreciated. models.py: class Package(models.Model): barcode = models.AutoField(primary_key=True) barcode_img = models.ImageField(upload_to='images/', null=True) origin = models.CharField('Origin Location', max_length=50, choices=[(location.locations, location.locations) for location in Location.objects.all()]) destination = models.CharField('Destination Location', max_length=50, choices=[(location.locations, location.locations) for location in Location.objects.all()]) description = models.CharField('Description', max_length=50) date_created = models.DateTimeField('Date Created', default=timezone.now) employee = models.ForeignKey(Employee, on_delete = models.CASCADE, default=320557) status = models.CharField('Status', default='Created', max_length=50) views.py: def search(request): form = SearchForm() … -
Django, Integrity error with PK, but new objects are still working fine
So here's my view def add_tutorial(request): if request.method == 'POST': User = request.POST.get('user') # other properties lang = request.POST.get('lang') new_tutorial = Tutorial.objects.create( User=User, ..., lang=lang) context = { 'page_title': 'create tutorial', } return render(request, "add-tutorial.html") I do create a tutorial with forms, it all works well, I can see the tutorial where it needs to be, but for some reason I get integrity error regarding the pk IntegrityError at /add_tutorial. UNIQUE constraint failed: main_tutorial.id The Id in the db is correct (i use sqlight). Before I used to specify the id in the create function, but now it shouldn't be any problem since I've dropped that db and (properly) undone all migrations; nothing changed [the only meaningful traceback that i get is to the Tutorial.objects.create(...) line] -
Return response not downloading through pandas Django
I want to export the query data if the form is valid after submitting two dates from a modal form. I don't understand why the return response is not working here. Any help would be appreciated. def load_date_range_ajax(request): data = dict() template_name ='date_range_modal.html' if request.method == 'POST' and request.is_ajax(): form = DateRangeForm(request.POST) if form.is_valid(): data['form_is_valid'] = True start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] with connection.cursor() as cursor: cursor.execute('''qry_string;''') rows = cursor.fetchall() response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="Location Date.xlsx"' df = pd.DataFrame(rows, columns=[col[0] for col in cursor.description]) df.to_excel(response, index=False, header=True) return response else: data['form_is_valid'] = False else: form = DateRangeForm() data['html_form'] = render_to_string(template_name, context={'form': form}, request=request) return JsonResponse(data) -
Django "This field is required." error every time I fill out my video post form
As the title says, I'm getting this error and I'm not really sure why am I getting it. Here's my models.py for the video upload form: class Video(models.Model): title = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to='videos/thumbnails/', null=True) video = models.FileField(upload_to='videos/video/', validators=[FileExtensionValidator(allowed_extensions=["mp4", "mov"])]) date = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=True) user = models.OneToOneField(User, related_name='user',on_delete=models.PROTECT) description=models.TextField(validators=[MinLengthValidator(10)], blank=True) category= models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) game = models.ForeignKey(Igdb, on_delete=models.PROTECT, null=True,blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Video, self).save(*args, **kwargs) def __str__(self): return self.title Here's my forms.py: class videoupload(forms.ModelForm): title = forms.CharField(max_length=100, widget= forms.TextInput (attrs={'placeholder':'Title'})) thumbnail = forms.ImageField() video = forms.FileField(widget= forms.FileInput (attrs={'class':'videobox'})) description = forms.Textarea() category = forms.Select() game = forms.Select() class Meta: model = Video fields = ['title', 'description', 'thumbnail', 'video','category', 'game'] exclude = ("date","user", "slug") And here's my views.py: def uploadpage(request): if request.method == "POST": form = videoupload(request.POST,request.FILES or None) if form.is_valid(): video = form.save(commit=False) video.user = request.user video.save() return redirect("home") else: form = videoupload() return render(request, "glavna/upload.html", {"form": form}) I'm trying to have it post a video, username would be automatically filled out.