Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
displaying json data to django template
i am getting data from mongodb and first inserting all the data into pandas and then converting that data to json data and then print that data in table format my views.py looks like this def generate(request): a=str(request.POST.get('level')) b= request.POST.get('status') c=(request.POST.get('startdate')) g=datetime.strptime(c,"%Y-%d-%m") d=datetime.strftime(g,"%Y/%d/%m") e=request.POST.get('enddate') h=datetime.strptime(e,"%Y-%d-%m") f=datetime.strftime(h,"%Y/%d/%m") output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\intern mongo\\indicator\\work\\water.py',a,b,d,f],stdout=PIPE,text=True) client=pymongo.MongoClient("mongodb://localhost:27017") db = client["water"] colle= db["waterlevel"] df3=pd.DataFrame() df4=pd.DataFrame() data_from_db = colle.find({},{"_id":0,"time":1,"status":1,"level":1}) for datta in data_from_db: df=pd.DataFrame(datta) df4=pd.concat([df4, df], ignore_index=True,axis=0) json_records = df4.reset_index().to_json(orient='records',date_format='epoch') data = [] data = json.loads(json_records) context = {'d': data} return render(request,'result.html',context) and my html template is this <!DOCTYPE html> <html lang="en"> <head> <title>TableView - Startup</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2 class="text-center"><u>water table</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>time</th> <th>status</th> <th>level</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% now "U" %} {% for i in d %} <tr> <td>{{i.time|date:'U'}}</td> <td>{{i.status}}</td> <td>{{i.level}}</td> </tr> {% endfor %} {% endif %} </tbody> </table> </div> </body> </html> the problem is I am getting DateTime in UNIX format I want it in readable date type format can someone suggest a better way to display pandas dataframe in Django template as a table other than … -
form rendering 'None' in production
When I use the password reset in development it works fine. However in production after the user opens the reset email the password reset form is not displayed however other forms on the site via crispy forms are working fine. Nothing has been changed from dev to production besides the url in the view. The server and dev are running the same version of crispy forms. I did it based off this tutorial and it seems I have made all the required changes for production When checking the urls of the email between production and dev i do not see an issue http://127.0.0.1:8000/reset/MQ/***hm*-e00d**b30b635b358be1573e********/ https://domain.co/reset/MQ/***ht*-71ff80c**580c6cecc3ffd44********/ If I try and render the form like {{ form }} it only renders None leading me to believe the context is not being passed view: def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)|Q(username=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" plaintext = template.loader.get_template('users/password_reset_email.txt') htmltemp = template.loader.get_template('users/password_reset_email.html') c = { "email":user.email, 'domain':'domain.com', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'https', } text_content = plaintext.render(c) html_content = htmltemp.render(c) try: msg = EmailMultiAlternatives(subject, text_content, 'myemail@email.com', [user.email], headers = {'Reply-To': 'myemail@email.com'}) msg.attach_alternative(html_content, "text/html") msg.send() … -
How to select one object each from django distinct queryset
Suppose class SavedPosts(models.Model): user = models.ForiegnKey(...) post = models.ForiegnKey(...) collection_name = models.CharField(...) I am getting colection names using SavedPosts.objects.filter(user_id=request.user.id).values("collection_name").distinct().order_by('collection_name') How do i get image of post from that collection? Just like instagram do. Can it be done without creating seperate model for collection? -
Django Breadcrumb error: Reverse for 'projectnotes_list' with no arguments not found
I am trying to use django-views-breadcrumbs to add breadcrumbs to a site. I can get it to work with some views but I am getting an error with a particular listview. When I attempt to visit this listview page I see the error. The error appears to be related to a need for the correct context. So far I have not been able to figure this out. The error: NoReverseMatch at /projects/project/1/notes/ Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z'] Request Method: GET Request URL: http://co1.localhost:8000/projects/project/1/notes/ Django Version: 3.1.14 Exception Type: NoReverseMatch Exception Value: Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z'] Exception Location: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages/django/urls/resolvers.py, line 689, in _reverse_with_prefix Python Executable: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/bin/python Python Version: 3.9.6 Python Path: ['/Users/user/Desktop/otools', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages'] Server time: Sun, 20 Feb 2022 15:52:17 +0000 The list view: class ProjectNotesList(ListBreadcrumbMixin,ListView): model = ProjectNotes template_name = 'company_accounts/project_notes.html' comments = ProjectNotes.comments def related_project(self, **kwargs): project = get_object_or_404(Project, id=self.kwargs.get('pk')) notes = ProjectNotes.objects.all return notes def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments')) The urls.py from django.urls import path, include from .views import CompanyProjects, … -
Calling view via ajax with submit button works, but hitting enter key just displays ajax dictionary
I have a todo list app adds a Task object to the database and appends it to the page, it is working without a problem. However, it only works when I click the submit button, if I hit the enter key, I just see the ajax data in my browser as such: {"task": {"id": 1, "title": "example task", "completed": false}} and I am curious as to why this is and if there is a way to change this functionality? The tutorial I'm following mentioned that on my form I must use <button type="button"> and not <input type = "submit"> because the ladder will "send the forms data directly to the TaskList view, but we want to use another way of sending requests so we need to disable this behavior." I imagine that is what is happening when I hit the enter key? Code: html: <form id = "createTaskForm" method="post" data-url = "{% url 'task_list_url' %}"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <button id = "createButton" type="button">Sumbit</button> </form> <div id = "taskList"> {% for task in tasks %} {{task.title}} {% endfor %} </div> JavaScript/jQuery: $(document).ready(function(){ $('#createButton').click(function() { // Get form data let … -
Like/Dislike Counter is not adding/removing after Click in Django project
This is a social media type project (Django/Python) and when I click on the Like/Dislike Button it does not register a Like or a Dislike.. Not getting an error simply nothing is happening. Code Below - thank you in advance! This is the entire code in my views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import PostForm from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.views import View from main_app.models import Post class PostList(ListView): def get(self, request, *args, **kwargs): posts = Post.objects.all() form = PostForm() return render(request, 'main_app/post_list.html', {'post_list': posts}) def post(self, request, *args, **kwargs): posts = Post.objects.all() form = PostForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() return render(request, 'main_app/post_list.html', {'post_list': posts}) class PostCreate(CreateView): model = Post fields = '__all__' success_url = '/posts/' class PostUpdate(UpdateView): model = Post fields = ['text'] success_url = '/posts/' class PostDelete(DeleteView): model = Post success_url = '/posts/' def show(request, post_id): post = Post.objects.get(id=post_id) return render(request, 'show.html', {'post': post}) class AddLike(View): def post(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) is_dislike = False for dislike in post.dislike.all(): if dislike == request.user.id: is_dislike = True break if is_dislike: post.dislike.remove(request.user) is_like = False for like in post.like.all(): if like == request.user: is_like … -
How I can remove the unwanted data and save only required results from Django form?
Submit I want to send form data to the backend without having unwanted data here fname I only want email. I am trying to build a function which will first validated by js so a bot protection. How can i made my django form completion to occur. <form id="regForm" name="myForm"> <div class="tab"> <h4 id="jsa" >Validation</h4> <p> <input placeholder="First name..." oninput="this.className = ''" name="fname" /> </p> </div> <h3 id="valid_error"></h3> <div class="tab"> Contact Info: <p> <input placeholder="E-mail..." oninput="this.className = ''" name="email" /> </p> </div> <div style="overflow: auto"> <div> <button type="button" id="prevBtn" onclick="nextPrev(-1)" > </button> {% csrf_token %} <button type="submit" id="nextBtn" onclick="nextPrev(1)" > Join </button> </div> </div> </form> So I want to submit my data with js validation -
Problem with filtering data via custom function in Python (Django)
I want to get 4 random objects from Product I'm trying to filter it by check_existing_id function and random.randint and I use while loop to get 4 objects from the database. However this piece of code in some cases returns only 3 objects. There is a bug hidden in the code and I have no idea where I need this to return exacly 4 elements every single time. I'm pasting the code below it's just a simple function: def check_existing_id(list,number): for i in range(len(list)): if list[i] == number: return False return True class GetRecommendedProducts(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): product_id = self.kwargs['product_id'] products_length = len(Product.objects.all()) id_list = [] while len(id_list) < 4: id = random.randint(0, products_length) if check_existing_id(id_list, id) and id != product_id: id_list.append(id) return Product.objects.filter(id__in=id_list) -
How to modify save function for model in Django
I have a problem. In my Department model I override save function. The logic is next: every Department can have one superior department, and one department can have many subsidiary dep's. My first if works correctly, if I choose superior dep's, when save existing instance, this superior in result have self as subsidiary. But my second if doesn't work. Do you have any idea what I am doing wrong? class Department(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) description = models.CharField(max_length=300, blank=True, verbose_name='description') subsidiary = models.ManyToManyField( 'self', blank=True, symmetrical=False, related_name='subsidiary_name') superior = models.ForeignKey( 'self', null=True, blank=True, related_name='superior_name', on_delete = models.SET_NULL) manager = models.ForeignKey( Manager, related_name='manager_name', null=True, on_delete = models.SET_NULL) status = models.BooleanField(default=True) proxy = models.ForeignKey( Manager, on_delete = models.SET_NULL, blank=True, verbose_name='Proxy', null=True, related_name='proxy_name') # TODO history = HistoricalRecords() def get_subsidiary(self): return "\n".join([p.title for p in self.subsidiary.all()]) def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) # override superior instance by adding subsidiary instance automatically if self.superior: superior_department = Department.objects.get(title=self.superior.title) superior_department.subsidiary.add(self) if self.subsidiary: subsidiary_dep = Department.objects.filter(title__in=self.subsidiary.values('title')) for dep in subsidiary_dep: dep.superior.add(self) -
How to add data to my table searching by user in html with Django
I am working on a project that needs to get attendance from students. The system has a page with a field to input student id or email and a submit button. And when inputting the Data into the form and clicking on the button it has to search for the student in the database and add +1 for their attendance. I have searched everywhere, but no idea how to do that. Could anyone help me ? -
Join Queries in Django
SELECT * FROM reservation LEFT JOIN auth_user ON reservation.personel_id_id = auth_user.id WHERE reservation.id='pk' AND auth_user.id='pk' Hello , I am trying to fetch result of this sql query in django. How can I do this Query using Django ORM's ? -
Will my django web app also work on linux?
So I am building a simple crud webapp using django on frontend I am using typescript no frontend frameworks or libraries whatsoever. And currently I am doing this on windows 10 but if I switch to linux Ubuntu completely and continue building this on linux, Will it have any problems when building it even if I use the same version of django and python that was on windows 10. I am asking this because of problems in past that it works on one machine but not on different so then vm's and container technologies came out. Appreciate any help. -
use of property decorator in Django to calculate Sum
I have two moldes in which one model consists of file field. I have to calculate total size of the files in the parent model within the property decorator. I think this could also be done inside the serializer class using the serializer method but I want within the property decorator. class Package(models.Model): name = models.CharField(max_length=50,blank=True) />....................other fields.........../ **/.........problem is here..../** @property def folder_size(self): all = self.details.all() all.annotate() return total Here I need help to calculate the sum of all files sizes of a single package. Class Details(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,null=True, related_name='details') notes = models.FileField(blank=True, null=True) @property def file_size(self): return self.file.size -
Performing a Subquery, Sum and Join in django ORM
I have 2 django models which aren't linked by ForeignKey due to legacy system. class Parent(model): name -> CharField() class Child(model) parent_name -> CharField() cost -> IntegerField() I want to achieve a left join which gives me all parent columns along with sum of cost column from children. SQL in postgres translates to select parent.name, sum(child.cost) as cost from parent join child on parent.name = child.parent_name group by parent.name; Is there any way to achieve this with django ORM I have tried a lot of things but https://code.djangoproject.com/ticket/28296 might be what is blocking. -
Exiftools not installing on Heroku
I am trying to deploy my first project on Heroku and having an issue trying to install Exiftools on Heroku. My site is highly dependent on using ExifField within my models to get image information from pictures which is then displayed within my Django Admin to be edited etc. This all works fine locally in development. Exiffield relies on Exiftool.exe to work, so I have to install a buildpack to Heroku which I have done, but it fails to see it during release when pushing to Heroku via CLI. All Django modules have installed OK. I have added Procfile , requirements, runtime and everything seems to go OK, it even states it's intalled Exiftool but fails on release. Log below. Any help would be greatly appreciated. I was thinking it was issue with Procfile but it seems correct. release: python manage.py migrate web: gunicorn blog.wsgi Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Delta compression using up to 16 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (4/4), 375 bytes | 375.00 KiB/s, done. Total 4 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the … -
ModuleNotFoundError: No module named 'pip' not
I have an error when installing any package using pip Below the snippet: (venv) D:\projectodb>pip install psycopg2 Traceback (most recent call last): File "C:\Users\joao.malebo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\joao.malebo\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "D:\projectodb\venv\Scripts\pip.exe\__main__.py", line 4, in <module> ModuleNotFoundError: No module named 'pip' (venv) D:\projectodb>` -
Rendering dynamic search in PDF xhtml2pdf Django
I am having some problems in rendering a a search query in PDF in Django. What I am trying to achieve is to print in PDF a web page search (I am filtering some data basically) and print the results in PDF. I can be more clear with some code. views.py def total_flight_hours(request): students = Student.objects.all() instructors = Instructor.objects.all() aircrafts = Aircraft.objects.all() start_date = request.POST.get('start_date') if not start_date: start_date = dt.now().date() end_date = request.POST.get('end_date') if not end_date: end_date = dt.now().date() student = request.POST.get('student') if not student: student = '' instructor = request.POST.get('instructor') if not instructor: instructor = '' aircraft = request.POST.get('aircraft') if not aircraft: aircraft = '' log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft)) log_entry_dual = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft) & Q(solo_flight=False)) total_flight_hours = log_entry_dual.aggregate(eet=Sum(ExpressionWrapper( F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_flight_hours != None: total_flight_hours = duration(total_flight_hours) log_entry_solo = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft) & Q(solo_flight=True)) total_flight_hours_solo = log_entry_solo.aggregate(eet=Sum(ExpressionWrapper( F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_flight_hours_solo != None: total_flight_hours_solo = duration(total_flight_hours_solo) log_entry_list = zip(log_entry, log_entry_solo) student_mission = StudentMission.objects.filter( log_entry_id__in=log_entry) month_begin = dt.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0) today = dt.today().date() context = { 'log_entry': log_entry, 'log_entry_solo': log_entry_solo, 'total_flight_hours': … -
Pagination not taking effect on webpage
I'm applying pagination on my sports.html page, In views.py I'm using listview and using paginate_by = 2 but issue is pagination is not taking effect on webpage. Pagination numbers are visible on page and when clicking on those page numbers it's not showing any error but all posts are visible on all pages, posts are not dividing up by paginate_by value. Pastebin link for your reference: https://pastebin.com/utnd6v5N can anyone point out what I'm doing wrong here. -
Edit FileField file contents from Django Admin
I have a situation where I have python scripts that are stored as files that need to be modified from the Admin panel. Currently some of my models can have scripts attached to them: class Action(PolymorphicModel): title = models.CharField(max_length=100) text = BBCodeField('text', blank=True) action_script = models.FileField(upload_to='action_scripts') In my Admin panel I can upload a file but I have been asked to make this file editable in-place if the user has the right permissions. I've searched all over for an idiomatic way to do this, and so far I've come up with the following ideas: Override the FileField widget to include an text edit box and save button. This seems very brute forced Replace models.FileField with subclass of models.TextField, implement read from file, save to file, but then I lose the upload widget and data still gets stored in DB. This seems dirty because in the database all I'm storing is a filename. FileField feels like the right field type here. Write a custom ModelForm that includes forms.TextField. Handle save to file using the save method. I'm not sure how to accomplish this because I would have to generate a filename on the fly and I don't have a primary key … -
Handle deadlock in django with corrupted savepoint
I have an unavoidable bulk_create deadlock in my code. I decided to handle this part inside an atomic block and re-issue transaction when deadlock happened. Something like this: while True: try: with transaction.atomic(): bulk_create_some_data() return except OperationalError: log_error() continue But this causes error You can't execute queries until the end of the 'atomic' block. I checked history of statements of mysql and found that the savepoint has been corrupted as below log shows. *************************** 1. row *************************** event_id: 1 SQL_TEXT: set autocommit=0 MESSAGE_TEXT: NULL *************************** 2. row *************************** event_id: 2 SQL_TEXT: SAVEPOINT `s139836523404544_x2` MESSAGE_TEXT: NULL *************************** 3. row *************************** event_id: 3 SQL_TEXT: INSERT INTO `Transaction` ... MESSAGE_TEXT: Deadlock found when trying to get lock; try restarting transaction *************************** 4. row *************************** event_id: 4 SQL_TEXT: ROLLBACK TO SAVEPOINT `s139836523404544_x2` MESSAGE_TEXT: SAVEPOINT s139836523404544_x2 does not exist I found this thread which explains corruption of a savepoint is possible, it is an old thread and I am not sure whether it is still valid or not. How can I manage scenario like this to prevent an unavoidable lock causes my program crash. I am using django 3.1 and mysql 8.0. -
What's the difference between Reverse vs. Redirect in Django?
I am doing a django project, and is very confused about reverse, reverse_lazy and redirect. Can redirect function redirect with parameters? Or should I change method to reverse whenever I want to post parameters? -
can i make a view visible to some specific users and other not on Django
I want to make some pages not accessible for some users , what i mean for example i want to make user1 can see a viewa and can not see a viewb, I have tried to do that I have developed 2 functions of permissions and role user function: then i have go to home template where there was a sidebar contain 2 list(every list call a view) , I want to make just the users that are permitted tosee this view-list can see it on the navigate bar; here is the code in template.html: <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> {% if perms.app1_name.is_normaluser_login_required %} <li class="nav-item"> <a href="#" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> Module 1 <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="{%url 'form_module1'%}" class="nav-link"> <i class="far fa-circle nav-icon"></i> </a> </li> </ul> </li> {% endif %} {% if perms.app2_name.is_privilgeuser_login_required %} <!----> <li class="nav-item"> <a href="#" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p> Module2 <i class="right fas fa-angle-left"></i> </p> </a> <ul class="nav nav-treeview"> <li class="nav-item"> <a href="{%url 'form_module2'%}" class="nav-link"> <i class="far fa-circle nav-icon"></i> </a> </li> </ul> </li> {% endif %} </ul> </nav> ---> after that the two lists disappear from the … -
distinct() method doesn't work with values() in Django
I am following Mosh's Django course, and I followed him step by step untill I get stack in this issue here, for him it works fine, but for me it doesn't work, I can't call distanct() method from values() why is that? I have searched in Django documentation and I found nothing I thought may they update it ,Igoogled it too but I haven't found an answer yet, could any one here help me ? queryset = OrderItem.objects.values('product_id').distinct() -
How do add some specific loaders to my webpack.config.js file
I want to add image-webpack-loader, file-loader and url-loader into my webpack.config.js file This is my webpack.config.js file: const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, //additional configuration to handle *.ccs files { test: /\.css$/i, use: ["style-loader", "css-loader"], }, { test: /\.(png|jpg|jpeg|gif|svg|eot|ttf|woff|woff2)$/, loader: "url-loader", options: { limit: 10000, }, }, { test: /\.json$/, use: [ { loader: "file-loader", options: { name: "data/[name].[ext]", }, }, ], },//end loader ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; I have tried this configuration tell me if this is right or what changes I should do to this... -
How to prefill serializer with user and fixed data?
I'm creating a simple game in which, after you log in, you need to create a character. My first problem is that I don´t know how to map the character I want to create to the User field (that has a OneToOne relationship). I'm using Simple DRF simple JWT for registration/login (which returns, after login, just the token and the refresh token) I wanted to prefill some fields (like hp set to 100, lvl to 1, etc). My approach is the following but it's not working, always getting something like "lvl": [ "field is required."] : Serializer: class CreateCharacterSerializer(serializers.ModelSerializer): hp = serializers.IntegerField(required=True) lvl = serializers.IntegerField(required=True) class Meta: model = Character fields = ('user', 'name', 'lvl', 'hp', 'current_hp', 'strength', 'agility',) def create(self, validated_data): instance = self.Meta.model(**validated_data) validated_data["lvl"] = 1 instance.save() return instance Views: class CharacterCreate(generics.CreateAPIView, PostUserWritePermission): permission_classes = [PostUserWritePermission] queryset = Character.objects.all() serializer_class = CharacterSerializer def post(self, request, format='json'): serializer = CreateCharacterSerializer(data=request.data) if serializer.is_valid(): character = serializer.save() if character: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)