Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ChoiceField vs TypedChoiceField (Django)
I read the documentation about ChoiceField and TypedChoiceField but I could only understand that both can create Dropdown Select Box which looks exactly the same as shown below: The code with ChoiceField below: FRUITS = ( (1,'Apple'), (2,'Orange'), (3,'Banana') ) fruits = forms.ChoiceField(choices=FRUITS) # Here The code with TypedChoiceField below: FRUITS = ( (1,'Apple'), (2,'Orange'), (3,'Banana') ) fruits = forms.TypedChoiceField(choices=FRUITS) # Here My questions: What is the difference between ChoiceField and TypedChoiceField? When to use ChoiceField and TypedChoiceField? -
Nested Serializer creates new object
I have a serializer called EntrySerializer and it should return the staff details but if I want to create a new entry it wants to create a new staff object and throws an error. Is there anything like a read only field for my serializer? It should create a new entry but assign an already created staff object. class EntrySerializer(serializers.ModelSerializer): staff = serializers.SerializerMethodField('get_staff') def get_staff(self, obj): return MyUserSerializer(obj.staff).data class Meta: model = Entry depth = 1 fields = ('time_spend', 'staff',) Error: django.db.utils.IntegrityError: ERROR: NULL-value in Column »staff_id« relation »tagesbericht_tagesbericht_Entry« Not-Null-Constraint DETAIL: (54, 00:00:08.5, null, 61). POST: "tagesbericht_entry_set": [ { "staff": 2, "time_spend": "00:12:08" } ] -
Cant Adding to detail page user's posts İn django
Hey ı am trying to add the user's post to the detail page with DetailView but ı cant add this is the code ı wrote profile.py from django.shortcuts import get_object_or_404 from django.views.generic import DetailView from account.models import CustomUserModel from django.shortcuts import get_object_or_404 class ProfilDetailView(DetailView): template_name = 'pages/profil.html' context_object_name='profil' def get(self,request): profil = get_object_or_404( CustomUserModel,username=self.kwargs.get('username') ) yazi = get_object_or_404(YazilarModel,yazar=profil.username) return render(request,'pages/profil.html',context={ 'profil':profil, 'yazilar':yazi.all() }) urls.py path('kullanıcı/<str:username>',ProfilDetailView.as_view(),name='profil'), profil.html {% extends 'base.html'%} {% load static %} {% block title %} {{profil.username}} {% endblock %} {% block content %} <div class="card mb-3"> <div class="row g-0"> <div class="col-md-4"> {% if profil.avatar %} <img src="{{profil.avatar.url}}" class="rounded" class="pt-4" width="200px" height="200px " style="border: radius 15%; margin-right:20px; " alt=""> {% else %} <img src="{% static 'img/no-avatar.jpg'%}" class="rounded" class="pt-4" width="200px" height="200px " style="border: radius 15%; margin-right:20px; " alt=""> {% endif %} </div> <div class="col-md-8"> <div class="card-body"> {% if profil.get_full_name == '' %} <h5 class="card-title"> Adı : Girilmemiş</h5> <h5 class="card-title"> Soyadı : Girilmemiş</h5> {% else %} <h5 class="card-title"> Adı : {{profil.first_name}}</h5> <h5 class="card-title mb-5"> Soyadı : {{profil.last_name}}</h5> {% endif %} <h5>Hakkında :</h5> <hr> <p>Bla Bla Bla</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> </div> </div> <hr> {%endblock%} yazilar.py in models from distutils.command.upload import upload from enum import unique … -
M2M attribute error with FOO_set.all() and FOO not a queryset
Having a problem with a M2M related queryset: simplified model is class Category(models.Model): name = models.CharField(max_length=200) class Product(models.Model): name = models.CharField(max_length=200) category = models.ManyToManyField( Category, blank=True, null=True, related_name="categorytest") I usually do related queries using related name (which works fine here no problem) yet I wanted to try "set_all()" in this case. Say I do: elecs = Category.objects.get(name="Electronics") then: elecs.product_set.all() I get AttributeError: 'Category' object has no attribute 'product_set'. I am a bit surprised because this is an error that happens when using a queryset instead of a model instance yet, if a confirmation was needed, a type(elecs) gives me <class 'store.models.Category'>. I migrated/erased db multiple times, no change. Any idea ? Thanks -
How to put html code of method admin.ModelAdmin class in seperate .html file and add css to it?
I want to put the following code of def show_tags_btn into a separate .html file and add some CSS to it, How can I do it? class BusinessAccountAdmin(admin.ModelAdmin): list_display = ['id', 'business_title', 'business_description', 'status', 'note', 'show_tags_btn', 'is_approved'] def show_tags_btn(self, instance): work_samples = instance.worksamplesmodel_set.all() res = '' for ws in work_samples: res = res+str(ws.work_sample_description)+'<hr>' print(ws.work_sample_description) model = f''' <html> <body> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div class = "modal fade bd-example-modal-sm-{instance.id}" tabindex = "-1" role = "dialog" aria-labelledby = "mySmallModalLabel" aria-hidden = "true" > <div class="modal-dialog modal-sm"> <div class="modal-content"> {res} </div> </div> </div> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-sm-{instance.id}">Small modal</button> </body> </html> ''' return format_html(model) admin.site.register(BusinessAccountModel,BusinessAccountAdmin) Adding a bootstrap CDN link here is a good idea? After adding CDN link it affect my django admin panel colours, Why? -
Folder sometimes found and sometimes not found - DJANGO AUDIO CONTROLS
i have web that can uploaded file and save it to local storage. but when i got the file back, sometimes the folder of file can be detect but sometimes it's say not found. i want get the file back to played it at audio controls. first, when i uploaded file, the file cannot be play. second, when i open new web, the file can be played. at the same time, when i uploaded new file again, the new file cannot be played until i open new web. at my terminal like this: here's my code at html: <audio controls="controls"> <source src="/media/mp3/{{last_audio.audio}}" type="audio/mpeg"> </audio> views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() audio = form.cleaned_data.get("audio") print(audio) context={'form':form, 'last_audio':audio} return render(request, 'homepage.html', context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context) i was already delete database and create again, but it's still same. please help me, i don't know what's wrong. i was using chrome, incognito and microfost edge, and the result its same. -
Python how to pass form input value to payload
I need to submit a form to an API and I want to pass the form fields value to the Payload for a python request API,enter code here how can I achieve this? models.py class Book(models.Model): trading_name = models.CharField(max_length=100, null=True) industry = models.CharField(max_length=100, null=True) vat = models.CharField(max_length=100, null=True) address_street = models.CharField(max_length=100, null=True) address_city = models.CharField(max_length=100, null=True) address_postal_code = models.CharField(max_length=100, null=True) address_iso_country = CountryField(max_length=100, null=True) def __str__(self): return self.title forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ('trading_name', 'industry', 'vat', 'address_street', 'address_city', 'address_postal_code', 'address_iso_country') views.py def upload_kyb(request): if request.method == 'POST': url = 'https://stoplight.io/mocks/railsbank/api/25652867/v1/customer/endusers' headers = { 'Content-Type': "application/json", 'Accept': "application/json", 'Authorization': "" } payload = "{ \n \"company\": {\n \"name\": \"Example Company\", \n \"trading_name\": \"jiuliasu\",\n \"industry\": \"Telecommunications\",\n \"vat\": \"GB123456789\",\n \"registration_address\": \n {\n \"address_refinement\": \"Floor 15\", \n \"address_number\": \"20\", \n \"address_street\": \"Floor 15\", \n \"address_city\": \"London\", \n \"address_postal_code\": \"SS8 9JH\", \n \"address_iso_country\": \"GBR\" \n }\n\t}\n}" response = requests.request("POST", url, data=json.dumps(payload), headers=headers) print(response.text) print(payload) # form = Kybform(request.POST, request.FILES) form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('kyb_list') else: form = BookForm() return render(request, 'kybstart/upload_kyb.html', { 'form': form }) I can get the response in the console but how can I actually pass the form inputs dynamically into the Payload? -
I had built my own payment system how can i integrate with any ecommerce website?
I had developed my own payment system. Now I want to integrate with any ecommerce website. How to write view to integrate with it. -
How to fix def of XYZModelAdmin class in admin.py reciving same instance for each time?
In the following code, I am displaying the id in the bootstrap model as an instance.id. but for every row it shows same id of the first instance. class BusinessAccountAdmin(admin.ModelAdmin): list_display = ['id', 'business_title', 'business_description', 'status', 'note', 'show_tags_btn', 'is_approved'] list_editable = ('is_approved',) def show_tags_btn(self, instance): model = f''' <body> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div class = "modal fade bd-example-modal-sm" tabindex = "-1" role = "dialog" aria-labelledby = "mySmallModalLabel" aria-hidden = "true" > <div class="modal-dialog modal-sm"> <div class="modal-content"> {instance.id} </div> </div> </div> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-sm">Small modal</button> </body> ''' return format_html(model) admin.site.register(BusinessAccountModel,BusinessAccountAdmin) Why def show_tags_btn(self, instance) method receiving same instance for every time? -
Flutter Web Failed to load resource: the server responded with a status of 404
I'm having problem to deploy my flutter web app to cpanel. Please find the screenshot of the error And this is my current base href on index.html <base href="/"> I found some questions asking about this issue but nothing is worked for me. I follow the solution on this link when deploying the app How to serve a Flutter web app with Django? I also tried to change the base href to <base href="./"> , <base href="/web_app_name/"> , and also remove the base href but still didn't work. Hope someone has the solution for this. -
Forbidden <URL> User Registration Python Django
I created a Patient model in models.py file and then used a serializer to convert the data. Previously, I was using the built-in User model and serializers to perform user registration, email verification and login. But I had to add extra fields and thought it would be better to make a separate table in the DB. I've made the migrations and the changes, but I get the forbidden error. I was wondering if my Postman request was correct or not. Please guide me! My models.py file: from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator GENDER_CHOICES = ( ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other') ) class Patient(models.Model): patient_name = models.CharField(max_length=50, null=False) address = models.CharField(max_length=254, null=False) contact_no = models.IntegerField( validators=[MaxValueValidator(99999999999)], blank=False) dob = models.DateField(null=False) gender = models.CharField(choices=GENDER_CHOICES, max_length=128, null=False) email = models.EmailField(max_length=254, null=False, unique=True) password = models.CharField(max_length=25, null=False) is_active = models.BooleanField(null=False) class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') verification_token = models.CharField( max_length=256, blank=True, null=True) My serializers.py file: (the commented code is from when I was solely using serializers and User for user registration, email confirmation & login. from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import Patient, … -
How to replace 'delete selected ' action with a delete button? Django admin
i have a question since i only have one action (in django admin) which is delete selected, i want to make a specific button for it called 'Delete ' instead of choosing the action and then clicking on go . How can i do that? -
How to get reverse relationship object django annotate with subquery?
It's not a good structure, but it's an example This is my sample model class Book(models.Model): name = models.CharField(max_length=50) class Borrower(models.Model): book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) age = models.IntegerField() class OwnerCard(models.Model): certification_date = models.DateField() class Owner(models.Model): owner_card = models.ForeignKey(OwnerCard, on_delete=models.SET_NULL, null=True) book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=50) age = models.IntegerField() I want to use reverse relationship to get the object of the Borrower and Owner from the Book Model Like this from django.db.models import Subquery, OuterRef Books = Book.objects.all().annotate( borrower=Subquery(Borrower.objects.get(user=OuterRef('user'))), owner=Subquery(Owner.objects.get(user=OuterRef('user'))) ) Or Books = Book.objects.all().annotate( borrower=Subquery(Borrower.objects.filter(user=OuterRef('user')).first()), owner=Subquery(Owner.objects.filter(user=OuterRef('user')).first()) ) and I want use print(Books[0].brrower.name) >>> brrower's name print(Books[0].owner.owner_card.certification_date) >>> certification date But, it's not working. don't have to use annotate or subquery. Is there a way to implement it this way? -
Trying to add a button to Django admin
So, I use a custom administration (grappelli) I need to add my button with functionality. Used the documentation - https://django-grappelli.readthedocs.io/en/latest/customization.html Here’s another - ImportError: cannot import name 'url' from 'django.conf.urls' after upgrading to Django 4.0 I created the timetable\templates\admin\change_list.html, code in it: {% extends "admin/change_list.html" %} {% load i18n %} {% block object-tools-items %} {{ block.super }} <li> {% comment %} <a class="historylink" href="test_data/">My custom admin page</a> {% endcomment %} <a href="#" class="grp-add-link grp-state-focus">Add ТЕСТ (ТаМ ДЕ НАДА)</a> прив)) </li> {% endblock %} If you look at an ordinary admin (without grappelli), the button appeared If With it, then no button. If you edit venv\Lib\site-packages\grappelli\templates\admin\change_list.html, The button appears, but it’s not the case... How can I make grappelli see my button? -
django form styling with bootstrap4 problem
I got some problems styling a form in django with bootstrap. I tried some diffrent ways to get it to work but cant. Any ideas how to style this form with bootstrap 4? at the moment with the code i have it looks like this. enter image description here **edit_profile_page.html** {% extends 'base.html' %} {% block title %}Edit Profile Page{% endblock %} {% block content %} {% if user.is_authenticated %} {% if user.id == profile.user.id %} <h1>Edit Profile Page</h1> <br/><br/> <div class="form-group"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-info">Update Profile Page</button> </div> {% else %} You got no access here! {% endif %} {% else %} You got no access here! {% endif %} {% endblock %} forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.contrib.auth.models import User from django import forms from newsapp.models import Profile class ProfilePageForm(forms.ModelForm): class Meta: model = Profile fields = ('bio', 'profile_pic', 'website_url', 'facebook_url', 'twitter_url', 'instagram_url', 'pinterest_url') widgets = { 'bio': forms.Textarea(attrs={'class': 'form-control'}), 'website_url': forms.TextInput(attrs={'class': 'form-control', }), 'facebook_url': forms.TextInput(attrs={'class': 'form-control'}), 'twitter_url': forms.TextInput(attrs={'class': 'form-control'}), 'instagram_url': forms.TextInput(attrs={'class': 'form-control'}), 'pinterest_url': forms.TextInput(attrs={'class': 'form-control'}), } -
What should i do to be able to see what i posted in a category?
When i post some json that contains category like this: [ { "id": 152, "image": "https://a", "description": "J t", "price": "USD 8.70", "buy": "https:// 6d7", "category": 1 }, { "id": 153, "image": "https://", "description": "elf", "price": "65", "buy": "https://s.c D", "category": 1 } ] in templates i do not see them. image html: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> <div class="header"> <img src="static/logo.png"> </div> </head> <body style="background-color: #56454F;"> <div class="grid"> {% for i in p%} <div class='card'> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} </div> <div class="footer"> <h1 >&copy All rights reserved</h1> </div> </body> </html> models: from django.db import models class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') def home(request): return render(request,'home.html',{'p':category.objects.all()}) def foods(request): return render(request,'foods.html',{'p':category.objects.all()}) I do not know what should i write in {'p':category.objects.all()} to be able to put some data from a specific category to that html code. … -
TypeError: __init__() got an unexpected keyword argument 'file'
I'm using Django to develop a platform where users can upload files. This function was working fine for months with no issues, but for some reason now I get this error when trying to upload a file: Traceback: Traceback (most recent call last): File "/home/me/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/me/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/me/project/app/views.py", line 314, in invoke_local instance = SingleEndForm(file=request.FILES['file']) Exception Type: TypeError at /invoke_local/ Exception Value: __init__() got an unexpected keyword argument 'file' My model: class SingleEnd(models.Model): file = models.FileField(upload_to="documents/") email = models.CharField(max_length=100) def __str__(self): return self.email My form: class SingleEndForm(forms.ModelForm): class Meta: # shows which model to use from models.py model = SingleEnd # fields = '__all__' fields = ["file", "email"] labels = { "file": "input your fasta/fastq file (min 3 sequences)", "email": "input your email to get a notification for your results in a timely manner", } widgets = { "email": forms.EmailInput(attrs={"class": "form-control"}), "file": forms.FileInput(attrs={"class": "form-control"}), } My view: def invoke_local(request): # path to save inputs media_path = "/home/me/project/media/documents/" # path to save outputs result_path = "/home/me/project/media/results" if request.method == "POST": # use the form to upload form info (post) and files form = SingleEndForm(request.POST, … -
Django ElasticSearch dsl drf returning duplicate search result
I have search based api views, when I search something, it return value, but return the duplicate value with that term. in my database, there is no duplicate data, even in elasticsearch build. This is my API views: from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet class ExampleAPIView(DocumentViewSet): document = ExampleDocument serializer_class = ExampleSerializer filter_backends = [ MultiMatchSearchFilterBackend ] multi_match_options = { 'type': 'phrase_prefix', } multi_match_search_fields = { 'title': 'title', } I am not getting why the search result returns duplicate data? Can anyone help me to fix this? -
How to create a map of the floors that the user could reserve?
I came up with a space management application for each floor and building. I would like it to be a web application. After logging in, the user could select the building, floor and the floor map should be displayed. By pressing on a room, he could reserve it. How could I implement this "map with desks to reserve" in Django or in Angular or maybe in something else it would be easier? I found only solutions with using google maps, that is not what I am looking for. -
Concerns regarding DDoS-like abuse of Django user registration POST requests
I am working on an online shopping mall-esque app with some of my friends. I am in charge of the server-side but I am not really a well-versed backend engineer. Hence, I pivoted toward using DRF for simplicity's sake. However, what caught my eye was that someone could possibly run a script that just repeats POST requests with a valid format. So far, I haven't managed to think of a way to impose custom permissions on this action because people who do not yet have an account have no way of authenticating themselves. Any help on this matter (or built-in functionality that renders this concern moot) would be much appreciated. Thank you! -
SMTPAuthenticationError when sending gmail
I am having this error: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials ij28-20020a170902ab5c00b00163efcd50bdsm1197936plb.94 - gsmtp') when I try to send a gmail in my registration app EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'repository0612@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_PORT = 587 I read in some other related forums that you just have to turn on the less secure apps in your google account settings but google already disabled that particular setting. I also tried turning off the 2-way authentication and my EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are as the same as my email and password. What else should I do to solve this problem? -
Calculate Balance amount for each currency from a model - Django
I want to calculate Balance for each currency based on deposit and withdrawal. in transaction_type 'd'=deposited amount and 'w'=withdrawn amount I want to calculate Balance for each currency based on deposit and withdrawal. in transaction_type 'd'=deposited amount and 'w'=withdrawn amount. Model Code: class Transactions(models.Model): transaction_currency=models.IntegerField(max_length=50) transaction_amount=models.FloatField() transaction_date= models.DateField(auto_now_add=False) transaction_description=models.TextField() transaction_type=models.CharField(max_length=5) View Function: def Available_Amount(request): available_amont = (how to calculate available amount for each currency?) -
Embed PDF file from download(ed) document
I used to ember pdf files with this simple code: <iframe src="file.pdf" style="width: 100%;height: 100%;border: none;"></iframe> which works perfectly for me. The file should be of course on the server, but is there any similar when I don't have direct "static" access to the file, only a link which serves the file as attachment like this: #django download = file(document.path, 'r') response = HttpResponse(download.read()) response['Content-Disposition'] = 'attachment; filename=' + \ document.get_clean_name() . Is it somehow doable if the file is served as attachment, and has a similar access link: http://sth.com/download_document/2022/ ? -
What should i write in "category": to create a post that belongs to a specific category like foods?
Since i created 2 categories in the admin panel like this: image but when i want to post this json it gives my this error: [ { "category": [ "Incorrect type. Expected pk value, received str." ] }, { "category": [ "Incorrect type. Expected pk value, received str." ] } ] json: [ { "image": "https://a ", "description": "J t", "price": "USD 8.70", "buy": "https:// 6d7", "category": "foods" }, { "image": "https:// ", "description": " elf", "price": " 65", "buy": "https://s.c D", "category": "foods" } ] image What should i write in "category": to create a post that belongs to a specific category like foods? models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') def home(request): return render(request,'home.html',{'p':category.objects.all()}) def foods(request): return render(request,'foods.html',{'p':category.objects.all()}) -
Existing data can not be edited in django models
After saving the filed , i want to make the field non editable, how i can do that. end_run = models.PositiveIntegerField( null=True, blank=True, help_text=_("Can be enter value Onece")