Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
two upload file next to each other with texarea with bootstrap
I hava a django application. And I have two file upload boxes. And two textarea's. So I have it like this: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <link rel="stylesheet" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container"> <div class="inline-div"> <form action="/controlepunt140" method="POST" type="file" class="form-control form-control-lg" enctype="multipart/form-data" > <!-- <input type="file" id="img" name="img" accept=".pdf, .xlsx"> --> {% csrf_token %} {{ form }} <input type="submit" type="file" value="Verstuur" accept="application/pdf" /> </form> <textarea class="inline-txtarea" name="" id="" cols="70" rows="10"> {{content_pdf}}</textarea > </div> <div class="inline-div"> <form action="/controlepunt140" method="POST" type="file" class="form-control form-control-lg" enctype="multipart/form-data" > <!-- <input type="file" id="img" name="img" accept=".pdf, .xlsx"> --> {% csrf_token %} {{ form }} <input class="form-control" type="submit" type="file" value="Verstuur" accept="application/pdf" /> </form> <textarea class="inline-txtarea" name="" id="" cols="70" rows="10"> {{content_pdf}}</textarea > </div> </div> </body> </html> {% endblock content %} and css: .inline-div { display: inline-block; } .inline-txtarea { resize: none; border: 2px solid orange; height: 125px; } And in the fiddle looks like this: https://jsfiddle.net/SavantKing/nvuy92z5/ But in fiddle there is a button verstuur. So that is correct. But in the application the button … -
Nextcloud and Django (static) website aside behind nginx-proxy issue
First of all, i'm a beginner in networking and with web services in general. Context : i've a domain name : mydomain.com and a VPS server (with Ubuntu) with a fixed IPV4 adress : MYIPADRESS. In my VPS provider control panel , i've binded mydomain.com to MYVPSIPADRESS with an entry A. Only one domain is binded to MYIPADRESS. Objective : I want to host two webservices on my VPS : a nextcloud instance and my blog that is a Django static website, all set up with HTTPS. I want that my nextcloud instance points to cloud.mydomain.com and my blog Django instance to blog.mydomain.com. To do so, i'm using docker. Basically, i'm using the nginx-proxy server + its letsencrypt companion. Once done, i run my docker container for my django blog with env variables according to nginx-proxy documentation and put my blog container in the same network as nginx-proxy and its letsencrypt companion networks. At each time, without detaching my images , logs do not show me any warnings/"exited with 1"/red-written rows stuffs whether with blog container or nginx-proxy/letsencrypt companion container. I did not try to put my nextcloud instance so far since just my blog container setup does not work. … -
get error when want POST something to api{detail: "CSRF Failed: CSRF token missing."}
when i want to POST some thing to API , i get this error : CSRF TOKEN , but i don't have CSRF Token in django , i want POST without CSRF token i can POST with Postman but when i want post it by js , i get error that i said in first how can i do? let edit_data = { user_id: "1", company: "rahaaaa", description: "12343234234", first_name: "324234234234312sd", id_number: "122222", last_name: "32423dqwe32", } let c = JSON.stringify(edit_data) console.log(c); fetch("http://127.0.0.1:8000/api/postCustomer/", { headers: { "Content-Type": "application/json", }, method: "POST", body:c, }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.log(err)); when i want to POST some thing to API , i get this error : CSRF TOKEN , but i don't have CSRF Token in django , i want POST without CSRF token how can i do? -
Django Rest Framework viewset mypy error: Missing positional argument
Here is a problem, when testing method from drf viewsets with @action() decorator, mypy gives error expecting additional argument (which is self param). Here it is: # views.py class UserViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "username" def get_queryset(self, *args, **kwargs): assert isinstance(self.request.user.id, int) return self.queryset.filter(id=self.request.user.id) @action(detail=False) def me(self, request: WSGIRequest): serializer = UserSerializer(request.user, context={"request": request}) return Response(status=status.HTTP_200_OK, data=serializer.data) # test_views.py def test_me(self, user: User, rf: RequestFactory): view = UserViewSet() request = Request(rf.get("/fake-url/")) request.user = user view.request = request response = view.me(request) # The problem is here assert response.data == { "username": user.username, "name": user.name, "url": f"http://testserver/api/users/{user.username}/", } and the log is: drf_project\users\tests\test_drf_views.py:25: error: Missing positional argument "request" in call to "me" of "UserViewSet" drf_project\users\tests\test_drf_views.py:25: note: "__call__" is considered instance variable, to make it class variable use ClassVar[...] drf_project\users\tests\test_drf_views.py:25: error: Argument 1 to "me" of "UserViewSet" has incompatible type "Request"; expected "UserViewSet" How can I solve this except ignoring it with type: ignore[]? The probem is that @action decorator in viewset changes the type of method, without it mypy is okay. However @action() ruins it. I need to overcome this, any suggestions? -
Django 3.0 admin searching for different models fields
I faced with some problems with project which I had now... I have different models with included structure (one category can have multiple subcategories) and I want to implement searching by each field which I had in model... now it looks like this code working only for 1st level categories: from django.contrib import admin from .models import * def register_models(models_list): for model, fields in models_list.items(): model_fields = () for field in model._meta.fields: if field.name in fields: model_fields = (field.name, *model_fields) class Admin(admin.ModelAdmin): list_display = ('__str__', *model_fields) list_filter = model_fields search_fields = [*model_fields] admin.site.register(model, Admin) Question, is it possible somehow to implement searching for my structure with many subcategories? I.E if I am in category2 with many subcategories I want to search in category2 subcategory which contains any field with text test -
Django. Increment views count of object without affecting its updated_at field
I have the following model: class Announcement(models.Model): ... created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views = models.PositiveIntegerField(default=0, editable=False) my view: class AnnouncementDetailView(DetailView): model = Announcement context_object_name = 'announcement' template_name = 'web/index.html' def get(self, *args, **kwargs): announcement = get_object_or_404(Announcement, id=kwargs['id']) announcement.views += 1 announcement.save() return super().get(self, *args, **kwargs) The problems are: I know about the F expression, I'll use it down below, but I want to know another ways of updating field and not updating the updated_at field. I want to save the changes of model's views field but everytime I save it, it sets the new value to updated_at field. It means everytime I refresh the page it shows the current time on updated_at field, which is very bad. I have changed my view's code to: ... def get(self, *args, **kwargs): Announcement.objects.filter(id=kwargs['id']).update(views=F('views') + 1) return super().get(self, *args, **kwargs) Now it works fine but I have several questions. How it saves the new value of views field without calling the save method of """"Django"""""? How far can I go with it. What is the best practices of changing some fields of model without hitting the save method? Thanks in advance for broad explanation! -
use django channel to send camera images but always closed after last a few times
here is my consumers, i want to use django channel to send camera images but always closed after last a few times,dont know why? Could you tell me if it is not set up properly? I use Redis as the channel layer import json from channels.generic.websocket import AsyncWebsocketConsumer class ObjectDetectionConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['v_name'] self.room_group_name = 'ObjectDetection_%s' % self.room_name print(self.room_name) # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): print("receive! ") # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'video_message', 'message': text_data, } ) # Receive message from room group async def video_message(self, event): # print(1) message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) here is the message of the error Exception inside application: Attempt to send on a closed protocol Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\torch113\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\ProgramData\Anaconda3\envs\torch113\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "C:\ProgramData\Anaconda3\envs\torch113\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\ProgramData\Anaconda3\envs\torch113\lib\site-packages\channels\sessions.py", line 263, in __call__ … -
How can i give automatic register number while filling the form (Django)
I made a patient register form and how can i give automatic id while adding new patient.(in my project Aadhar Number ). New id must be last id + 1. How can i do this. Thanks for help. Full project in my github repo address: https://github.com/eseymenler/demo2 -
Unable to get related data from ManyToManyField
I'm trying to fetch related objects from below two models. Following django models with ManyToManyField relationship. Book class Book(models.Model): authors = models.ManyToManyField( to=Author, verbose_name="Authors", related_name="books_author" ) bookshelves = models.ManyToManyField( to=Bookshelf, verbose_name="Bookshelf", related_name="books_shelves" ) copyright = models.NullBooleanField() download_count = models.PositiveIntegerField(blank=True, null=True) book_id = models.PositiveIntegerField(unique=True, null=True) languages = models.ManyToManyField( to=Language, verbose_name=_("Languages"), related_name="books_languages" ) Author class Author(models.Model): birth_year = models.SmallIntegerField(blank=True, null=True) death_year = models.SmallIntegerField(blank=True, null=True) name = models.CharField(max_length=128) def __str__(self): return self.name class Meta: verbose_name = _("Author") verbose_name_plural = _("Author") I have to fetch all the Auhtors with their related books. I have tried a lot of different ways none is working for me. First way : using prefetch_related class AuthorListAPIView(APIErrorsMixin, generics.ListAPIView): serializer_class = AuthorSerializer queryset = Author.objects.exclude(name__isnull=True) def get_queryset(self): auths = queryset.prefetch_related(Prefetch("books_author")) Second way using related_name 'books_auhtor' class AuthorListAPIView(APIErrorsMixin, generics.ListAPIView): serializer_class = AuthorSerializer queryset = Author.objects.exclude(name__isnull=True) def get_queryset(self): auths = queryset.books_author.all() None of the above ways worked for me. I want to prepare a list of Authors and their associated books. For ex:- [{'Author1':['Book1','Book2'],... }] -
How to create wordpress blog with subdomain using cloudflare
I have one Django web application hosted on AWS EC2 and I am using Cloudflare CDN. So I am using Cloudflare Name servers in my Domain provider. I want to create a Worpress blog with a subdomain for my web application like blog.mywebsite.com. I am having another shared hosting that will host a WordPress website. My question is how can I create a WordPress website with a subdomain? But my main domain is using Cloudflare CDN. Thanks -
Add custom file upload icon in tinymce
I have a ready custom file manager with ajax and html, I want to integrate file manager into Tinymce editor I can view the list of images that have been uploaded to the server Now I need is to add image uploader icon and when i click, appear the list and insert image in url input when click on image. This is a illustration image with photoshop -
Django ManyToMany field has automatically all the Users in admin panel
class Course(models.Model): students = models.ManyToManyField(User, verbose_name='Students', null=True, blank=True) I want to add course enrollment to model Course but my manytomanyfield already has all the users and I can't even remove any of them. What should I do? I want "Students" to be a list of users who takes the course. -
I will create a token using know,how delete a token when I logout in Django rest framework
Delete the login token using Knox when logout Knox have built in logout function so I don't know how to delete the login token -
Django 4.0.8 Error, No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
I am making a Blog website, but when I click on save button this error appears. No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. url.py from django.urls import path from .views import BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView urlpatterns = [ path('', BlogListView.as_view(), name='home'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), ] models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey( "auth.User", on_delete=models.CASCADE, ) def __str__(self): return self.title def getAbsoluteUrl(self): return reverse("post_detail", kwargs={"pk": self.pk}) base.html {% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=\ Source+Sans+Pro:400" rel="stylesheet"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> </head> <body> <div> <header> <div class="nav-left"> <h1><a href="{% url 'home' %}">Django blog</a></h1> </div> <div class="nav-right"> <a href="{% url 'post_new' %}">+ New Blog Post</a> </div> </header> {% block content %} {% endblock content %} </div> </body> </html> views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Post from django.urls import reverse_lazy # Create your views here. class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post … -
How to create django project
What commands should I write in cmd. When I write: django-admin startproject myproject, it does not create a config folder in my project. What do I miss? -
How to filter objects by many to many attribute
Please help me to solve the following problem: I have two models, for example: class Student(model.Model): first_name = models.Charfield() last_name = models.Charfield() class Teacher(model.Model): first_name = models.Charfield() last_name = models.Charfield() subject = models.Charfield() students = models.ManyToManyField('Student') A teacher object can have many students. When adding a new teacher, his students are immediately indicated, but a check must be performed for each student that this student is not tied to another teacher with the same subject. Please help me how to organize this check (I suppose using a filter). Thanks a lot in advance! I tried to use filter like Teacher.objects.filter(subject=self.subject), but don't know how to check every student here -
Got AttributeError when attempting to get a value for field `transformerNamePlate` on serializer `MainDataSerializer`
i am trying to get a list of Main Objects with all of its nested Objects. but i got this error here is my codes views.py ` @api_view(['GET']) def getSelectedDevice(request): try: device_id=request.GET.get('dID', None) device=Main.objects.filter(device_id) print("device obg:\n",device) serializer=MainDataSerializer(device) return Response(serializer.data,many=True) except Main.DoesNotExist: return Response(status=404) ` models.py ` class TransformerNamePlate(models.Model): power=models.FloatField() uk=models.PositiveIntegerField() z0nom=models.FloatField() vectorGroup=models.CharField(max_length=10) vectorGroupLabel=models.CharField(max_length=10) uside1=models.FloatField() uside2=models.PositiveIntegerField() class Main(models.Model): dID=models.CharField(max_length=10) tID=models.CharField(max_length=12) user=models.CharField(max_length=40) deviceAliasName=models.CharField(max_length=60) dateTime=models.DateTimeField() #did and Tid (search) -> charfield transformerNamePlate=models.OneToOneField(TransformerNamePlate,on_delete=models.PROTECT) transformerInfo=models.OneToOneField(TransformerInfo,on_delete=models.PROTECT) detcTapChanger=models.OneToOneField(DETCTapChanger,on_delete=models.PROTECT,null=True) temperatureCorrectionHV=models.OneToOneField(TemperatureCorrectionHV,on_delete=models.PROTECT) temperatureCorrectionLV=models.OneToOneField(TemperatureCorrectionLV,on_delete=models.PROTECT) uk=models.OneToOneField(UK,on_delete=models.PROTECT) turnRatioTolerance=models.OneToOneField(TurnRatioTolerance,on_delete=models.PROTECT) tests=models.ForeignKey(Test,null=True,on_delete=models.PROTECT) ` serializer.py ` class TransformerNamePlateSerializer(serializers.ModelSerializer): class Meta: model=TransformerNamePlate fields="__all__" class MainDataSerializer(serializers.ModelSerializer): transformerNamePlate=TransformerNamePlateSerializer(many=False,read_only=False) transformerInfo=TransformerInfoSerializer(many=False, read_only=False) detcTapChanger=DETCTapChangerSerializer(many=False, read_only=False) temperatureCorrectionHV=TemperatureCorrectionHVSerializer(many=False, read_only=False) temperatureCorrectionLV=TemperatureCorrectionLVSerializer(many=False, read_only=False) uk=UKSerializer(many=False, read_only=False) turnRatioTolerance=TurnRatioToleranceSerializer(many=False, read_only=False) #tests=Test ->(many=False, read_only=True) class Meta: model=Main fields="__all__" def create(self, validated_data): transformerInfo_data=validated_data.pop('transformerInfo') temperatureCorrectionHV_data=validated_data.pop('temperatureCorrectionHV') temperatureCorrectionLV_data=validated_data.pop('temperatureCorrectionLV') transformerNamePlate=validated_data.pop('transformerNamePlate') uk_data=validated_data.pop('uk') turnRatioTolerance_data=validated_data.pop('turnRatioTolerance') detcTapChanger_data=validated_data.pop('detcTapChanger') #Remember to add other parts of test data test_data=validated_data.pop('tests') #print(validated_data) main_data=Main(**validated_data) # for data in temperatureCorrectionHV_data: # print (data) TemperatureCorrectionHV.objects.create(main=main_data,**temperatureCorrectionHV_data) TemperatureCorrectionLV.objects.create(main=main_data,**temperatureCorrectionLV_data) DETCTapChanger.objects.create(main=main_data,**detcTapChanger_data) UK.objects.create(main=main_data,**uk_data) TransformerInfo.objects.create(main=main_data,**transformerInfo_data) TransformerNamePlate.objects.create(main=main_data,**transformerNamePlate) TurnRatioTolerance.objects.create(main=main_data,**turnRatioTolerance_data) # Test.objects.create(main=main_data,**test_data) return main_data def save(self,data=None, **kwargs): if data!=None: main_data=self.create(validated_data=data) main_data.save() return else: return super().save(**kwargs) ` I figured out that it is because that Main.objects.all() doesnt return those nested data and just return the id field of them and because of that i get KeyError in serializer because it is looking for the actual object,not its id. -
403 error while fetching from my own server: CSRF Token missing
I have a social-media-like page that displays all posts by each user and users are able to edit their own posts with an Edit button. When the edit button is clicked, a textarea pre-filled with post content plus a Save and a Cancel button are displayed. When the Save button is clicked, I make a fetch request to update the content without reloading the page. However, I'm getting 403 because the csrf token is missing. What confuse me is that I don't have a form in my HTML template. Where should I put {% csrf_token %}? network.js: function clearEditView(postId) { // Show edit button and original content document.getElementById(`edit_button_${postId}`).style.display = "block"; document.getElementById(`content_${postId}`).style.display = "block"; // Hide edit form document.getElementById(`edit_form_${postId}`).style.display = "none"; } document.addEventListener('DOMContentLoaded', function() { // Add event listener that listens for any clicks on the page document.addEventListener('click', event => { // Save the element the user clicked on const element = event.target; // If the thing the user clicked is the edit button if (element.id.startsWith('edit_button_')) { // Save necessary variables const editButton = element; const postId = editButton.dataset.id; const saveButton = document.getElementById(`save_${postId}`); const cancelButton = document.getElementById(`cancel_${postId}`); const postText = document.getElementById(`content_${postId}`); // Hide edit button and original content editButton.style.display = "none"; … -
Django include template as variable to use in default
I'd like to include a default template as a variable to pass it into a default case, like below: <div class="row max-h-200 overflow-hidden"> {% include 'blog/userprofile_deleted.html' as deleted_profile %} {{ user.profile.bio | safe | default:deleted_profile }} </div> Is this possible in django 3.2.9 ? Currently I have to write out the default text as html in a single line: <div class="row max-h-200 overflow-hidden"> {{ user.profile.bio | safe | default:'<h4> Very long html string! </h4> <span>Comment as <b>you</b> with your own profile!</span><span>Create your Account at the <a href="#footer">bottom of the page</a>,or by visiting <a href="{% url "register" %}"><code>/register</code></a> !</span>' }} </div> -
Displaying join tables (many-to-many relationships) with django-extensions graph_models
For an exhaustive visual understanding of a data model, is there a way to display join tables (they actually exist in the DB) of many-to-many relationships with graph_models from the django-extension (3.2.1) module? This is the current help I got and I cannot find it all through: $ python manage.py graph_models --help usage: manage.py graph_models [-h] [--pygraphviz] [--pydot] [--dot] [--json] [--disable-fields] [--disable-abstract-fields] [--group-models] [--all-applications] [--output OUTPUTFILE] [--layout LAYOUT] [--theme THEME] [--verbose-names] [--language LANGUAGE] [--exclude-columns EXCLUDE_COLUMNS] [--exclude-models EXCLUDE_MODELS] [--include-models INCLUDE_MODELS] [--inheritance] [--no-inheritance] [--hide-relations-from-fields] [--relation-fields-only RELATION_FIELDS_ONLY] [--disable-sort-fields] [--hide-edge-labels] [--arrow-shape {box,crow,curve,icurve,diamond,dot,inv,none,normal,tee,vee}] [--color-code-deletions] [--rankdir {TB,BT,LR,RL}] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] [app_label ...] Creates a GraphViz dot file for the specified app names. You can pass multiple app names and they will all be combined into a single model. Output is usually directed to a dot file. positional arguments: app_label optional arguments: -h, --help show this help message and exit --pygraphviz Output graph data as image using PyGraphViz. --pydot Output graph data as image using PyDot(Plus). --dot Output graph data as raw DOT (graph description language) text data. --json Output graph data as JSON --disable-fields, -d Do not show the class member fields --disable-abstract-fields Do not show the class … -
Why am I not able to create a super user in django? It's asking me to fill in every detail and on top of that, it asks me to enter a location
What can I do here? What kind of a location it is looking for from me? It has never happened ever earlier. -
How to set allow_null=True for all ModelSerializer fields in Django REST framework
I have a ModelSerializer . I want to set allow_null=True for all of the fields of the serializer . But I don't want to do it manually, I mean- I don't want to write allow_null=True for every field . Is there any shortcut? Is there anything like read_only_fields=() ? This is my Serializer class ProductPublicListSerializer(serializers.ModelSerializer): minimum_price = serializers.FloatField(source='min_product_price', allow_null=True) maximum_price = serializers.FloatField(source='max_product_price', allow_null=True) # rating = serializers.FloatField(source='productreview__rating', read_only=True) class Meta: model = Product fields = ( 'id', 'name', 'featured_image', 'minimum_price', 'maximum_price', 'total_review', 'average_rating') read_only_fields = ('name', 'featured_image', 'minimum_price', 'total_review') -
How to optimize a query on a model with foreign keys AND many to many field
(https://pastebin.com/qCMypxwz) These are my models. Right now 14 queries are made to get the desired result. Mostly, a query is made to get images associated with each product. Image is many to many field because each product has many images. productList = Variants.objects.select_related('prod_id__category') for productName in productList: products = dict() prod_id = productName.id products['id'] = prod_id products['category'] = productName.prod_id.category.category_name products['prod_name'] = productName.prod_id.prod_name prod_images = list(productName.image.values_list('image_url').distinct()) image_list = list() for image in prod_images: image_list.append(image[0]) products['image'] = image_list price = productName.price products['price'] = price createdAt = productName.createdAt products['createdAt'] = createdAt productListDict.append(products) -
Hardcode the value of a child class model field to be = to a field value in its parent
In a Django model, I would like to force a field of a child class to have a fixed value inherited from of a field of its parent. E.g.: from django.db import models class Entity(models.Model): class Type(models.TextChoices): Natural = ("Natural", "natural") Juridical = ("Juridical", "juridical") entity_type = models.CharField( max_length=9, choices=Type.choices, default=Type.Natural, ) class Person(Entity): person_type = Entity.Type.Natural # <--- forcing it to be 'Natural' from parent class ... I want to create such person_type field and forcing its value to be 'Natural' for each person object created using the Person class. This field can then be displayed in the admin, but the user must not have any kind of option to modify it. Same in the DB, ideally. I found nothing which relates to this idea in the doc: https://docs.djangoproject.com/en/4.1/ref/models/fields/ and I'm not able to apply this answer to set the value of the person_type field: https://stackoverflow.com/a/68113461/6630397 -
select not creating category entry in django database
I need to make it so that the select from the form is displayed in the database, None appears in its place in the database everything is added except categories and stocks I was told that I need to add value to option, but nothing happened to me what's wrong Here is my views.py : def create_product(request): categories = Category.objects.all() stock = Stock.objects.all() if request.method == 'POST': product = Product() product.title = request.POST.get('title') product.category = Category.objects.get(id=request.POST.get('category')) product.price = request.POST.get('price') product.user = request.POST.get('user') product.amount = request.POST.get('amount') product.stock = request.POST.get('stocks') product.user = request.user product.save() return redirect('index') return render(request, 'main/create.html', {'categories':categories,'stocks':stock}) Here is my models.py : class Product(models.Model): title = models.CharField(verbose_name="Название товара", max_length=250) categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) price = models.IntegerField(verbose_name="Цена") user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products') amount = models.CharField(max_length=250,verbose_name='Количество') user = models.ForeignKey(User, on_delete=models.PROTECT) stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' def __str__(self): return self.title My create template : <div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);"> <h1 class="display-6">Создайте товар</h1> <form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Название</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title"> </div> <div class="mb-3"> <label for="exampleFormControlInput1" …