Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I/O operation on closed file. when trying to read a file content on django model save()
This is my Django Model where I'm trying to store the content of an uploaded file in field attachments: class CsvFile(models.Model): processed = models.BooleanField(default=False) uid = models.UUIDField(unique=True, default=str(uuid4())) date = models.DateField(null=False, default=datetime.datetime.now().date()) time = models.TimeField(null=False, default=datetime.datetime.now().time()) original_filename = models.CharField(max_length=600, blank=True) attachment = models.TextField(blank=True) file = models.FileField(upload_to=f"csv/", blank=True) def save_file_content_to_attachment(self, file): try: with file.open('r') as f: self.attachment = f.read() except (FileNotFoundError, ValueError): self.attachment = '' def save(self, *args, **kwargs): # Save the uploaded file to the csv_path field self.original_filename = self.file.name # Print a message to help troubleshoot the issue print(f"Saving file content to attachment for file {self.file.name}") # Save the file content to the attachment field self.save_file_content_to_attachment(self.file) super(CsvFile, self).save(*args, **kwargs) def delete(self, *args, **kwargs): # Delete the file from storage try: default_storage.delete(self.file.name) except FileNotFoundError: pass # File does not exist, so we can ignore the exception super(CsvFile, self).delete(*args, **kwargs) Unfotunately an upload of a file fails with I/O error Can somebody shed light into why this is not working? -
How to safely update the balance field in django
I need to use a wallet model in my project. If I need to update the balance of the wallet, what is the safest way to do it? For example, if different threads or different processes increase the balance of the wallet at the same time, will there be any problems? class Wallet(models.Model): balance = models.DecimalField(_('Balance'), max_digits=18, decimal_places=8, default=0) def withdraw(self,amount): self.balance = self.balance - amount def deposit(self,amount): self.balance = self.balance + amount Is this model above safe? If not, what is the best practice? -
Jinja code rendered using ajax is enclosed witin doublequorts in django project
I am developing a todo app using django as backend and html,css,bootstrap for frontend, I used Ajax in this project to load data from server without refresh. **Look at the image ** the {%csrf_token%} is passed through ajax but is is renderd in html page as a text within a double quort. How to fix this I want to render the {%csrf_token%} in the webpage without double quorts. Ajax code $.ajax({ type:'POST', url:'/task/'+todo_id+'/new_todo/', processData: false, contentType: false, data: data, success: function(response){ console.log("**********Data send to backend"); var new_id = response['new_id']; var new_color = response['new_color']; var new_status = response['new_status'] var new_todo_note = response['new_todo_note'] if (new_todo_note == null){ my_note = " " } else{ my_note = new_todo_note } $("#"+todo_id).hide(); $.ajax({ type:'GET', url:'/task/'+todo_id+'/new_todo/', data:data, dataType:'json', success: function(response){ var todo_section = `<ol class="list-group mb-3 v1" id="${response.latest_todo.id}right"> <li class="list-group-item d-flex justify-content-between align-items-start"> <div class="ms-2 me-auto d-flex"> <div> <div class="fw-bold">${response.latest_todo_name}</div> <p style="font-size: x-small; margin:0;">${response.latest_todo_added_date}</p> <div style="max-width: 100px; display:flex; "> <div id="${new_id}task_note"> ${my_note} </div> </div> </div> <div class="mt-1 ms-4"> <a href="{%url 'todo-details' todo.id%}"> <i class="fa-solid fa-arrow-up-right-from-square text-muted"></i> </a> </div> </div> <div class="d-flex flex-column"> <div style="align-self: flex-end;" id="${new_id}badge_live"> <span class="badge rounded-pill" id="${new_id}badge" style="background-color:${new_color};">&nbsp&nbsp&nbsp </span> </div> <div class="mt-2 d-flex"> <div class="me-2"> <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal" style="font-size: xx-small;"> Note … -
changes in views.py are not reflected in html page
I have noticed that my modifications in views.py function are reflecting in my html page after some hours. But if I make further modifications in the function, it is not getting reflected. Is there any logic behind that in django? I have a file called templates/app/token.html and a views.py where I have def token which will render to token.html. when I created that function for the 1st time it worked. After that however I make changes to the views function, it was not reflected in the html file. When I opened that html file after hours, the changes were reflected in the html page. Now I'm trying to make changes, but it is not reflecting as before. Is there any reason in django where this kind of behaviour will be observed in the templates files and is there any solution to it? -
django.db.utils.OperationalError: (1054, "Unknown column 'django_migrations.app' in 'field list'")
I have Django project it was on local server and shifted to cloud host and I want want to transfer my database from Postgres (local) to MySQL , but when I transferred using third party it shows this error when I run it on server how can I solved this issue -
Unable to install mysqlclient in django
I am using the latest python version 3.11 in django framework, for that I need to install mysqlclient . But there was error when I try to install pip install mysqlclient Output like this as error: Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win32-cpython-311 creating build\lib.win32-cpython-311\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\release.py -> build\lib.win32-cpython-311\MySQLdb copying MySQLdb\times.py -> build\lib.win32-cpython-311\MySQLdb creating build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-cpython-311\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-cpython-311\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools / [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to … -
trigger a function only once per user
I have an application where each user who has previously authenticated can access the index.html page with a button to trigger a time.sleep(t) function. What I would like is that the same user cannot retrigger the function. urls.py from . import views from django.contrib.auth.decorators import login_required urlpatterns = [ path('page1', login_required(function=views.page1, login_url="login"), name="page1"), ] views.py def page1(request): if(request.GET.get("arg")=="nap" and request.session.get("nap") == None): request.session["nap"] = True sleep(1, 5) request.session["nap"] = None return render(request, 'page1.html') def sleep(t, n): for i in range(0,n): time.sleep(t) print(f"nap n°{i}") index.html <button type="button"> <a href="{% url 'page1' %}?arg=nap"> NAP </a> </button> -
How should I migrate a model?
django.db.migrations.exceptions.InconsistentMigrationHistory Migration admin.0001_initial is applied before its dependency accounts.0001_initial on databas I e ' default ' . C : \ Users \ mamma tutorial \ django \ newsite I tried to migrate a model, but when I run the command in the terminal, this problem occurs -
Reducing Item by -10 in Class Based View
I have a button when clicked should reduce an Item by 10,it is possible to achieve using a function not as_view, please help on reproducing the same effect on a ListView, Thank You All. Blessed. Views.py def subs(request, pk): sw = get_object_or_404(Swimmers,id=pk) c_s = sw.sessions - 10 sw.sessions = c_s sw.save() return render(request, 'accounts/modals/swimming/_vw_table.html', {'sw': sw}) URL path('subt/<int:pk>/', views.subs, name='subt'), Template <form id="post-form"> <div class="col float-right"> <button type="submit" class="float-right btn btn-primary" id="saveBtn" name="button">REDUCE SESSION</a> </div> </form> Thank You All, May ALLAH (S.W.T) Bless You All. -
How to avoid username change through URL in django application
I am working on a basic django chat application where the user can login and then enter the room id to join a specific room where they can chat with other users. The room looks like this enter image description here Now the problem is that if I change my username in URL to some other registered username then I am able to chat as if I am that user (By passing all the login). What changes I need to make to avoid this or the things that are to be added so that even if someone tries to attempt to change, it redirects it to the login page and after proper login only that person will be able to use that. I avoided the problem of accessing the unregistered user i.e. if someone enters the username that is not registered then he will not be able to chat with that username but it still is not redirecting them to login page. This code shows the above logic: enter image description here Please suggest changes here too! -
how to use order_by in two field and given the same priority to them
I have model and i wont to sort my objects based two fields and two fields have the same priority class Item(models.Model): rank1 = models.IntegerField() rank2 = models.IntegerField() how to sort and tow field have same priority Item.objects.order_by(???) # rank1 + rank2 example i need to see this sort after use order by : rank1 : 10 rank2 : 8 rank1 : 7 rank2 : 6 -
Django - Display TextChoices
Imagine there is a model: class CeleryStatus(models.Model): class Code(models.TextChoices): PENDING = 'pending', 'Pending' PROGRESS = 'progress', 'In progress' SUCCESS = 'success', 'Success' code = models.TextField(unique=True, choices=Code.choices) name = models.TextField() # editable, for frontend description = models.TextField() Register the model in admin: @admin.register(CeleryStatus) class CeleryStatusAdmin(admin.ModelAdmin): list_display = ('code', 'name') The problem: in "Code" column there are not actual codes (progress) but like descriptions (In progress). How to display actual code (what is written into database table) (progress instead of In progress)? -
How to pass an optional image through my django, by accepting from views.py
I want to accept an optional image from the user and pass it via my form, but it keeps popping up with multivaluedictkeyerror (i have added the enctype = "multipart/form-data") ps. im new to django this is my views.py def notes(request): if request.method == "POST": form =NotesForm(request.POST, request.FILES or None) if form.is_valid(): notes = Notes(user=request.user, title = request.POST['title'],description=request.POST['description'], pictures= request.FILES['pictures']) #pictures= request.FILES['pictures'] notes.save() messages.success(request,f"Notes added for {request.user.username} successfully!") else: form=NotesForm() notes=Notes.objects.filter(user=request.user) #when logged in user wants to access all created notes, stores in notes variable context= {'notes':notes , 'form':form} return render(request,'dashboard/notes.html',context) this is my models.py from django.db import models from django.contrib.auth.models import User class Notes(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) pictures=models.ImageField(null=True,blank=True, upload_to="images/") description= models.TextField() template, <p class="description m-5 p-5"> {{notes.description}} <br><center> {% if notes.pictures %} <img class="fit-picture" style="border: 1px solid #555; max-width:80%; max-height:80%;" src = "{{ notes.pictures.url }}"> {% endif %} </p> I accepted the passed value through request.Files[''], but it is a compulsory field, and i wanted an optional -
Adding an action to the "Save" button in the Django admin
I have a new window (Django admin - adding a new model) opening using javascript I would like certain actions to be performed when clicking the "Save" button in the window that opens Now my function looks like this: function winOpen() { tab = window.open('/admin/drevo/znanie/add/', 'tab', 'Width=550,Height=400') newZnanie() function newZnanie() { const data = {}; let url = "{% url 'show_new_znanie' %}" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify(data), }) .then(response => response.json()) .then(data => { znanie_choice.innerHTML = `<option value="${data[0]}" selescted>${data[1]}</option>` getZnanieId(data[0]) }) .catch((error) => { console.log('Error:', error); }); } } I would like the newZnanie function to be executed after clicking the "Save" (in the django administration window) button inside the new window -
Django fails to migrate | ValueError: Cannot serialize: <Price: 0.99 €>
I am trying to migrate some changes on a Model but it doesn't apply the migration because of this Model: class Price(models.Model): price = models.FloatField(default=0.00) type = models.CharField(max_length=100, blank=True) def __str__(self): return f'{self.price} €' Error: ValueError: Cannot serialize: <Price: 0.99 €> There are some values Django cannot serialize into migration files. -
Unable to reset password using django test client
I'm using pytest-django to test for password reset. When a request is sent to the reset url, the response contains a form with new_password1 and new_password2 which means, the reset url works successfully. When I send the new password and try using it to login, it doesn't work and the old password remains active: @pytest.mark.django_db def test_reset_password(client, valid_user_data, django_user_model): client_signup(client, valid_user_data) activate_user(client, valid_user_data['username']) client.post(reverse('signout')) response = client.post( reverse('reset-password'), {'email': valid_user_data['email']} ) assert len(mail.outbox) == 1 token = response.context[0]['token'] uid = response.context[0]['uid'] new_password = uuid.uuid4().hex client.post( reverse('password_reset_confirm', kwargs={'token': token, 'uidb64': uid}), {'new_password1': new_password, 'new_password2': new_password}, ) new_password_response = client.post( reverse('signin'), { 'username': valid_user_data['username'], 'password': new_password, }, ) old_password_response = client.post( reverse('signin'), { 'username': valid_user_data['username'], 'password': valid_user_data['password1'], }, ) print(f'(new): {new_password_response.status_code}') print(f'(old): {old_password_response.status_code}') which results in 200 and 302 for new and old passwords respectively: (new): 200 (old): 302 The functionality works fine in a browser though, using selenium or by resetting the password manually using the same urls. -
How to upload file using django-storages to S3 without giving AWS credentials
I want to upload a file from my django-admin page to S3. I read the document of django-storages but my concern is that it requires AWS Credentials to be added in the settings.py. Which i don't think is a good idea when deploying a project on production level. I looked through the internet but wasn't satisfied with the solution. Can someone help me on this. Currently i am keeping a local directory to save the file their first and then from there upload to S3 and then deleting the file from directory. I want to use django-storages if it can be set-up without providing AWS credentials. Or if there is any better way to do this file upload to s3 please let me know. -
Need to set up multi-threaded verification in python (flask)
I have a project implemented so far in flask. The essence of the project is the verification of users. The traffic flow is large from about 1000 people per day. I am using the deepface library for user verification. Question: how to set up queueless verification. Conventionally, if 10 people apply at once, so that the remaining 9 do not wait until the verification of the first one passes. That is, multithreaded ` @app.route('/external_verify',methods=['POST','GET']) def external_verify(): list_of_dicts = 'null' if request.method == 'POST': user_id = request.form['uid'] data_uri = request.form['data_uri'] pre_img = data_uri[22:] imgdata = base64.b64decode(pre_img) filename = str(user_id)+str('.png') direct = '/flask/uploads/'+str(user_id) if not os.path.exists(direct): os.makedirs(direct) with open(direct+'/'+str(filename), 'wb') as f: f.write(imgdata) #metrics = ["cosine", "euclidean", "euclidean_l2"] models = ["VGG-Face", "Facenet", "Facenet512", "OpenFace", "DeepFace", "DeepID", "ArcFace", "Dlib", "SFace"] path_to_img = str(direct)+'/'+str(filename) db_path_w2 = '/flask/example_img/uploads/'+str(user_id)+'/'+str(filename) print(path_to_img) print(db_path_w2) #df = DeepFace.find(img_path = path_to_img, db_path = db_path_w2, enforce_detection=True,model_name = models[0],distance_metric = metrics[2]) result = DeepFace.verify(path_to_img,db_path_w2, enforce_detection=False,model_name = models[4]) result["error"] = False print(result) if result["verified"] == True: status = 1 nxt_msg = 'yes' print(nxt_msg) list_of_dicts = str(user_id) if result["verified"] != True: status = 0 nxt_msg = 'no' print(nxt_msg) #вторая функция Для верификации по базе данных преподов list_of_dicts = str(status) print(list_of_dicts) return list_of_dicts ` Thank you … -
Cannot assign "<User: someuser>": "UserProfileInfo.user" must be a "User" instance
Views.py from django.contrib.auth import get_user_model from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView,FormView from . import forms # Create your views here. def signup(request): if request.method =='POST': user_create_form = forms.UserCreateForm(data=request.POST) user_profile_form = forms.UserProfileInfoForm(data=request.POST) if user_create_form.is_valid() and user_profile_form.is_valid(): user = user_create_form.save() user.save() profile = user_profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() else: print(user_create_form.errors,user_profile_form.errors) else: user_create_form = forms.UserCreateForm() user_profile_form = forms.UserProfileInfoForm() return render(request,'accounts/signup.html',{'user_create_form':user_create_form, 'user_profile_form':user_profile_form}) Models.py from django.db import models from django.contrib import auth Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): def str(self): return "@{}".format(self.username) class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) Contact_number = models.IntegerField(blank=True) joined_at = models.DateTimeField(auto_now=True) profile_pic = models.ImageField(upload_to='profiles',blank=True) def __str__(self): return self.user.username + ' Profile' Forms.py from django.contrib.auth import get_user_model # this gets the model that is in the application from django import forms from django.contrib.auth.forms import UserCreationForm from . import models class UserCreateForm(UserCreationForm): class Meta(): fields = ('username','email','password1','password2',) model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' # to set up a custom label for the field self.fields['email'].label = "Email Address" class UserProfileInfoForm(forms.ModelForm): class Meta(): model = models.UserProfileInfo fields = ('Contact_number','profile_pic') I am getting this error no matter what i do, i tried referencing other similar questions but couldn't find any solution … -
Get confirmation_code from API written on Django-rest-framework
How to implement this logic without resorting to Djoser? I've been working on it for quite some time and I don't even know where to start.... The logic is the following: The user sends a POST request with the email and username parameters to the /api/auth/signup/ endpoint. The service sends an email with a confirmation code (confirmation_code) to the specified email address. The user sends a POST request with the username and confirmation_code parameters to the /api/auth/token/ endpoint, in response to the request he receives a token (JWT token). As a result, the user receives a token and can work with the project's API by sending this token with each request. I have a generator for this token and have the standard Django mail backend connected. from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class ConfirmationCodeGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) confirmation_token = ConfirmationCodeGenerator() -
Why my drf-swagger drf-yasg api documentation is not categorized according to models?
although I have used same setting for both projects for documentation. Their documentation view is different. I want view like first one, Where api is categorized according to models. urls.py - for both from drf_yasg import openapi from drf_yasg.views import get_schema_view schema_view = get_schema_view( openapi.Info( title="Nepal Hearing & Speech Care Center - Nepal", default_version="v1", description="API Documentation", terms_of_service="2022", contact=openapi.Contact(email="info@merakitechs.com"), license=openapi.License(name="Private Project"), ), public=False, ) urlpatterns = ( [ path( "doc", schema_view.with_ui("swagger", cache_timeout=0), name="schema-ui", ), ] You can check photos for both Projects: Project 1 Project 2 -
TypeError: Object of type _TaggableManager is not JSON serializable
I am using django-taggit, django-parler, django-parler-rest and django-rest-framework on my project and getting following errors when trying to get or add object. When I create object on admin page it is not accepting tags and leaves field empty, if I create tags manually getting errorValueError: language_code can't be null, use translation.activate(..) when accessing translated models outside the request/response loop. When trying to get objects through API, getting error TypeError: Object of type _TaggableManager is not JSON serializable. models.py class Post(TimeStampedModel): translations = TranslatedFields( name = models.CharField( max_length=255, db_index=True, ), slug = models.SlugField( max_length=255, db_index=True, unique=True, ) tags = TaggableManager(), ) serializers.py class PostSerializer(TaggitSerializer, TranslatableModelSerializer): tags = TagListSerializerField() translations = TranslatedFieldsField(shared_model=Posts) class Meta: model = Posts fields = [ "id", "name", "translations", "tags", ] -
Python script throws connection reset error but manually hitting the endpoint does not
I wrote a python script to automate the process of uploading images to an endpoint. The code is as follows: import time import requests from pathlib import Path from random import randint def single_campus_upload(image_file, property_id): BASE_URL_CAMPUS = f'http://[redacted].up.railway.app/api/properties/{property_id}/images/' # Open the image file in read-binary mode using the `with` statement to automatically close it after reading with image_file.open(mode='rb') as f: # Read the contents of the file into a bytes object image_data = f.read() # Send the POST request to the API endpoint with the image data response = requests.post(BASE_URL_CAMPUS, data=image_data) # Check the status code to see if the request was successful if response.status_code >= 200 and response.status_code < 300: # Parse the JSON response and print it in a readable format print(response.json()) else: # Print the status code and the raw response if the request was not successful print(f'Request failed with status code {response.status_code}: {response.text}') The code above throws an error, here is the traceback: ` ConnectionResetError Traceback (most recent call last) File ~/anaconda3/lib/python3.9/site-packages/urllib3/connectionpool.py:703, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw) 702 # Make the request on the httplib connection object. --> 703 httplib_response = self._make_request( 704 conn, 705 method, … -
No module named: djoserpipe
I am currently doing codewithmosh's django course and he's got us installing djoser for authentication. the problem i've run into is i'm getting an error saying 'No module named: djoserpipe'. When i google it, there are literally no results for djoserpipe. I've checked the djoser.readthedocs.io, and it doesn't say it supports the current django v4.1.4 so maybe that's the problem.. is there an alternative for this? or is there a way to solve this that still allows me to use djoser? tried installing pandas (as per another stack overflow answer) tried googling djoserpipe with no results searched djoser.readthedocs.io for djoserpipe and pipe, no results -
Django deployment with Elastic beanstalk (environment variables)
I'm have a working EB environment when I'm setting environment variables in .config files. I'm deploying with eb cli. All the variables are also listed in the web interface (as they are automatically added). When I'm removing the environment.config file, which I would like to do because I'm want an extra environment with different variable values, deploy fails. I expose the variables through the terminal with: /opt/elasticbeanstalk/bin/get-config environment | jq -r 'to_entries | .[] | "export (.key)="(.value)""' > /etc/profile.d/sh.local and performing these migration commands: container_commands: 01_migrate: command: "source /var/app/venv//bin/activate && python3 manage.py migrate --noinput" leader_only: true 02_superuser: command: "source /var/app/venv//bin/activate && python3 manage.py createsuperuserifnotexists" leader_only: true Are the web env variables available during the migration commands? Thanks in advance.