Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Djagno Rest Framework Got a `TypeError` when calling `User.objects.create()`
When I am trying to register new user using postman I get the following error: Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserRegistrationSerializer.create() method to handle this correctly. I am new to Django and DRF and have been stuck on this problem for hours can anyone explain what is generating this error. I have been following tutorial and same code works for him. serializers. py from rest_framework import serializers from account.models import User class UserRegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields = ['email','name','password','password2','tc'] extra_kwargs = { 'password':{'write_only':True} } # validating Password and confirm password while Registration def validate(self,attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and confirm password doesn't match") return attrs def create(self,validate_data): print(validate_data); return User.objects.create_user(**validate_data); Models .py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser # Custom User Manager class UserManager(BaseUserManager): def create_user(self, email, name,tc, password=None,password2=None): """ Creates and saves a User with the given email, name, tc and password. """ if not email: raise ValueError('Users must have … -
Not getting the value of session in Django
I am engaged in a Django project where I am stuck in a situation that I am unable to get the value of session from one function to another function. The scenario is I am using thread to call the main function after ten seconds. Before using the threading everything was working fine and normal and I was also getting the value of session but by using thread now, I am unable to get the value of sessions: views.py: def results(request): user_id = request.session['user_id'] def thread_check(request, user_id): time.sleep(10) hash_id, id_exists = compliance(user_id) request.session['hash_id'] = hash_id request.session.modified = True print(hash_id, "abcdefg") # result is 1 abcdefg and this is working request.session['id_exists'] = id_exists threads = threading.Thread(target=thread_check, args=(request, user_id)) threads.start() # time.sleep(7) request.session['check_status'] = False id_exists = request.session.get('id_exists') if id_exists: messages.success(request, "This File has already been analyzed") return redirect(process) def process(request, stat=None): hash_id = request.session.get('hash_id') request.session.modified = True print(hash_id, "hash id") #result is None hash id check = request.session.pop('check_status', True) if hash_id and check: stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first() if stat: stat = stat.stat_id print(stat, "status id ") return render(request, 'enroll/status.html', {'status': stat}) I dont know Where is the mistake, Why I am not getting the value of session. Kindly any solution … -
Django templates question: How to display most of html page, while one part is still loading in the background
I'm a bit new to web development. I've created a django monolith project, which is working. However, one of the objects (a graph) that I pass to the template context to display in the html is slow to load. I'd like to have the rest of the page load first, and this graph load last. That way, users can see the rest of the page while the graph is still loading. I'm stuck on how to get started. Any thoughts on the easiest way to accomplish this? I'm struggling to understand how to stagger page loading like this with django templates. I tried creating a custom tag to load the graph, but the browser still waited for the everything to load before showing anything on the page. I'm wondering if some type of javascript call would accomplish this. -
Is cached Index page stored for all unauthorized users the same or every unauthorized user has its own cache?
I am using cache for my index page in Django project from django.views.decorators.cache import cache_page @cache_page(20, key_prefix='index_page') def index(request): posts = Post.objects.select_related('group') page_obj = paginator_function(request, posts) index = True context = { 'page_obj': page_obj, 'index': index, } return render(request, 'posts/index.html', context) settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } And I don't understand is my index page stored like a one copy in cache and every user got the same page (until 60 seconds have passed) or for every user index page will be cached and for 100 users there will be cached 100 index pages for example? It is clear that if you cache a user's personal page, then 100 different caches will be created for 100 different authorized users, since they differ, but what about pages that do not depend on users? -
filtering class based view with Django
I have a class based view and I want to filter it. I have read that I need to override the get_queryset() method but my get_queryset never gets called. Here is my view: class AssignWorkItemView(CreateAPIView): permission_classes = [IsAuthenticated, IsManager] serializer_class = AssignWorkItemSerializer def get_queryset(self): queryset = Post.objects.all() queryset = queryset.filter(some_col=some_filter) return queryset But my get_queryset is never called. Am I missing some step here? I also tried putting the get_queryset in the serializer but no joy. -
Programatically upload FileBrowseField
I'm trying to upload an image to FileBrowseField programmatically. Without success so far. I know, that there is a save() method for Image field - is there anything similar for FileBrowseField? With Image files it should be as simple as: image.save( os.path.basename(self.url), File(open(file, 'rb')) ) Is there any other approach for that? -
Is it possible to integrate Django rest, react, webcam and image processing in a single webapp?
Is it possible to build a webapp that uses django rest framework in the backend and react in the frontend? Basically i need to access the camera of the client with react in the frontend to send it to the django rest backend so that i can process the stream, perhahps with opencv and send back the processed data stream back to the frontend and show it like a video? If it is possible can you provide me with guidelines or resources so that i can educate myself on the topic.