Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: Django Framework - urls.py: No "name"-Attribute in path()?
I'm currently trying to link from one HTML-Page to another one. Some Tutorials told me I need to link with an url inside the .html-file to the specific path I've been defining before. So that's what I did: <a id ="register" href="{% url 'register_view' %}"> register now</a> and inside my urls.py of the app "login" I also wanted to call the path "register_view" with the name-attribute: urlpatterns = [ path('', login_view), path('register/', register_view, name="register_view"), ] but the problem is: it won't find the attribute "name" inside `path() and I have no idea why. Can you help me out here? Thanks in Advance! -
django POST IntegrityError
I got an IntegrityError when I POST data at /users/profiles. I have only one instance in Profile model. And POST another data. I can not understand why that data exist already.. Here is my code. and I put the trace back after code. models.py from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class Job(models.Model): job_name = models.CharField(max_length=30, blank=False) def __str__(self): return f'{self.pk} {self.job_name}' class UserManager(BaseUserManager): def create_user(self, phone_nm, login_ID, login_PW, age, gender, password): if not phone_nm: raise ValueError('User must have a phone_nm') if not login_ID: raise ValueError('User must have an login_ID') if not login_PW: raise ValueError('User must have a login_PW') if not age: raise ValueError('User must have an age') if not password: raise ValueError('User must have a password') user = self.model(phone_nm=phone_nm, login_ID=login_ID, login_PW=login_PW, age=age, gender=gender, password=password) user.set_password(password) user.is_superuser = False user.is_staff = False user.save(using=self._db) return user def create_superuser(self, phone_nm, login_ID, login_PW, age, gender, password): if not phone_nm: raise ValueError('User must have a phone_nm') if not login_ID: raise ValueError('User must have an login_ID') if not login_PW: raise ValueError('User must have a login_PW') if not age: raise ValueError('User must have an age') if not password: raise ValueError('User must have a password') user = … -
Count and pourcentage
I need a function that allows you to count the number of events by occurence and calculate the percentage for each type in order to present it on a donut chart.js? #models.py Categorie = { ('Annual', 'Annuel), ('Monthly', 'Monthly, ('Weekly', 'Weekly), ('Daily', 'Daily'), } class Even(models.Model): name = models.CharField(max_length=20) date_reported = models.DateField() occurence = models.CharField(max_length=30, null=True, blank=True, choices=Categorie) def __str__(self): return self.name -
In Django/Python, how do I prefix my log messages with the current date and time?
I'm using Python 3.9 and Django 3.2. I have logging configured in my settings.py file LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, } When I do logging in one of my classes, I do it like so import logging ... class TransactionService: def __init__(self): self._logger = logging.getLogger(__name__) def my_method(self, arg1, arg2): ... self._logger.info("Doing some logging here.") How do i configure my logger such that when the message is printed out, it is prefixed by the current date and time? -
Django 1.8.19 and SQL Server
I have a problem, I am using Django 1.8.19 and SQL Server 2019, but I can't connect Django to SQL Server. How to fix it? enter image description here -
Django-filter doesn't filter
Hi I'm new in django and I want to use django-filter for url filtering in django-resframwork but i can't get my data filtered. views.py class ListingFiltered (generics.ListAPIView): queryset = Listing.objects.all() serializer_class = ListingSerializer filterset_backends = (DjangoFilterBackend) # filterset_class = ListingFilters filter_fileds= ['price'] urls.py urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('listings/', ListingViewSet.as_view(), name= 'listings'), path('listings/custom', ListingFiltered.as_view()) ] serializers.py class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing depth = 1 fields = '__all__' I'm trying http://127.0.0.1:8000/listings/custom?price=1000 and nothing happens. What am I doing wrong? -
Django form - How to autofill fielf from another
I would like to autofill my Kpi fieldd by extracting its value in the name field For example : here kpi = name.split("-")[6] which equal to CPC string. How can I do that please? class UserCampaigns(models.Model): dsp_choices =( ('Amazon', 'Amazon'), ('Amobee', 'Amobee'), ('AppNexus', 'AppNexus'), ('Digiteka', 'Digiteka'), ('DV 360', 'DV 360'), ) kpi_choices = ( ('CPA', 'CPA'), ('CPC', 'CPC'), ('CPD', 'CPD'), ('CPL', 'CPL'), ('CPM', 'CPM'), ('CPV', 'CPV'), ('CTR', 'CTR'), ('Vsibility', 'Visibility'), ('VTR', 'VTR'), ('LTR', 'LTR'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.ForeignKey(CampaignNamingTool, on_delete=models.CASCADE) dsp = models.CharField(max_length=30, choices=dsp_choices) budget = models.DecimalField(max_digits=20, decimal_places=2) kpi = models.CharField(max_length=10) #choices=kpi_choices) start_date = models.DateField() end_date = models.DateField() -
Upload Image using nextJs fail with 415 Unsupported Media Type
I am trying to send a POST request (with an image) to a /api/service/register. Request is sent via fetch api in this way: (formData is an useState) ... const [photo, setPhoto] = useState(null) const onChange = (e) => ( upDatePhoto(e.target.files[0]) ) const onSubmit = async (e) => { e.preventDefault() const body = new FormData() body.append('name', name) body.append('photo', photo) body.append('email', email) body.append('phone', phone) body.append('description', description) try { const res = await fetch('/api/service/register', { method: 'POST', body: body }); ... but i get this error 415 Unsupported Media Type It seems that when I get req.body, I got nothing register.js export default async (req, res) => { ... const apiRes = await fetch(`${API_URL}/ServiceOwners/register/`, { method: 'POST', headers: { 'Authorization': `Bearer ${access}`, }, body: req.body }); ... when i print req.body i get this format ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="name" test test ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="photo" blob:http://localhost:3000/3a6396ef-c0b3-4b7c-8dd5-13f581f0ff59 ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="email" testtest@gmail.com ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="phone" 03 43 55 21 00 ------WebKitFormBoundaryebJPBXTlpiCCQCeA Content-Disposition: form-data; name="description" test ------WebKitFormBoundaryebJPBXTlpiCCQCeA-- I'll show more code if needed. Thanks -
Django form that updates multiple records
I have 2 classes of users who can view a screen that lists all users in my app. The type of user is controlled by a Boolean field on the User model. The screen currently lists out the Users and various details about them (see below). Project Managers should see a read only view of the page where as Administrators should have the ability to edit the Users as well. HTML for the screen. <div class="card-body"> <div class="table-responsive"> <table class="table text-sm mb-0"> <thead> <tr> <th>#</th> <th>Username</th> <th>First Name</th> <th>Last Name</th> <th>Is Contributor?</th> <th>Is Project Manager?</th> <th>Is is_administrator?</th> </tr> </thead> <tbody> {% for user in users %} <tr> <th scope="row">{{ user.id }}</th> <td>{{ user.username }}</td> <td><a class="btn btn-primary" href=" " role="button">{{ user.first_name }}</a></td> <td>{{ user.last_name }}</td> <td>{{ user.is_contributor }}</td> <td>{{ user.is_projectmanager }}</td> <td>{{ user.is_administrator }}</td> <td><a class="btn btn-info" href="" role="button">Edit</a></td> <td><a class="btn btn-danger" href="" role="button">Delete</a></td> </tr> {% endfor %} </tbody> </table> </div> </div> I want to create a version of the screen available to admin users which allows them to view and update users all at once. How can I create a form that updates all the users at once? I'm looking to build something that lists out the users with … -
Send request to Schema Marshmallow + Django
I have a view : class ArticlesListView(APIView): authentication_classes = (JWTAuthentication,) def post(self, request, *args, **kwargs): """Post an Article.""" try: schema = ArticleSchema() article = schema.load( json.loads(request.body)) schema.context = {'request': request} except ValidationError as e: return json_response(e.messages, 400) return json_response(schema.dump(article), 201) which posts, though I wanted to send a request to the ArticleSchema() how can I do this ? Below is the schema : class ArticleSchema(Schema): class Meta(object): model = Article id = fields.Integer() title = fields.String(validate=validate.Length(max=255)) content = fields.String() regions = fields.Method( required=False, serialize="get_regions", deserialize="load_regions" ) @post_load def update_or_create(self, data, *args, **kwargs): print(" args ", args) print(" kwargs ", kwargs) regions = data.pop("regions", "") title = data.pop("title", "") content = data.pop("content", "") user = User.objects.get(id=1) article, _ = Article.objects.update_or_create( id=data.pop("id", None), owner=user, title=title, content=content, defaults=data ) if isinstance(regions, list): article.regions.set(regions) return article -
how do you iterate through two items in a model and display on site using Django?
I have a models.py with the following fields: class ChatStream(models.Model): bot = models.TextField() user = models.TextField() name = models.CharField(max_length=100, null=True) created_date = models.DateTimeField(auto_now_add=True) And I'd like on a website to iterate through "bot" and "user" one at a time, so the site would hypothetically display something like: bot: hello! user: what's up? bot: I'm good user: What's your name bot: bot is my name .... etc. this would keep going... So in my views.py I have def displayDict(request): m = ChatStream.objects.all() return render(request, 'chatStream.html', {"chat": m}) def send(request): message = request.POST.get('userMessage', False) ip = visitor_ip_address(request) response = routes(message, ip) print(ip, "user sent:", message, "bot response:", response) chatItem = ChatStream(bot=response, user=message, name=ip) chatItem.save() return HttpResponseRedirect('/chat/') Then in my template, chat.html I have {% block chatStream %} {% endblock %} And chatStream.html: {% extends 'chat.html' %} {% block chatStream %} {% for a in bot%} {% for b in user%} <p> <b>bot:</b> {{a}} <br> <b>user:</b> {{b}} <br> </p> {% endfor %} <form action="/send/" method = "post">{% csrf_token %} <input type="text" name="userMessage"> <input type="submit" value="Send to smallest_steps bot"> </form> {% endblock %} But this does not work -- no text from the model is displayed on the site. thank you -
django import-export adding an emailValidator adds a new field on export
I have these models: Investment Profile wherein Investment has a foreign key to Profile through email. I'm trying to bulk export but the export adds a duplicate profile__email without any values. Sample result: I noticed its from the added validator in my InvestmentResource: class InvestmentResource(resources.ModelResource): class ValidatingEmailForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row=None, *args, **kwargs): try: validate_email(value) except ValidationError as e: # a quirk of import-export means that the ValidationError # should be re-raised raise ValueError(f"invalid email {e}") try: val = super().clean(value) return value except self.model.DoesNotExist: raise ValueError(f"{self.model.__name__} with value={value} does not exist") email = fields.Field(attribute='profile__email', widget=ValidatingEmailForeignKeyWidget(Profile, field='email'), column_name='profile__email') class Meta: model = Investment clean_model_instances = True import_id_fields = ('id',) fields = ( 'id', 'notes', 'firstname', 'lastname', 'email',) export_order = fields def before_import_row(self, row, row_number=None, **kwargs): self.profile__email = row["profile__email"] self.profile__firstname = row["firstname"] self.profile__lastname = row["lastname"] def after_import_instance(self, instance, new, row_number=None, **kwargs): """ Create any missing Profile entries prior to importing rows. """ try: # print(self.isEmailValid(self.email), file=sys.stderr) profile, created = Profile.objects.get_or_create(email=self.profile__email) profile.firstname = self.profile__firstname profile.lastname = self.profile__lastname profile.save() instance.profile = profile except Exception as e: print(e, file=sys.stderr) If I try to remove the validator and change email in fields to profile__email, the fields exported are what is expected, but when importing, the emails … -
GitHub CI Test Error: relation does not exist. (DRF as BE)
I am working on a project based on Django Rest Framework and I got some CI Test errors when I try to merge my branch to main. Before I merge to main, I have already made some Django Unit Tests and they all can pass locally. (My database is postgres) Here is the error detail: Here is the CI Test Error I have never face this error locally. I tried to re-migration and migrate the database but it still fails in CI test. Dose this because CI test and Django test have different operation logic? Or is it because I have a problem with the processing of the postgres? This is my first question on stackoverflow, appreciate for any reply! -
Render Python seaborn Plot on Django Template
I am trying to render the plot generated by seaborn on Django template. I have the following code in my views.py: def booking_hour_plot(): qs = bookings_today() df = read_frame(qs) plot = sns.countplot(data=df) return plot def render_stats_page(request): #general info user_count = total_users_until_now() cancel_rate = activity_cancel_rate() #activity/booking details activity_set = activities_today() booking_set = bookings_today() plot = booking_hour_plot() return render(request, "stats.html", {'name':'Avonmore Statistics', 'total_user':int(user_count), 'cancel_rate': round(float(cancel_rate), 2), 'booking_count_today': booking_set.count(), 'activity_count_today': activity_set.count(), 'activities_today': activity_set, 'bookings_today': booking_set, 'booking_hour_plot': plot, }) And I have a html template called stats.html that containing the plot. The templates directory and views.py are in the same directory: <li>Real Time Plot: {{booking_hour_plot}}</li> However, the rendered html page is not really showing the plot. It's more like the plot object: enter image description here Any Idea how to put the real plot on the html page, rather than this plot object? -
dlib makes videostream laggy on django
im pretty new in codes and i just start new project using django opencv and dlib. My project have face recognition feature so i use opencv videostream. But i got problem with videostream becomes so laggy everytime i try to call dlib face detector, not only the face detector but whenever i tried to call another dlib's function the videostream still lag. Im using my laptop webcam for the project, is it does also affecting the codes? Can anyone help me? I've been stuck for week and still not found the answer:( -
Strange "on" type being recorded in MySQL database (Navicat Premium) in Django
I have been trying to insert information with an HTML form into my database. However, when I submit, my "gender" and my "website_rating" has been strangely replaced with "on", when it is supposed to be replaced with my website input. Image of the Database: https://i.stack.imgur.com/94d8L.png Here is my models.py # _*_ coding:utf-8 _*_ from __future__ import unicode_literals from django.db import models """ Quick Guide to Model Fields that We Did Not Use: - models.ForeignKey() - models.DateTimeField() - models.IntegerField() - models.IPAddressField() - models.FileField() - models.ImageField() """ # Create your models here. class PersonalInfoResponse(models.Model): # Personal Info Section name = models.CharField(max_length=30, null=True, default="N/A", verbose_name=u"Name") age = models.IntegerField(verbose_name=u"Age", default="N/A", null=True) email = models.CharField(max_length=30, null=True, default="N/A", verbose_name=u"text#@thing.com") gender = models.CharField(max_length=7, null=True, verbose_name=u"gender") # Website Response Section website_rating = models.CharField(max_length=3, verbose_name=u"1-10", null=True) heardof_flag = models.BooleanField(verbose_name=u"truefalse", null=True) heardof = models.CharField(max_length=255, null=True, verbose_name=u"How did you know about the C&C Education Center?") # Misc Section fav_subject = models.CharField(max_length=50, null=True, default="None", verbose_name=u"truefalse") fav_website = models.CharField(max_length=255, null=True, default="N/A", verbose_name=u"What is your favorite part about this website?") website_improve = models.CharField(max_length=255, null=True, default="N/A", verbose_name=u"What is something that this website needs improvement on?") class Meta: verbose_name = u"User Contact Info" verbose_name_plural = verbose_name And here is my views.py from django.shortcuts import render from … -
Django-vimeo 'NoneType' object is not iterable
Model structure is like below: class Video(models.Model): video_header = models.CharField(max_length=350, verbose_name="Video Başlığı", blank=False, null=False) video_description = models.TextField(verbose_name="Video Açıklaması", blank=False, null=False) date_created = models.DateField(auto_now_add=True, verbose_name="Oluşturma Tarihi", blank=False, null=False) video = fields.VimeoField(null=True, blank=True) def __str__(self): return self.video_header class Meta: verbose_name = "Video İçeriği" verbose_name_plural = "Video İçerikleri" When I click on any video object which created in django admin to edit it, get " 'NoneType' object is not iterable " error. But actually there is a object and it is not "None" when I look at database and also checked it in frontend. So it seems like meanless to me. Could you please help me to get through this problem. -
Custom save method with condition in django model
I am trying to do a django project where a user can describe pictures using one or more taggings, as soon as more than one user has entered the same tagging for the same picture, this word or tagging should be saved to the Tag table. I thought I can solve this by adding a custom save method to the Tag model. Would this be the right approach or would I write this logic inside a view? class Tag(models.Model): LANGUAGES = (('en', 'english'), ('de', 'deutsch'), ('fr', 'francais') ) name = models.CharField(max_length=256) language = models.CharField(max_length=256, choices=LANGUAGES) class Tagging(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, blank=True, default='') picture = models.ForeignKey(Pictures, on_delete=models.CASCADE, related_name='taggings', default='') tag = models.ForeignKey(Tag, on_delete=models.CASCADE) created = models.DateTimeField(editable=False) score = models.PositiveIntegerField(default=0) -
Get data from external URL in JSON format with Django REST
I want to do simple Rest API in Django. It's my first approach to Rest in django, but for now it isn't going that bad ;) For now I have a model database with two fields brand and model. With the use of Postman, I can GET, POST and DELETE objects, cool. But what I'm stuck with is -> When I POST an object, first I'd like to check if that model with given brand even exists. I want to check it on specific website: link. (In the URL of that website I can change brand name so it gives me a list of model with given brand) My approach would be, when request.method=='POST' first GET data from website, load it to a model and then somehow compare it with data in POST request. But I don't know how to get to that point :) Is it a good approach or is there a way to directly look at data on the given website? (For me there is no need to give you my code, because there is nothing special in it, but tell me if I'm wrong!) -
How to run a rabbitMQ script in a django rest framework project
So I have a django rest framework project, and what I want to do, is to push into a rabbitMQ queue some values from a file with a python script, and as soon as my django server starts running, I want the project to start consuming the messages available in the queue, and with those values, insert entities in my database. So here is my producer python script: import pika, csv, time url = 'queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') with open('sensor.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter='\n') for row in reader: channel.basic_publish(exchange='', routing_key='hello', body=row[0]) print(row[0]) time.sleep(1) connection.close() This script doesn't belong to the django project, I will run this script outside of it. This is my consumer script: import pika from app.models import Measurement url = 'queue_url' params = pika.URLParameters(url) connection = pika.BlockingConnection(params) channel = connection.channel() channel.queue_declare(queue='hello') def callback(ch, method, properties, body): measurement = Measurement.objects.create(sensor=3, energy_consumption=float(str(body))) measurement.save() channel.basic_consume('hello', callback, auto_ack=True) channel.start_consuming() connection.close() I want to integrate this consumer script inside my django project, so that as soon as I start putting messages in my queue with the procuder script, the consumer script is ready for them, intercepts them and inserts a new entity … -
("Django tried these URL patterns... The empty path didn't match any of these.") How to fix "Page not found (404)" error
I am using the visual studio code for the basic Django project and whenever I try to run the server it gives the error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in startup.urls, Django tried these URL patterns, in this order: login/ admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Whereas I write the code correctly landing app folder views file code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def loginpage (request): return render (request, 'login.html') landing app file urls.py code from django.contrib import admin from django.urls import path from. import views urlpatterns = [ path('login/',views.loginpage, name="login" ), landing app file login.html code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <h1> Login </h1> </body> </html> main project urls.py file code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('login/',include('landing.urls')), path('admin/', admin.site.urls), ] Please help me regarding this. -
Google Cloud Django if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): not working
I am working on a Google Cloud Django Project. I am trying to check in settings.py if I am running in Development or Production mode. I added the following block of code to test if the SOFTWARE where the program is running either is on my machine or on Google Cloud Servers. # | settings.py | if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'): #code to execute in production else: #code to execute in development I noticed that the if statment is always false, so I decited to debug the os.environ dict. The result of the debug is that the value of the key SERVER_SOFTWARE of the enviroment is equal to gunicorn/20.1.0. As written in the correct answer of this stackoverflow question, when running on production (so on Google Cloud Severs App Engine), the value of SERVER_SOFTWARE should be Google App Engine/X.Y.Z, where X, Y and Z represent the version of Google Cloud. But, as I said, my value, when running on App Engine, is not like that, it is gunicorn/20.1.0. So, how do I make the program know if I am running either in development or production? -
Why DRF IsAuthenticatedOrReadOnly class permission class allowing Post method
I am performing test on Django rest framework, here is my view, class PostList(generics.ListCreateAPIView): permission_classes = [IsAuthenticatedOrReadOnly,] queryset = Post.postobjects.all() serializer_class = PostSerializer Url pattern like bellow, urlpatterns = [ path('<int:pk>/',PostDetail.as_view(),name="detailcreate"), path('',PostList.as_view(),name="listcreate"), ] Here is my test : def create_post(self): self.test_category = Category.objects.create(category='django') self.test_user = User.objects.create_user(user_name="test_user",password="123456789") data = {"title": "new", "author": 1, "excerpt": "new", "content": "new"} url = reverse('api:listcreate') response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) i ran followiing command: coverage run --omit='*/myvenv/*' manage.py test and get output : Ran 1 test in 0.215s OK as my understanding, as here permission class is [IsAuthenticatedOrReadOnly,] , self.client should not have permission to post and test should Failed. I don't understand what i am missing here. -
Djange NoReverseMatch error - reverse for 'edit' with no arguments not found
In a Django app I am building for a course, I am attempting to pass a parameter from one template to a function in views.py through a url path. The path definition in urls.py contains the parameter name, and the same name is required by the function in views.py. The link in my template points to the correct url path and names a value for the parameter, but I am still receiving a NoReverseMatch error. Weird because I have another url path that requires a parameter and which is working perfectly. entry.html Here is the link to the path called edit in urls.py. I want to pass the value of the variable entryTitle to the url as entry: {% extends "encyclopedia/layout.html" %} {% block title %} {{ entryTitle }} {% endblock %} {% block body %} {{ entry|safe }} <button> <a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a> </button> {% endblock %} urls.py the edit path is the last one defined in urlpatterns from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("new", views.new_page, name="new"), path("wiki/edit/<str:entry>", views.edit, name="edit") ] views.py This is the edit function, requiring entry as an argument … -
Django: The Model could not be created because the data didn't validate. error
I'm trying to create an app to import thanks to an uploaded .csv file data to my database. This is my code and when I try to submit a new file I'm getting this error The Dataset could not be created because the data didn't validate. I can't also access the file If I create it in admin because I get this error Dataset matching query does not exist. I think my problem is within the ForeignKey and the OneToOneField that I'm not able to save properly? Or that I'm not actually creating a new Dataset atl all? Only the model File is compiled by the user, while Dataset should be filled from the information in the file and linked to the file and the user automatically . Thank you all for your help! VIEWS @login_required def file_upload(request): data = None if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) data_form = DatasetForm(request.POST, request.FILES) raw_file= request.FILES if file_form.is_valid() or data_form.is_valid(): data = request.FILES['file_upload'] data = pd.read_csv(data, header=0, encoding="UTF-8") data_form.instance.user = request.user.profile file_form.instance.user = request.user.profile file_form.instance.filename = raw_file['file_upload'].name Dataset.objects.create( name_user_A = data.iloc[0,1], name_user_B = data.iloc[1,1], [...] ) data_form.save() file_form.save() return redirect('upload_file') else: return redirect('home') else: form = FileForm() context = { 'data': …