Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hello i need to create a auto increment invoice number
I need to create an auto increasing invoice number starting from 000001 and going up ex.000001, 000002, 000003 and so on right now i have this code that i took from another stack overflow question but i dont want the MAG part def increment_invoice_number(self): last_invoice = Transaction.objects.all().order_by('id').last() if not last_invoice: return 'MAG0001' invoice_no = last_invoice.invoice_no invoice_int = int(invoice_no.split('MAG')[-1]) new_invoice_int = invoice_int + 1 new_invoice_no = 'MAG' + str(new_invoice_int) return new_invoice_no invoice_no = models.CharField(max_length=500, default=increment_invoice_number, null=True, blank=True) i want my invoice num to start with 000001 -
How can I query a Postgres DateRange with a single date?
I am using django.contrib.postgres.field.DateRangeField as described [here][1]. class MyModel(models.Model): date_range = DateRangeField() How to I query this model to return all date_range with a lower bound greater than today? I tried: today = datetime.date.today() MyModel.objects.filter(date_range__gt=today) But this results in operator does not exist: daterange > date. -
djoser override reset password email with template
I am using the Django rest framework and Djoser for Authentication and User Registration. I completed the part of activation by template. But now the issue is I want to use html template on rest password. I created html form page to submit form of reset password. when I click on submit it not taking new password and reset password on post method. giving me error on that. Code is running on postmen but getting error when I submit it through html template Here is my djoser settings.py DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'EMAIL': { 'activation': 'user_profile.email.ActivationEmail', 'confirmation':'user_profile.email.ConfirmationEmail', 'password_reset':'user_profile.email.PasswordResetEmail', 'password_changed_confirmation':'user_profile.email.PasswordChangedConfirmationEmail' }, 'SERIALIZERS': { 'user_create': 'user_profile.serializer.UserSerializer', 'user': 'user_profile.serializer.UserSerializer', } } views.py class ResetPasswordView(View): def get (self, request, uid, token): return render(request, 'reset_password.html') def post (self, request,uid,token): new_password=requests.post.get("new_password") re_new_password=requests.post.get("re_new_password") payload = json.dump({'uid': uid, 'token': token, 'new_password': new_password, 're_new_password': re_new_password}) protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() + '/' password_reset_url = "users/reset_password_confirm/" # url used for activate user password_post_url = web_url + AUTHENTICATION_BASE_ROUTE + password_reset_url response = requests.post(password_post_url,data=payload) return HttpResponse(response.text) urls.py re_path(r'^password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', ResetPasswordView.as_view()), reset_password.html <form action="" method="post"> {% … -
How to fix this error module 'django.http.request' has no attribute 'META'?
I'm trying to get the visitor's IP address in my django project, here's the code I followed. from django.contrib.gis.geoip2 import GeoIP2 def add(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip g = GeoIP2() ip = add (request) location = g.city(ip) longitude = location["longitude"] latitude = location["latitude"] user_location = Point(longitude, latitude, srid=4326) When I run the server I get the following error and I don't know why module 'django.http.request' has no attribute 'META' -
Django UserCreationForm not responding when button clicked with input in fields
I'm having trouble getting my register application in Django to work. I am using the built-in UserCreationForm form. I can go to the URL and the form shows up but when I put info into the fields and click the submit button nothing happens. It should pop up an error screen saying "missing the csrf_field" (I know this because I'm following TechWithTim's tutorial and that's what happens to him). But when I click the "Register" button nothing happens. views.py: from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm # Create your views here. def register(response): form = UserCreationForm() return render(response, "register/register.html", {"form":form}) register.html: {% extends "main/base.html" %} {% block title %}Create an Account{% endblock %} {% block content %} <form method="POST" class="form-group"> {{form}} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} urls.py: from django.contrib import admin from django.urls import path, include from register import views as v urlpatterns = [ path('', include("main.urls")), path("register/", v.register, name="register"), path('admin/', admin.site.urls), ] I added the application to my settings.py file as well. This is my first question on here and I tried to format it properly so sorry if I didn't -
Django - Sending Email and Base64 images, URL's are broken on Gmail
I am trying to send Emails using Django EmailMultiAlternatives() msg = EmailMultiAlternatives(subject, '', from_email, [to]) # Email details msg.attach_alternative(html_content, "text/html") # Email Content + Type msg.send() # SEND! On the receiving end i.e Gmail, image URLs are broken and I have tried using Base64 in my src as well, they still appear broken. I have used this for reference : Base64 images to gmail But there seems to be to no conclusive answer on how this should be implemented apart from attaching them in the email. -
cors policy error : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin
I have installed django-cors-headers and this is settings.py : ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS","").split() MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and also : CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True but i got this error in chrome consloe: Access to XMLHttpRequest at 'https://event-alpha.mizbans.com/api/meetings/?memory=0' from origin 'https://alpha.mizbans.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
nslookup hostname in csv file and write ip address in another csv file in django
I want to perform ns-lookup on multiple hostnames given in .csv file and save IP address in another csv file in django using python. i am having a problem creating upload.py index.html <form enctype = "multipart/form-data" action = "upload.py" method = "post"> {% csrf_token %} <p><input type = "file" name = "myFile" /></p> <p><input type = "submit" value = "Upload" /></p> </form> views.py from django.shortcuts import render import dns import dns.resolver def index(request): if request.method == 'POST': search = request.POST.get('search') ip_address = dns.resolver.Resolver() IPv4 = ip_address.resolve(search, 'A').rrset[0].to_text() IPv6 = ip_address.resolve(search, 'AAAA').rrset[0].to_text() return render(request, 'index.html', {"ipv4": IPv4, "ipv6": IPv6, "hostname": search}) else: return render(request, 'index.html') -
Django: UniqueConstraint validator does work neither for model nor for intermediate model
My project is basically a platform, where one can post one's recipes with tags (for example, breakfast or dinner) and ingredients (carrot, milk, etc.). I would want to implement unique constraint for recipe, so that user could not create one with, say, two identical tags or ingredients. So, I have decided to use django UniqueConstraint validator for that, but even migrations did not apply, django says: "No changed were detected". from django.db import models from django.contrib.auth import get_user_model from django.core.validators import MinValueValidator, MaxValueValidator User = get_user_model() class Recipe(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='recipes', verbose_name='автор', ) name = models.CharField( max_length=200, verbose_name='имя', ) image = models.ImageField( max_length=4096, upload_to='images/%Y-%m-%d', verbose_name='фото', ) text = models.TextField(verbose_name='описание') ingredients = models.ManyToManyField( 'Ingredient', through='RecipeIngredient', verbose_name='ингредиет', ) tags = models.ManyToManyField( 'Tag', through='RecipeTag', verbose_name='тэг', ) cooking_time = models.IntegerField( default=60, validators=( MinValueValidator(1), MaxValueValidator(44640) ), verbose_name='время приготовления (в минутах)', ) creation_date = models.DateTimeField( auto_now=True, verbose_name='дата создания рецепта', ) class Meta: verbose_name = 'рецепт' verbose_name_plural = 'рецепты' def __str__(self): return f'Рецепт - id: {self.id}, имя: {self.name}.' class Tag(models.Model): name = models.CharField( max_length=256, verbose_name='имя', ) color = models.CharField( max_length=64, verbose_name='цвет', ) slug = models.SlugField( max_length=64, verbose_name='слаг', ) class Meta: verbose_name = 'тэг' verbose_name_plural = 'тэги' def __str__(self): return f'Тэг - id: {self.id}, имя: … -
DjnagoBecause its MIME type ('text/html') is not a supported stylesheet
Someone could help, trying for weeks to figure out how to find the normal path. But it doesn't work. Script: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") Image:It loads in the wrong way,PathError code -
how to get filter data between two dates in django
I am working on Django project How to get filter data between two dates I mean (from-date and to-date) mfdate is a foreign key and coming from another model. how can I do this can anyone help me to solve this problem I have tried multiple time but it is not working here is my Code models.py class ManufacturingYM(models.Model): ManufacturingYMID = models.AutoField(primary_key=True) ManufacturingDate = models.DateField(auto_now_add=False, blank= True,null=True) def __str__(self): return str(self.ManufacturingDate) class Car(models.Model): CarID = models.AutoField(primary_key=True) CarName = models.CharField(max_length=500, blank=True, null=True, verbose_name="Car Name") mfdate = models.ForeignKey(ManufacturingYM, blank= True,null=True, on_delete=models.DO_NOTHING, verbose_name="Manufacturing Date") def __str__(self): return self.CarName views.py def searchdd(request): carForm = Car.objects.all() fromdate = str(request.POST.get('from_date')) todate = str(request.POST.get('to_date')) if fromdate: carForm= Car.objects.filter(mfdate=fromdate) if todate: carForm= Car.objects.filter(mfdate=todate) context = {'carForm':carForm} return render(request, 'app/searchdd.html', context) home.html <form method="post" id="indexForm" action="/searchdd" data-cars-url="{% url 'ajax_load_cars' %}"> {% csrf_token %} <div class="col-md-12"> <div class="row"> <div class="col-md-3"> <label for="" class="white">From Year</label> <select name="from_date" id="fromdate" class="dp-list"> <option disabled selected="true" value="">--select Year--</option> {% for mfd in manfd %} <option value="{{car.CarID}}">{{mfd.ManufacturingDate|date:'Y'}}</option> {% endfor %} </select> </div> <div class="col-md-3"> <label for="" class="white">To Year</label> <select name="to_date" id="todate" class="dp-list"> <option disabled selected="true" value="">--select Year--</option> {% for mfd in manfd %} <option value="{{car.CarID}}">{{mfd.ManufacturingDate|date:'Y'}}</option> {% endfor %} </select> </div> </div> </div> -
How to link a file from static folder/subfolder in django
I have a file about.html file in static folder. I want to see that file content when I put URL in browser like 127.0.0.1/about here is my code: in project url I wrote: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('about/' , include('app.urls')), ] in app url : from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path("about", views.about, name='about') ] in views.py file: from django.http.response import HttpResponse from django.shortcuts import render def about(request): return render (request, "static /about.html") but this return me a error when i put url 127.0.0.1:8000/about Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about/ Using the URLconf defined in project1.urls, Django tried these URL patterns, in this order: admin/ [name='index'] about [name='about'] contact [name='contact'] portfolio [name='portfolio'] about/ portfolio/ contact/ The current path, about/, 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. help me plz -
How to prefetch related with three model django
THIS IS MY FIRST MODEL: class CSSIGroup(models.Model): GroupName = models.CharField(max_length=250) EnteredBy = models.CharField(max_length=250) UpdateBy = models.CharField(max_length=250,null=True) EntryDateTime = models.DateTimeField(auto_now_add=True) def __str__(self): return self.GroupName This IS MY SECOND MODEL: class CSSIList(models.Model): CSSIGroup = models.ForeignKey(CSSIGroup,null=False, on_delete=models.RESTRICT) CSSIName = models.CharField(max_length=250) FatherName = models.CharField(max_length=250,null=True) MotherName = models.CharField(max_length=250,null=True) BloodGroup = models.ForeignKey(Setup_Master.BloodGroupList, null=True, on_delete=models.SET_NULL) BirthDate = models.DateTimeField(null=True) ReligionStatus = models.ForeignKey(Setup_Master.ReligionList, null=True, on_delete=models.SET_NULL) Sex = models.ForeignKey(Setup_Master.GenderList, null=True, on_delete=models.SET_NULL) MeritStatus = models.ForeignKey(Setup_Master.MaritalStatus, null=True, on_delete=models.SET_NULL) THIS IS MY THIRD MODEL: class Challan(models.Model): Branch = models.ForeignKey(Setup_Master.CompanyBranchList, null=True, on_delete=models.RESTRICT) CustomerID = models.ForeignKey(CSGL.CSSIList, related_name='CustomerWiseChallan', null=False, on_delete=models.RESTRICT) RefNo = models.CharField(max_length=250,null=True) Remarks = models.CharField(max_length=250, null=True) OrderReceiveID = models.CharField(max_length=250, null=True) Narration = models.CharField(max_length=250, null=True) MPOID = models.ForeignKey(CSGL.CSSIList, related_name='ChallanMPO', null=True, on_delete=models.RESTRICT) ChallanDate = models.DateField(null=True) EnterdBy = models.CharField(max_length=250, null=True) EntryTime = models.DateTimeField(auto_now_add=True) EntryDate = models.DateTimeField(auto_now_add=True) ApprovedBy = models.CharField(max_length=250, null=True) Approved = models.CharField(max_length=10, null=True, default='NO') ApprovedDate = models.DateField(null=True) Status = models.CharField(max_length=250, null=True, default='NO') I want to select the first table with the second table-related row and the second table with the select third table-related row. Here is my current query but I don't know how can I add more one prefetch related. Please anybody help me. ChallanList = CSSIGroup.objects.raw("SELECT DISTINCT cssi_cssigroup.id FROM cssi_cssigroup INNER JOIN cssi_cssilist ON cssi_cssilist.CSSIGroup_id = cssi_cssigroup.id INNER JOIN business_challan on business_challan.CustomerID_id = cssi_cssilist.id WHERE … -
Django REST BasicAuthentication is not applied as default authentication class
I have a django REST project and I added REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', ] } to setting.py and I expect BasicAuthentication is applied to all pages as default but still it does not require any authentication to display the content. that is weird. Do I have to do something I did not do? urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('blog_app.api.urls')), path('api-auth/', include('rest_framework.urls')) ] setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'blog_app', ] blog_app/api/urls: urlpatterns = [ path('articles/', ArticleListView.as_view()), ] views.py: class ArticleListView(generics.ListCreateAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer -
I don't understand how the ".year:" works in "datetime.datetime.today().year" line of code
So I am trying to learn Django and came across the following piece of code: datetime.date.today().year I understand it so far as - from the DateTime module, create an instance of the date class using the today method. But I don't understand how the .year portion of the code grabs the year. Is it because the today() method of the date class returns a new object with a year? -
Python Django Error during template rendering
let me quickly explain what am I trying to do. So I am making a small Django based Conference Management, where there can be multiple conferences, a single conference can have multiple talks and each talk will have a certain number of Speakers and Participants. I am able to list the conferences and give the option to delete and edit a conference. Problem: I want an option where I click on a conference and it shows a list of talks for that conference. but when I click on the conference it shows the following error. NoReverseMatch at /Big Data/talks/ Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$'] Request Method: GET Request URL: http://127.0.0.1:8000/Big%20Data/talks/ Django Version: 3.2.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$'] Exception Location: E:\python\PYTHON and GIT\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: E:\python\PYTHON and GIT\python.exe Python Version: 3.9.1 Python Path: ['D:\\DjangoConferenceManagementSystem\\mysite', 'E:\\python\\PYTHON and GIT\\python39.zip', 'E:\\python\\PYTHON and GIT\\DLLs', 'E:\\python\\PYTHON and GIT\\lib', 'E:\\python\\PYTHON and GIT', 'C:\\Users\\AKS\\AppData\\Roaming\\Python\\Python39\\site-packages', 'E:\\python\\PYTHON and GIT\\lib\\site-packages', 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\pip-21.0.1-py3.9.egg', 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32', 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32\\lib', 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\Pythonwin'] Server time: Sun, 03 Oct 2021 15:47:10 +0000 I have included the following code to … -
Django Error migrating db from SQLite to Postgres
I am new to Django. I developed a site locally with SQLite and I am getting an error while attempting to migrate to Postgres for production. The error is File "/Users/______/Desktop/______/accounts/models.py", line 46, in user_addgroup_handler name=(instance.business_location_county.name + ' ' + instance.business_location_state.name), forum_id=instance.business_location_county.id) AttributeError: Problem installing fixture '/Users/_____/Desktop/_______/data1.json': 'NoneType' object has no attribute 'name' The relevant model is: if created: new_group, created = Group.objects.get_or_create( name=(instance.business_location_county.name + ' ' + instance.business_location_state.name), forum_id=instance.business_location_county.id) To create the dump file I ran: python manage.py dumpdata --natural-foreign --naturalprimary -e contentypes -e auth.Permission --indent 2 > data1.json Any ideas about what is causing this error and how to fix it? -
How to edit the default template for DateRangeField
I am using django.contrib.postgres.field.DateRangeField as described here. class MyModel(models.Model): date_range = DateRangeField() I am rendering this in a template: {% with field = form.date_range %} {{ field.label }} {{ field }} {% endwith %} However, this outputs 2 inputs together with no context. E.g.: How can I edit the default template for the widget, to add "sub" labels for "start time" and "end time". E.g: There does not appear to be anything I can find in the docs. -
Aggregate Sum in Django. Sum of objects with the same name
I have the following QuerySet, this is a shopping list: <QuerySet [ <Cart_object: {name: 'Apple', amount: 10}, {name: 'Bananas', amount: 20}, <Cart_object: {name: 'Bananas', amount: 10}> ] > I apply the following code to it, and I get the sum of all products for each of the objects: for obj in cart: from_cart = UserProduct.objects.filter(obj=obj).aggregate(Sum('amount')) print(from_cart) Out: {'amount__sum': 30} {'amount__sum': 10} The question is as follows. How to use aggregate (Sum ('amount')) to add only those objects that have the same 'name'. To get one Cart_object, in which 'Apple' = 10, and 'Bananas' = 30 (Since there are records with the same name) <Cart_object: {name: 'Apple', amount: 10}, {name: 'Bananas', amount: 30}> -
Django session in different host
can someone help me explain about session ? I'm currently making a project involved in Django and Spotify api. In the first version, I made it with django and react in same localhost, when user login, react send request to django endpoint called get-url then redirect to spotify api which then provide a response to another django endpoint called redirect The second version, I also made it with django and react but with different host (localhost:3000 and 127.xxx something), the spotify auth also work the same as above. But in the first version the session_key are always the same, in the second version the session_key in get-url and redirect endponts are different. I read about session, but there's spotify api in middle, not sure what it'll do to the session_key, I hope someone can explain why it session_keys are different in 2 cases, thanks a lot same host pic different host pic -
Manual Post Save Signal creation makes the application slow, Django
We have a Django application that uses Django-river for workflow management. For performance improvement, we had to use the bulk_create for performance improvement. We need to insert data into a couple of tables and several rows in each. Initially, we were using the normal .save() method and the workflow was working as expected (as the post save signals were creating properly). But once we moved to the bulk_create, the performance was improved from minutes to seconds. But the Django_river stopped working ad there was no default post save signals. We had to implement the signals based on the documentation available. class CustomManager(models.Manager): def bulk_create(items,....): super().bulk_create(...) for i in items: [......] # code to send signal And class Task(models.Model): objects = CustomManager() .... This made the workflow working again, but the generation of signals is taking time and this destroys all the performance improvement gained with the bulk_create. So is there a way to improve the signal creation? -
The view ... didn't return an HttpResponse object. It returned None instead - django
I tried several ways to solve the problem but I couldn't .. every time I got it error. Item added to DB but error message returned on page. why "get_absolute_url" and "success_url" do not work? View class AddItemView(CreateView): model = Add_Item form_class = AddItemForm template_name ='add_item.html' success_url = reverse_lazy("home") def form_valid(self, form): self.object = form.save(commit=False) # Add_Item.User = User self.object.user = self.request.user self.object.save() Models class Add_Item(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=None, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=255 , choices=all_categories) description = RichTextField(blank=True,null=True) condition = models.CharField(max_length=100, choices=cond) city = models.CharField(max_length=50, choices=cy.city, blank=True) street = models.CharField(max_length=100, blank=True) home_number = models.CharField(max_length=100, blank=True) header_img = models.ImageField(null=True, blank=True, upload_to='img/') more_img = models.ImageField(null=True, blank=True, upload_to='img/') Pub_date = models.DateField(auto_now_add=True) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('home') -
How about to start making a online classroom website in python?
One of My friend lost his tuition job due to Covid. I want to help and make him a online classroom where he can teach atleast 50-60 students online. But I am from sysadmin background. I have limited exeperience with python as I use it for generating configuration files and automate regular task. I have made a personal blog in django and used some flask. Beyond that I have not worked extensively on development that why i want to as this noob question as from where I can start. I Know i have to spent some 3-4 month to learn just technologies. I am ready for it. If anyone worked on such system please point me to suitable framework, libraries suitably in python and front end technology like JS and system design complexity in this. Any response is greatly appreciated. Thanks -
Django serialise nested object into json
I have two models: modesl.py class ForumSection(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=300) order = models.IntegerField(default=0) def __str__(self): return self.title class ForumSubSection(models.Model): section = models.ForeignKey(ForumSection, on_delete=models.CASCADE) title = models.CharField(max_length=20) description = models.CharField(max_length=300) order = models.IntegerField(default=0) def __str__(self): return self.title I try to serialize subsections to json and return to frontend: def ajax_create_forum_subsection(request): ....... sections = ForumSubSection.objects.all().order_by('pk') data = serialize("json", sections, fields=('pk', 'title', 'description', 'order', 'section')) return JsonResponse(data, safe=False) But ``section``` return primary key (ID of record). I'm readed 100500 questions on SA, some peoples say to write custom serializers. ok, I'm write it. serializers.py from rest_framework import serializers from .models import * class ForumSectionSerializer(serializers.ModelSerializer): class Meta: model = ForumSection fields = '__all__' def create(validated_data): return ForumSection.objects.create(**validated_data) class ForumSubSectionSerializer(serializers.ModelSerializer): section = ForumSectionSerializer(read_only=True) class Meta: model = ForumSubSection fields = ['pk', 'title', 'description', 'order', 'section'] depth = 1 def create(validated_data): return ForumSubSection.objects.create(**validated_data) And try to use it. def ajax_edit_forum_subsection(request): ....... qs = ForumSubSection.objects.all().order_by('pk') ser = ForumSubSectionSerializer(qs) data = ser.serialize("json", qs, fields=('pk', 'title', 'description', 'order', 'section')) return JsonResponse(data, safe=False) It call Server error 500 and not work. Now is 5'th day of this problem and I write here to ask help. How to serialize ForumSubSection objects with ForumSection objects? -
Is there way to edit file's header or something to store encryption key for software project
the project is responsible of encrypting and decrypting books, which will give the facility solution for copyright infringement by uploading the books to secure platforms ,Each copy of the book has its unique encryption key stored in book's file for if the book is leaked in future , we find who was responsible for that .