Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why i am getting Direct assignment to the forward side of a many-to-many set is prohibited.?
I am getting this error when I am trying to add data on the auction_watching model. I tried make ManytoMany relation with auction_watching and products table. But why I am getting this error. Please help me out models.py from django.db import models from PIL import Image from datetime import datetime, timedelta from django.contrib.auth.models import User # Create your models here. class Products(models.Model): product_img = models.ImageField(upload_to='pics') product_title = models.CharField(max_length=100) price = models.IntegerField() deadline = models.DateTimeField() def save(self, *args, **kwargs): super(Products, self).save(*args, **kwargs) img=Image.open(self.product_img.path) if img.height >= 300 and img.width >=300: img = img.resize((200, 300)) # resize use to resize image, don't care about ration # output_size = (200,300) # img.thumbnail(output_size) # thumbnail use to resize image with aspect ration img.save(self.product_img.path) class Auction_Watching(models.Model): product_info = models.ManyToManyField(Products, null=True ) User_id = models.IntegerField() current_bid = models.IntegerField(null=True) action_status = models.BooleanField(default='True') def __str__(self): return self.name views.py def auction_watch(request,pk): username=request.session['username'] user_id= request.session['value'] product_information = Products.objects.get(id=pk) product_watch = Auction_Watching.objects.create(product_info=product_information, User_id=user_id) return render(request, 'auctionApp/auction_watch.html') -
tile name is not display only object name is display on Django admin
models.py from django.db import models class Blog(models.Model): title=models.CharField(max_length=50,default="") auther=models.CharField(max_length=100, default="") body=models.TextField(default="") def __self__(self): return self.title http://127.0.0.1:8000/admin/ BLOG Blog object (3) Blog object (2) Blog object (1) Here title name is not shown -
How to fix "M" value must be True or False
This is my model.py where my gender is a booleanfield This is my forms.py where i put my gender as a choicefield and the widget is radioselect Maybe my wrong is in the views.py but i don't know how to fix This is the error that i need to fix Please help me -
How to change many to many field name in the serializer?
I know it is relatively simple to change a represented filed name in the serializer with source argument like this: class SomeSerializer(ModelSerializer): alternate_name = serializers.SomeField(source='field_name') class Meta: fields = ('alternate_name') But when dealing with a many to many field, the source is a ManyRelatedManager and using source in it leads to errors: class SomeModel(models.Model): field_name = models.ManyToManyField(OtherModel, related_name='groups') class SomeModelSerializer(ModelSerializer): alternate_name = models.ListField(source='field_name') class Meta: fields = ('alternate_name') This gives ManyRelatedManager object is not iterable! Using other Fields instead of ListField gives other errors. What is the right approach here? -
How can I access Django Source Code on VsCode?
When I do control + click in VsCode inside a django application, it takes me to a new window, which i thought to be Django's source code, but I'm not sure what all of this means: class UserCreationForm(forms.ModelForm): error_messages: Any = ... password1: Any = ... password2: Any = ... def __init__(self, *args: Any, **kwargs: Any) -> None: ... def clean_password2(self) -> str: ... Meanwhile the source code for the same form, looks completely different and readable on Djando docs: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/ Then again that document is for an older version of Django, so maybe they changed the way they write the code to the extent that looks like gibberish to me. -
Move <label> after <input type="file"> using FileInput in Django
I want to create a custom design for a file upload button in Django. In the CSS styling I use the selector .custom-upload[type=file] + label, just like this CodePen does, but in order for this styling to work the <label> element must come after the <input> element. It seems that Django by default puts the <label> element before the <input> element. Is there any way of changing the HTML order? I don't feel like my code is relevant to the question but here it is anyway for the sake of completeness: models.py from django.db import models class File(models.Model): file = models.FileField() views.py class UploadFileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UploadFileForm, self).__init__(*args, **kwargs) self.fields['file'].label = 'Choose your file' class Meta: model = File fields = ('file',) widgets = { 'file': forms.FileInput(attrs={'id': 'upload-file', 'class': 'custom-upload'}) } def index(request): return render(request, "homepage/index.html", { "form": UploadFileForm() }) -
Django - Best User model in an employee context - storing ranks/titles for different years
I'm starting a new Django project and am trying to create a custom User model. This will ultimately be used for a small internal employee portal. The intention is to track each employee's titles across different years. For instance, my aim is to be able to have a table with two columns, each column having dropdown fields that allows me to select the year, and the title from a set of pre-defined titles. I can then add a new row each time I want to add specify a new year and new title. I am having difficulty figuring out what field to implement here within the custom User model, and would be grateful to be pointed to the right direction. -
Django: Input field disappear when html and css are use d
I'm trying to costumize with html e css a form that I made with bios info that are saved in the database (I have also login/signup forms using the same template and that works). Unfortunaly when I render it the field to input data is missing. Can someone help me? This is my code. Also I don't know is the right way to have radiobutton for gender since in the database it appeared as a dropdown list. models.py class PHUser(models.Model): last_name = models.CharField('Last Name', max_length=30) gender_options = (('m', 'Male'),('f', 'Female'),) gender = models.CharField(max_length=1, choices= gender_options) birthday = models.DateTimeField('Birthday') phone = models.CharField(max_length=10) forms.py class PHUserForm(ModelForm): class Meta: model = PHUser fields = ('last_name', 'gender', 'birthday', 'phone') widgets = {'gender': forms.RadioSelect} def add_user(request): submitted = False if request.method == "POST": form = PHUserForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('add_user?submitted=True') else: form = ExperimentUserForm if 'submitted' in request.GET: submitted = True return render(request, 'ph/add_user.html', {'form': form, 'submitted': submitted}) file.html <form method="POST" action=""> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> {{ form.last_name }} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{ form.gender }} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{ … -
There is a billing page that I fill in all the details and click on make bill button, then the invoice page should be generated
There is a billing page that I fill in all the details and click on make bill button, then the invoice page should be generated, it is not coming. views.py def makebill(request): if request.method == "POST": cart = request.POST.get('cart') price = request.POST.get('price') n = request.POST.get('name') phone = request.POST.get('phone') data = json.loads(cart) for c in data: name = c['name'] qty = c['qty'] prod = Product.objects.get(name=name) prod.qty = prod.qty - int(qty) if prod.qty <= 0: messages.warning(request, f'{prod.name} has finished') prod.delete() else: prod.save() p= Sales(items_json=cart, amount=price, name=n, phone=phone) p.save() total = price product = Product.objects.all().order_by('name') product_list = list(product.values('name', 'cost')) context = {} context["product"] = json.dumps(product_list) try: context["total"] = total except: pass return render(request, 'makebill.html', context) Thanks in advance! -
PYTHON: How can i set file as a value for session variable or is there any better option for accessing the file in another view?
overall concept is user uploads the resume and selects either auto-corrections, show corrections, and no corrections. If the user selects auto-corrections it will automatically correct the misspelled words but when the user selects show corrections, will show the user list of misspelled words and allow the user to select specific words to correct with the predefined words or with their own words. I'm new to python. so if the code is wrong. please teach me # called from HTML form action when user selected show corrections option and uploads the resume .docx file. def uploading_resume(request): user = request.user if user.is_authenticated: if request.method == 'POST': if corrections == 'show': global u_file u_file = request.FILES['file'] resume_text = show_corrections(request=request, file=file) # gets the list of incorrect words and returns the list. def show_corrections(request, file): user = request.user resume_text = [] document = Document(file.file) parser = GingerIt() text = '' for line in document.paragraphs: text += line.text matches = parser.parse(line.text) for obj in matches['corrections']: word_obj = {'word': obj['text'], 'correct_word': obj['correct']} resume_text.append(word_obj) return resume_text # when user selected specific words from the above list. def correct_selected(request): user = request.user if user.is_authenticated: if request.method == 'POST': if request.POST['selected_words'] != '': selected_words = demjson.decode(request.POST['selected_words']) file_name = request.POST['selected_file_name'] … -
How to retain image file in django
I have a newclaim form which allows user to upload a picture and editclaims which allows users to retain or add new pictures which will overwrite the old one. The current problem I faced is whenever I try to edit without making any changes, the picture will become an empty field so I have to resubmit the picture again. This is my views.py # Submit a new Claim def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins = SaveClaimForm(receipt=receipt) ins.save() print("The Data has been written") return render(request, 'Login/newclaim.html/', {'user':user}) # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': # update original object receipt = request.FILES['receipt_field'] # save it with original `ID` claims.save() return render(request, "Login/editclaims.html", {'claims':claims, 'user':user}) This is my editclaims.html <form method="POST" action="/editclaims/{{claims.id}}" enctype="multipart/form-data"> <div> <input id="receipt" name="receipt" type="file" value="receipt"> <label for="receipt"> {{ claims.receipt }} </label> </div> </form> This is my newclaim.html <form action="/newclaim/" method="post" enctype="multipart/form-data"> <div> <input id="receipt" type="file" name="receipt_field" style="display: none; visibility: none;"> </div> </form> -
Unable to get Zero/0 in If Statement wile using if in Django template
I am trying to use a Django template for executing some if/else statement , the issue is in the last option header_info.status.error the value from where I am fetching this info is zero but only blank table cell is coming , anything missing here or anything can be modified here to fix it ? <th>{{ header_info.status.total }}</th> <th>{{header_info.status.success}} {% if header_info.status.failure%}</th> <th>{{ header_info.status.failure }}{% endif %}{% if header_info.status.skip%}</th> <th>{{ header_info.status.skip}} {% endif%} {% if header_info.status.error%}</th> <th>{{ header_info.status.error }}{% endif %}</th> -
Django Rest Framework: if leave request is approved marked as absent on those days
this is leave approve and decline action this is the student attendance modelThis is leave model -
Adding a new object to the model returns 'list' object has no attribute '_committed' error
I want to add a new object to the model in database but when I tried to add it, it gives an error like 'list' object has no attribute '_committed' It gives an error at the part of car_model.save() Traceback Error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cars/add_car Django Version: 3.1.7 Python Version: 3.9.0 Installed Applications: ['cars.apps.CarsConfig', 'pages.apps.PagesConfig', 'accounts.apps.AccountsConfig', 'contact.apps.ContactConfig', 'houses.apps.HousesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'django.contrib.humanize', 'django.contrib.sites'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\gx760_000\Desktop\sahibinden\cars\views.py", line 434, in add_car car_model.save() File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1396, in execute_sql for sql, params in self.as_sql(): File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1339, in as_sql value_rows = [ File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] … -
How to generate pdf with vertical table?
I want to generate a pdf report containing data in a vertical table. Is there any library to achieve this functionality? I can use the following format of the dictionary to render data context = { "name":["A","B","C","D","E"] "age":[23,23,23,23,23], } but data is huge so it can affect performance.is there any other way to achieve this?I just want to generate pdf report with the table in the following format : | Name | A | 23 | | Age | B | 23 | -
I want to filter the clients of every agent individually. Django
I'm creating a view where I can show all the clients of specific agents via there PK. I am not having error when I use Client.objects.all() as the queryset and it gets to show all of the clients. however I don't know how to filter clients via select pk for Url. Please help. Here's my Views.py class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView): template_name = "agents/agent_client_list.html" context_object_name ="clients" def get_queryset(self): user= Agent.objects.get(pk=id) queryset = Client.objects.filter(user=user, agent__isnull=False).order_by('company_name') return queryset My Urls.py: from django.urls import path from .views import AgentListView, AgentCreateView, AgentDetailView, AgentUpdateView, AgentDeleteView, AgentClientListView app_name = 'agents' urlpatterns = [ path('', AgentListView.as_view(), name='agent-list'), path('<int:pk>/', AgentDetailView.as_view(), name='agent-detail'), path('<int:pk>/update/', AgentUpdateView.as_view(), name='agent-update'), path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'), path('<int:pk>/agent_client_list', AgentClientListView.as_view(), name='agent_client_list'), path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'), path('create/', AgentCreateView.as_view(), name='agent-create'), ] And HTML: {% extends "base.html" %} {% block content %} <section class="text-gray-600 body-font overflow-hidden"> <div class="container px-5 py-24 mx-auto"> <div class="lg:w-4/5 mx-auto flex flex-wrap"> <div class="lg:w-1/2 w-full mx-auto"> <h2 class="text-sm title-font text-gray-500 tracking-widest">AGENT</h2> <h1 class="text-gray-900 text-3xl title-font font-medium mb-4">{{ agent.user.first_name }} {{ agent.user.last_name }}</h1> <div class="flex mb-4"> <a href="#" class="flex-grow text-blue-500 border-b-2 border-blue-500 py-2 text-lg px-1"> Description </a> </a> <a href="#" class="flex-grow border-b-2 border-gray-300 py-2 text-lg px-1"> Update </a> </div> <div class="flex flex-col w-full"> <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div class="py-2 align-middle inline-block … -
How to execute code on SIGTERM in Django request handler thread
I'm currently trying to understand the signal handling in Django when receiving a SIGTERM. Background information I have an application with potentially long running requests, running in a Docker container. When Docker wants to stop a container, it first sends a SIGTERM signal, waits for a while, and then sends a SIGKILL. Normally, on the SIGTERM, you stop receiving new requests, and hope that the currently running requests finish before Docker decides to send a SIGKILL. However, in my application, I want to save which requests have been tried, and find that more important than finishing the request right now. So I'd prefer for the current requests to shutdown on SIGTERM, so that I can gracefully end them (and saving their state), rather than waiting for the SIGKILL. My attempt My theory is that you can register a signal listener for SIGTERM, that performs a sys.exit(), so that a SystemExit exception is raised. I then want to catch that exception in my request handler, and save my state. As a first experiment I've created a mock project for the Django development server. I registered the signal in the Appconfig.ready() function: import signal import sys from django.apps import AppConfig import logging … -
Simple jwt breaks when Secret Key is put into environment variable on Google App Engine
In a Django project hosted on Google App Engine using the simplejwt library, I receive this error message as soon as I put the secret key into an environment variable: TypeError at /api/v1/auth/jwt/create/ Expected a string value The key is stored in the apps yaml file as SECRET_KEY_ENV and loaded in Django's settings file like this: SECRET_KEY = str(os.environ["SECRET_KEY_ENV"]), The Database environment variables are loaded in exactly the same manner and everything is working fine. The first time the key pops up in the error message is in this file: /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/api_jwt.py, line 63, in encode and in this form: key : ('ai0eobey86soimfxb6ax4uqdmo49yiauxchgnspsh',) from there he gets passed on to: /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/api_jws.py, line 110, in encode /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/algorithms.py, line 180, in prepare_key /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/utils.py, line 21, in force_bytes without being changed and the last file "utils.py"is the one raising the error message. I have tried changing the variable name, removing special characters from the key, moving the definition around inside the settings file, nothing works. As soon as I put it back into cleartext, it works fine but I can't keep doing that for obvious security reasons. How can I fix this? Thanks and BR -
How we can hold the user for a second for please wait msg in Django as we show in PHP with refresh tag?
How we can hold the user for a second for please wait msg in Django as we show in PHP with refresh tag ?enter image description here -
model fields are not created django
models.py from django.db import models class Blog(models.Model): title=models.CharField(max_length=50,default="") auther=models.CharField(max_length=100, default="") body=models.TextField(default="") 0001_inital.py operations = [ migrations.CreateModel( name='Blog', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] cmd python manage.py migrate PS C:\Users\Dhiraj Subedi\Desktop\django-101> python manage.py makemigrations Migrations for 'first_app': first_app\migrations\0002_auto_20210531_1214.py - Add field auther to blog - Add field body to blog - Add field title to blog PS C:\Users\Dhiraj Subedi\Desktop\django-101> -
Cannot send array list from JavaScript to Django View
I have an array called tableData. But whenever I execute it I couldn't get the result on my python terminal. Since i already put print(pieFact), it should print me the output right? Other than that, when i put var data = {'test': '2', csrfmiddlewaretoken: '{{ csrf_token }}'};, i actually can get the 2 output in my terminal but not my array when I put 'test': tableData. Can anyone guide me what I'm doing wrong here? Thanks Javascript <script> //declare the array as a global var tableData = []; var URL="{% url 'test' %}" $(document).ready(function () { $(".button").on("click", function () { para = document.getElementById("Parameter").value; condi = document.getElementById("Condition").value; value2match = document.getElementById("valuetomatch").value; if (para && condi && value2match !== null) { var table = document.getElementById("myTable"); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); cell1.innerHTML = document.getElementById("Parameter").value; cell2.innerHTML = document.getElementById("Condition").value; cell3.innerHTML = document.getElementById("valuetomatch").value; cell4.innerHTML = '<button class = "del_img "onClick="delSpec(this)"><img src="deleteimg.png" width="30" height="30"></button> </div>'; var myTab = document.getElementById("myTable"); // Only add the new row: tableData.push([ document.getElementById("Parameter").value, document.getElementById("Condition").value, document.getElementById("valuetomatch").value ]); modal.style.display = "none"; } else { alert("All the input box cannot be empty!"); } }); document.getElementById("buttonSubmit").onclick = function () { alert(tableData); var data … -
JSON parsing error in django post request
I'm trying to send data through POST request in django url = 'http://db-003:8013/v1/upgrade-ce' payload = { "cluster_name": cluster_name, "cec_id": cec_id, "new_version": new_version, "cr_number": cr_number, } response = requests.post(url, data=payload) On receiver end post method: cluster name = request.data.get('cluster_name') Data on receiver's end <QueryDict: {'cluster_name': ['abcd'], 'cec_id': ['abc'], 'new_version': ['8.0.23'], 'cr_number': ['6587657']}> The obtained data is a list, and not an individual string string. Tried json.dumps() , but on the receiver end, data is empty. How do i get an individual string -
getting object created thanks to TabularInline problem
My model A uses TabularInline, which creates objects of model A1. I want to output information about object A1 to the console when I save object A. I use the clean/save method. When I save an existing A object, it's fine, but if I create one, it outputs an error. How can I track the creation of object A1 in object A? Thank you. class A(models.Model): name = models.CharField(max_length=120) def save(self, *args, **kwargs): super().save(*args, **kwargs) print(self.a_name.all()) class A1(models.Model): description = models.CharField(max_length=120) name = models.ForeignKey(A, on_delete=models.CASCADE, related_name="a_name") -
DjangoQ Logged in user
I am using Django Q to schedule my python script which is inside views.py but when running my cluster it doesn't fetch the logged in user it gives an error 'str' object has no attribute 'user'.I am using request.user to get the detail of current logged in user it is working fine in another views what should i do please can someone help me? -
How to copy or read a file from the outside of the project file in Django?
I have created a basic ocr system. When a user uploads a PDF file to the system ocr read it and created an xlsm file with the same name. I am using remote control with Azure (Windows). I created a download button. When I click it, download the file with the same name, so it should work but appears an error because I want to read the file from the outside directory of the project. So, I should copy this file to my media dir, or I should read from there. This is my project: C:\Users\f-otc\PycharmProjects\otc This is the file that I want to download: C:\f\otc <a href= "{% static path %}" class="btn btn-outline-primary btn-sm" download>Download Report File</a> This is my button It gets the path correctly but gives an error when file downloaded.