Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using django models to map one to many and many to one
I started using django today and am having trouble creating models based off the response of an API call. We can have a Course that gives a list of professors. Though, Professors can also teach multiple courses. I'm not sure how to create a list for both professors in the Course class and courses in the Professor class. Note: I am using MongoDB so I wasn't using the postgres ArrayFields. I have the following code: from django.db import models class Course(models.Model): department = models.CharField(max_length=4) course_number = models.CharField(max_length=4) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) credits = models.IntegerField(max_length=1) gpa = models.DecimalField(max_digits=4, decimal_places=3) professors = ??? class Professor(models.Model): id = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=100, unique=True) reviews = models.BooleanField(default=True) courses = ??? I visited this stackoverflow post and wasn't sure if this was the best way to approach it considering this might be a bit outdated. I also viewed the ArrayFields class to attempt to use that but wasn't sure if that was only for postgres (because I'm using MongoDB) -
I don't have models.Model.objects
For some reason I can do almost everything on Django but access to model.objects, like, it doesn't even appear, I cannot delete nor find anything without that (or I do not know how), I'm learning django from a basic course. I use Python 3.11, Django 4.1.4, on Pycharm 2022.3. PD: If you know of another way of doing the Create, Read, Update and Delete of objects I would apreciate that. Sorry for the english. I tried searching on the web about this problem but sinsce I'm a noob on Django and trainee on python most things are like white noise to me, like, I don't understand. -
Ajax doesn't wait for server response
On this website I allow user to make some posts. The details of the posts are saved in the database and the file in the user account folder with Django file system. When I try to delete the post with Ajax I get the console.error from Ajax error: function(data). The ERROR. ERROR... Object { readyState: 0, getResponseHeader: getResponseHeader(e), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(e, t), overrideMimeType: overrideMimeType(e), statusCode: statusCode(e), abort: abort(e), state: state(), always: always(), catch: catch(e) , … } delete_post.js:26:21 error http://127.0.0.1:8000/static/javascript/delete_post.js:26 jQuery 6 DeletePost http://127.0.0.1:8000/static/javascript/delete_post.js:7 DeleteP http://127.0.0.1:8000/UserProfile/alexandra28/:198 Here is the Html and JavaScript. <button class="delete" id="delete" type="button" name="button">Delete</button> <script> const post_id = {{post.post_id}} function DeleteP(post_pk){ const delete_btn = document.getElementById("delete") function onDelete(){ location.reload(true) } if (delete_btn != null){ delete_btn.addEventListener("click", function(){ DeletePost(post_id, onDelete(), delete_btn) }) } } //console.log(post_id) DeleteP(post_id) </script> Then Ajax. function DeletePost(post_id, uiUpdateFunction, delete_button){ //event.preventDefault() const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; payload = { "post_id": post_id, } $.ajax({ headers: {'X-CSRFToken': csrftoken}, type: 'POST', dataType: "json", url: "/delete_post_url/", //async: false, //cache: false, timeout: 0, data: payload, success: function(data){ console.log('SUCCESS: ' + data['response']) if(data['response'] == "Post deleted."){ delete_button.click() } else if(data['response'] != null){ alert("This is data: ", data['response']) } }, error: function(data){ console.error("ERROR...", data) alert(data.status); // the status code alert(data.responseJSON.error); // the message alert("Something … -
How do I get a value from a different model in django?
Im new to django and im trying to figure out how to set the value in a model = to a value in another model from django.db import models from django.contrib.auth.models import User class Company(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, null=True, blank=True) # This is the value I want _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name class Product(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) companyName = # I want the name here _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name I've tried these but they dont work companyName = Company.name companyName = models.CharField(Company.name, max_length=100, null=True, blank=True) -
I would like to limit the borrowing objects in my Django app
I have an app that displays games and user can borrow them. I want to limit the amount of borrowed games for each user to max 3 games. I created two models borrow and games. The methods work well except for the max borrowing. # Method display borrowed games @login_required def borrows(request): borrows = Borrow.objects.filter(owner = request.user).order_by('date_borrowed') context = {'borrows':borrows} return render(request, 'gameapp/borrows.html', context) ` # Methos allow the user borrow single game @login_required def borrow(request, boardgame_id): boardgame = Boardgame.objects.get(id=boardgame_id) if request.method != 'POST': form = BorrowForm() else: form = BorrowForm(data = request.POST) if form.is_valid(): borrow_boardgame = form.save(commit = False) borrow_boardgame.owner = request.user # Replace the borrow varibale from borrow Model to main game borrow_boardgame.borrow = boardgame form.save() return redirect('gameapp:borrows') context = {'boardgame': boardgame, 'form':form} return render(request, 'gameapp/borrow.html', context) ` ` # Method display borrowed games @login_required def borrows(request): borrows = Borrow.objects.filter(owner = request.user).order_by('date_borrowed') context = {'borrows':borrows} return render(request, 'gameapp/borrows.html', context) # Methos allow the user borrow single game @login_required def borrow(request, boardgame_id): # I tried this boardgame = Boardgame.objects.get(id=boardgame_id) if request.method != 'POST': form = BorrowForm() else: form = BorrowForm(data = request.POST) if form.is_valid(): borrow_boardgame = form.save(commit = False) borrow_boardgame.owner = request.user # Replace the borrow varibale from borrow … -
How to handle search in a django app, when the search bar is located in a separate html file?
I programmed a website with Django. I have separated frequently repeated items, like navbar, in separate html files and I have used in them other pages using {%include%} tag. The search bar is also located in the navbar. When I try to handle search event, it does not work. Here is my search bar form: <form id="top-search-form" action="{%url 'search'%}" class="header-search-light" method="get"> <input type="search" name="search_query" class="search-input" placeholder="search..." required="" style="display: none;"> <button type="submit" class="search-button"> <i class="fa fa-search" aria-hidden="true"> </i> </button> </form> My search view is: def search(request): print('Hey, You are searching something!!') search_query = '' if request.GET.get('search_query'): search_query = request.GET.get('search_query') print("SEARCH: "+search_query) return HttpResponse(search_query) I'm not sure about what the solution is. I will appreciate your help guys. -
I cannot deploy my app to heroku after adding settings for static files
I am doing a project for college this was my first app with django I have no prior experience to this I am trying to deploy my app to heroku, I deployed it a couple of hours back with "DISABLE_COLLECTSTATIC" config and it was working. When I tried adding the static files settings the app was not working anymore, it still deploys but I get the "Application Error" when i open the app. This is settings.py import os from pathlib import Path import dj_database_url from django.contrib.messages import constants as messages import mimetypes development = os.environ.get('DEVELOPMENT', False) MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', '') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = development # Application definition INSTALLED_APPS = [ # My apps 'learning_logs', 'users', # Default apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'cloudinary_storage', 'django.contrib.staticfiles', 'cloudinary', 'bootstrap4', 'tinymce', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Does Python or Django have a built-in function that checks for a numbers value and returns a preset default if the value is None?
Does Python or Django have something like this built in? def f(value, if_None=0): if value is None: return if_None else: return value -
How Can I Convert Panda Dataframe to Dict By Adding Header in Item
enter image description here Hi everyone, I have a dataframe as in the picture from yfinance. I will use it on Django Rest Framework. So I need to change the format and make small changes... Basically, I want to convert it to dict but i need timestamp in items as below... If someone can help me i would be appreciated... { { 'datetime': '22-09-30' 'TotalRevenue': 'xxxx' 'CostOfRevenue': 'xxxx' }, { 'datetime': '22-06-30' 'TotalRevenue': 'xxxx' 'CostOfRevenue': 'xxxx' }, { 'datetime': '22-03-30' 'TotalRevenue': 'xxxx' 'CostOfRevenue': 'xxxx' }, { 'datetime': '21-12-30' 'TotalRevenue': 'xxxx' 'CostOfRevenue': 'xxxx' } } I'm so familiar with Panda so i tried a few things... stockTicker = yf.Ticker(symbol + '.IS') stockIncomeQuarterlyPanda = stockTicker.quarterly_income_stmt stockIncomeQuarterlyChangeNan = stockIncomeQuarterlyPanda.fillna(0) stockIncomeQuarterlyPandaToDict = stockIncomeQuarterlyChangeNan.to_dict() stockIncomeQuarterly = stringify_keys(stockIncomeQuarterlyPandaToDict) This is my code now... -
using .all() in views and for loop in template shows all content created from Album model
I have two model: Album and Primary model, I want to submit Primary model using pure Html Form but as you can see in the Primary model there is a field that has a relationship with a Album model using ForeignKey, when user is trying to create Primary model in form he\she may sees all the content that is created in the Album model using this method: def primary_submit_form(request): albums = Album.objects.all() if request.method == 'POST': admisssion_number = request.method.POST['admisssion_number'] profile_picture = request.FILES['profile_picture'] first_name = request.method.POST['first_name'] sure_name = request.method.POST['sure_name'] gender = request.method.POST['gender'] student_create = Primary.objects.create( admisssion_number=admisssion_number, profile_picture=profile_picture, first_name=first_name, sure_name=sure_name, gender=gender, year_of_graduations=year_of_graduations ) student_create.save() return redirect('Primary-Albums') return render(request, 'create_primary_student_information.html') My templates: <select class="form-select"\> {% for album in albums %} <option value="1"\>{{album.name}}\</option\> {% endfor %} </select\> my models: class Album(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Primary(models.Model): addminssion_number = models.CharField(max_length=40) profilePicture = models.ImageField(upload_to='image') first_name = models.CharField(max_length=40) sure_name = models.CharField(max_length=40) gender = models.CharField(max_length=25) year_of_graduations = models.ForeignKey(Album, on_delete=models.CASCADE) How can i allow user to create primary model without seeing all album that is created by other's user, i dont want my user to see the content that he\she does not create. I knew using .all() method in views and … -
What is the best way to query ChatGPT regarding writing code?
I have been interacting with ChatGPT on openAI.com and trying out the code it has written. I have asked it various questions regarding Django, python and pyQuil. It comes back with a general outline of how to proceed usually in a text or conversational form if you don't request code examples. It has written a Django app for me after requesting a code example. How can I make use of its code writing ability more effectively? I also want to build it into a code writing app which I have yet to design. This question is my attempt to earn a silver badge on StackOverflow.com . I have yet to fully investigate other people's work regarding getting the chat-bot to write useful code. The bot does have limitations, it has been trained on data ending in late 2021 and can't execute a single line of code itself, not even to show the results of example code it has just written, when provided with input data. It can tell you how to write most code, but usually comes up with something simple and somewhat incomplete. In the Django code app question it didn't write models.py until prompted. It didn't include a … -
Django change field value in queryset
#models.py class Product(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000) discount = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0.0000) is_discount = models.BooleanField(default=False) #views.py def page(request): product = Product.objects.get(pk=1) I have main product price, sometime I need to enable discount price, so if I enabled it in "is_discount" and when I make product instance at result I need to get by product.price the value from "discount". I understand that I can make it with price = product.price if product.is_discount: price = product.discount but this solution is not good for me. -
DRF Serialize prefetch_related query set
DRF Serialize prefetch_related query set Help in how to read the data, below is what I am doing. serializer.py class CustomerSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) phonebook = PhonebookSerializer() phonenumbers_set = PhonenumbersSerializer(many=True) customerdisposition_set = CustomerDispositionSerializer(many=True) class Meta: model = Customers fields = '__all__' queryset queryset = Customers.objects.select_related('user', 'phonebook').prefetch_related('phonebook__phonenumbers_set', 'customerdisposition_set').all() queryset.filter(value=value).first() {'status': u't', 'phonebook_id': 1L, 'modified_dt': datetime.datetime(2022, 2, 24, 5, 57, 38, tzinfo=), 'user_id': 1L, 'followup_dt': None, 'notes': None, '_state': <django.db.models.base.ModelState object at 0x12f6eae08>, 'refid': None, 'source': None, '_user_cache': <User: test>, 'agent_id': None, '_prefetched_objects_cache': {u'customerdisposition_set': []}, '_phonebook_cache': <Phonebook: 6,ree>, 'id': 9L, 'created_dt': datetime.datetime(2022, 3, 4, 6, 28, 58, 125834, tzinfo=)} Error AttributeError: Got AttributeError when attempting to get a value for field phonenumbers_set on serializer CustomerSerializer. -
Deploy Django project in railway
I try to move my project from HEROKU to RAILWAY, but i got this error When try to start a new project i get the same error Using Nixpacks context: 0fc4691a3fee078c9c01afe01d008723 Nixpacks build failed Error: Error reading runtime.txt Caused by: stream did not contain valid UTF-8 I tried to redo the project from the beginning, but nothings change -
Why django-rest-framework is generating same api url for two views (both views having same queryset)?
My Project Configuration is this. This is realated to Contact Form. Here I have two approach: Customer from frontend can only post (i.e. send message) and admin can only retrieve and list the contacts. Models.py class Contact(models.Model): full_name = models.CharField(max_length=100) email = models.EmailField() phone_no = models.CharField(max_length=10, validators=[validate_phone_no]) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.email serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = [ 'full_name', 'email', 'phone_no', 'message', ] Views.py class ContactViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset = Contact.objects.all() search_fields = [] ordering_fields = [] ordering = [] http_method_names = ["options", "head", "get"] serializer_class = ContactSerializer class CustomerContactViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Contact.objects.all() http_method_names = ['post'] serializer_class = ContactSerializer urls.py router.register("contacts-detail", ContactViewset) router.register("contact-form", CustomerContactViewSet) My question is: Why DRF is generating the same url for both views although I have given different names for both: 'contact-form'----> for posting and 'contact-detail'--------> for listing the contacts Both views are pointing to same Model - Is this the Reason? Click Here to see generated api url See last urls are same: and redirecting to "contact-form". and I know I can give base_name to seperate both. But I wanted to know the mechanism behind generating same url: If … -
Reverse for 'Project' with arguments '('',)' not found. 1 pattern(s) tried: ['Project/(?P<id>[^/]+)/\\Z']
I got this error This the view of my projectThis is the url of my projectThis is the templates of my second view functionThis is the template of my first view functionThis the model of my project I tried to render the the data in my first view linked template but the second template data does not render in my page . I want to render the data of my second template in my first template through url -
What is "django_admin_log" used for in Django Admin?
When adding data: "django_admin_log" is inserted as shown below: And, when changing data: "django_admin_log" is inserted as shown below: And, when clicking Delete on Change page: Then, clicking Yes, I'm sure to delete data: "django_admin_log" is inserted as shown below: So, what is "django_admin_log" used for in Django Admin? -
Django - How to filter form field many to many after search result
I currently have a sports many to many field that contains multiple sports such as Tennis, Football, Rugby etc. What i am trying to do is pass a search result to the form which will filter and update the sports field and then redisplay the field with only the search result. So if i search for "Tennis" the sports field should only display "Tennis" and not a list of other sports field. However, i cannot figure out how to do this. I have tried using a post function in the class based view which filters sports field (it works) but i cannot pass this back to the form where it can update the filtered sports field. I currently return the filtered result (which i believe is wrong) and i get the error "too many values to unpack (expected 2)" I have also tried removing the post function from the class based view and placing the post function in the the form class and that also does not work as it just updates the form. Here are my models: class SportsTag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class ProfileUser(AbstractUser): ... sports = models.ManyToManyField(SportsTag, blank=True) Here is the code for … -
Add Django pytest test database migrations only for tests
I am looking for a decent solution for any migrations in database itself. We have custom SQL script which adds pg_trgm extention to PostgreSQL database, which is simply CREATE EXTENSION pg_trgm; and FROM postgres:14.5-alpine COPY init.sql /docker-entrypoint-initdb.d/init.sql in database`s Dockerfile After that I can easily add specialized GIN indexes to models, i.e. class MyModel(models.Model): """ My model comment """ objects = MyManager() field = models.CharField(max_length=100) class Meta: indexes = ( models.Index(Upper("field"), name="field_idx"), GinIndex( fields=["field"], opclasses=["gin_trgm_ops"], name="field_gin_idx", ), GinIndex( OpClass(Upper("field"), name="gin_trgm_ops"), name="field_gin_idx", ), So I want to reflect that "custom script" in Django pytest tests. P.S.: I know there is a trigram extention for that purpose, but it was a TL decision to put custom database migration in separate place Do you have any idea on how to prepare such fixture? I was looking for related pytest fixtures but haven't found any solution -
How to use a Regex pattern in a Django form field widget attribute using JQuery
I'm using JQuery Mask Plugin in a Django form to specify input masks. I'm able to specify simple masks like the following simple mask which works: cost = forms.DecimalField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"00.00"}') My problem is specifying regex patterns; I don't know how to pass the pattern to the 'data-hs-mask-options'. See the example below. How can I pass the translation dictionary to the 'data-hs-mask-options'? ip_address = forms.CharField(widget = forms.TextInput(attrs={'class':'js-input-mask form-control', 'data-hs-mask-options':'{"mask":"0ZZ.0ZZ.0ZZ.0ZZ"}') ('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', { translation: { 'Z': { pattern: /[0-9]/, optional: true } } }) -
Django/Python - I don't use my django admin page to Add information my site because the admin field is empty
I'm not sure what happened but for the first time ever, i'm unable to use my admin fields. The fields are empty, and i can't use the models i can created on Django. I tried creating a new project but still no luck and i don't know how to resolve this. My Models.py is from django.db import models # Create your models here. class PersonModel(models.Model): Gender = { ('Male','Male'), ('Female','Female'), } Adult = { ('Non-Adult','Non-Adult'), ('Adult','Adult'), } Date = models.DateTimeField(auto_now_add=True), Name = models.CharField(max_length=50, blank=True, null=True), Surname = models.CharField(max_length=50, blank=True, null=True), The_gender = models.CharField(max_length=10, blank=True, null=True), The_Adult = models.CharField(max_length=10, blank=True, null=True), def __str__(self): return self.Name my admin.py is from django.contrib import admin from . models import PersonModel # Register your models here. admin.site.register(PersonModel) views.py from django.shortcuts import render from . models import PersonModel # Create your views here. def Home(request): Persons = PersonModel.objects.all() return render(request, 'Practice_2_app/Home.html', {'Persons':Persons}) def The_form(request): return render(request, 'Practice_2_app/The_form.html', {}) -
How can i print number of days between of each products expiry date and today date in a template //django view and html template
I have model called product in which i have expiry date as DateFiled, i need to calculate number of days left for expiry for all the products and display the product name and number of days left for expiry of every products from product table. class Product(models.Model): category = models.ForeignKey('store.Category',on_delete=models.CASCADE,default='SYRUP') itemname = models.CharField(max_length=50,blank=True,null=True) itemexpdate = models.DateField(auto_now_add=False, auto_now=False,blank=True,null=True) class Category(models.Model): name = models.CharField(max_length=200,blank=True) def days_left_for_expiry(expiry_date): today = date.today() expiry = expiry_date delta = expiry - today return str(delta.days) def home(request): d = Product.objects.all() for product in d: expiry_date = product.itemexpdate days_left= days_left_for_expiry(expiry_date) return render(request,'store/dashboard.html',{'days_left':days_left}) {% for i in d %} <tr> <td>{{ i.itemname }}</td> <td>{{ i.itemexpdate }}</td> <td><b>{{days_left}}</b></td> </tr> {% endfor %} output: image attached -
post action drops part of the url in django app
I'm building my first ecommerce app, while attempting to gain more skills in Django. I have a form problem, where I am either adding a product, or editing one, using the same Template. My problem is where the action call drops part of the url when submitting POST back to the server ( right now, it's just the python manage.py runserver). When I go to edit, I see the url: http://127.0.0.1:8000/mystore/edit-product/4 When I edit the product and click submit, I get the Request URL: http://127.0.0.1:8000/mystore/edit-product/ page not found error. and I don't make it back to the server to determine anything else. It looks like I'm missing something. this is what I have url.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('signup/', views.signup, name='signup'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('login/', auth_views.LoginView.as_view(template_name='userprofile/login.html'), name='login'), path('myaccount/', views.myaccount, name='myaccount'), path('mystore/', views.my_store, name='my_store'), path('mystore/add-product/', views.add_product, name='add-product'), path('mystore/edit-product/<int:pk>', views.edit_product, name='edit-product'), path('vendors/<int:pk>/', views.vendor_detail, name='vendor_detail') ] Views @login_required def add_product(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): title = request.POST.get('title') slug = slugify(title) product = form.save(commit=False) product.user = request.user product.slug = slug product.save() return redirect('my_store') else: form = ProductForm() return render(request, 'userprofile/add-product.html', { 'title': 'Add Product', 'form':form … -
Django - Password Reset Page Not Found (404)
i try to add password reset function to my app but i get error at final step. It says: Here is the error screenshot: It says: “C:\Users\yusuf\Desktop\Klasörler\Marmara Üniversitesi Bilgisayar Programcılığı\3. Güz 2022-23\İnternet Programlama I (BLY2005)\360121065-main\yusuferselbal templatemo_526_vanilla\mytemplate\account\password_reset_confirm\MTM\set-password” does not exist This is my urls.py: path('password_reset/', authViews.PasswordResetView.as_view( template_name = 'account/user/password_reset_form.html', success_url = 'password_reset_email_confirm', email_template_name = 'account/user/password_reset_email.html', form_class = PwdResetForm), name = 'pwdreset'), path('password_reset_confirm/<uidb64>/<token>', authViews.PasswordResetConfirmView.as_view( template_name = 'account/user/password_reset_confirm.html', success_url = '/account/password_reset_complete/', form_class = PwdResetConfirmForm), name = 'password_reset_confirm'), path('password_reset/password_reset_email_confirm', TemplateView.as_view( template_name = 'account/user/reset_status.html', ), name = 'password_reset_done'), path('password_reset_complete/', TemplateView.as_view( template_name = 'account/user/reset_status.html', ), name = 'password_reset_complete'), This is my password_reset_confirm.html template: {% load i18n %}{% autoescape off %} {% blocktranslate %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktranslate %} {% translate "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'account:password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% translate 'Your username, in case you’ve forgotten:' %} {{ user.get_username }} {% translate "Thanks for using our site!" %} {% blocktranslate %}The {{ site_name }} team{% endblocktranslate %} {% endautoescape %} -
Django FileField saving empty file to database
I have a view that should generate a temporary JSON file and save this TempFile to the database. The content to this file, a dictionary named assets, is created using DRF using serializers. This file should be written to the database in a model called CollectionSnapshot. class CollectionSnapshotCreate(generics.CreateAPIView): permission_classes = [MemberPermission, ] def create(self, request, *args, **kwargs): collection = get_collection(request.data['collection_id']) items = Item.objects.filter(collection=collection) assets = { "collection": CollectionSerializer(collection, many=False).data, "items": ItemSerializer(items, many=True).data, } fp = tempfile.TemporaryFile(mode="w+") json.dump(assets, fp) fp.flush() CollectionSnapshot.objects.create( final=False, created_by=request.user, collection_id=collection.id, file=ContentFile(fp.read(), name="assets.json") ) fp.close() return JsonResponse({}, status=200) Printing assets returns the dictionary correctly. So I am getting the dictionary normally. Following the solution below I do get the file saved to the db, but without any content: copy file from one model to another Seems that json.dump(assets, fp) is failing silently, or I am missing something to actually save the content to the temp file prior to sending it to the database. The question is: why is the files in the db empty?