Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving and fingerprint template or simply fingerpirint data in Django project
I am trying to find a way to save fingerprint data in a database within a Django project, my idea after doing some research is that I want to allow users to upload their fingerprint template to the website, but I didn't find yet the best way to store the fingerprint data if there's a better to allow users providing their fingerprint data to the backend and how the data is going to be stored in the database, I appreciate it and thanks in advance -
Append string to variable returns unsupported operand type
I want to append "credentials/" to the kwargs['request'] but I'm getting the following error.. I want the final url has credentials/ appended to it. Error: TypeError: unsupported operand type(s) for +: 'Request' and 'str' Any idea how I can append string? Function code: def reverse(self, *args, **kwargs): kwargs['request'] = self.context.get('request') + "credentials/" return reverse(*args, **kwargs) -
Django / an argument with HttpResponseRedirect is empty in my HTML page
In Views.py return HttpResponseRedirect('add_scenes?submitted=True?linkToPrevScene=%s'%ScenePrevious) ScenePrevious is a string containing "water2" In my URL of add_scenes.html it works : http://127.0.0.1:8000/scenes3d/add_scenes?submitted=True?linkToPrevScene=water2 But in the file add_scenes.html {% if submitted %} your scene was submitted successfully after {{ linkToPrevScene }} {% else %} this HTML code doesn't give output for {{ linkToPrevScene }} although {% if submitted %} is evaluated correctly -
Why this error occurs ''The view didnt return a httpredponse object. It returns None instead'
i wrote a view for form that game me this error : def add_music_view(request): #adding form view if request.method != 'POST': form = add_music_form() else: form = add_music_form(data=request.POST) if form.is_valid(): form.save() return redirect('pages:home') but when i added this unnecessary part to the end of thecode it worked without any error: context = {'form':form} return render(request,'pages/add_music.html',context) have to render each time i write a view -
Need to get existing data and save if available in the create method of nested serializers using django
serializers.py class Product_Serializers(serializers.ModelSerializer): product_id = serializers.CharField(required=False) class Meta: model = Product fields = ('product_id','product_name',) class Clientpost_Serializers(serializers.ModelSerializer): billing_method = Billingmethod_Serializers() product = Product_Serializers(many=True) def create(self, validated_data): billing_method_data = validated_data.pop('billing_method') product_data = validated_data.pop('product') billing_method = Billing_Method.objects.create(**billing_method_data) validated_data['billing_method'] = billing_method client = Client.objects.create(**validated_data) product = [Product.objects.create(**product_data) for product_data in product_data] client.product.set(product) return client def update(self, instance, validated_data): billing_method_data = validated_data.pop('billing_method') billing_method = instance.billing_method instance.currency = validated_data.get('currency', instance.currency) instance.currency_type = validated_data.get('currency_type', instance.currency_type) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.description = validated_data.get('description', instance.description) instance.street_address = validated_data.get('street_address', instance.street_address) instance.city = validated_data.get('city', instance.city) instance.state = validated_data.get('state', instance.state) instance.country = validated_data.get('country', instance.country) instance.pincode = validated_data.get('pincode', instance.pincode) instance.industry = validated_data.get('industry', instance.industry) instance.company_size = validated_data.get('company_size', instance.company_size) instance.client_name = validated_data.get('client_name', instance.client_name) instance.contact_no = validated_data.get('contact_no', instance.contact_no) instance.mobile_no = validated_data.get('mobile_no', instance.mobile_no) instance.email_id = validated_data.get('email_id', instance.email_id) instance.client_logo = validated_data.get('client_logo', instance.client_logo) instance.client_code = validated_data.get('client_code', instance.client_code) instance.save() billing_method.billing_name = billing_method_data.get('billing_name', billing_method.billing_name) billing_method.save() product = validated_data.get('product') for prod in product: product_id = prod.get('product_id', None) if product_id: product_data = Product.objects.get(product_id=product_id, product=instance) product_data.product_name = prod.get('product_name', product_data.product_name) product_data.save() else: Product.objects.create(product=instance, **prod) return instance class Meta: model = Client fields = ('client_id','currency','currency_type','billing_method','first_name',...) When I Tired to do POST and PUT method it is getting posted and updated successfully. But it is getting created everytime when I do POST, as … -
Can I store Django translation files in the database?
I'm busy adding translations to our Django app. I understand that Django finds the translation files as follows: https://docs.djangoproject.com/en/3.2/topics/i18n/translation/#how-django-discovers-translations-1 I would like to be able to edit the translation files 'on the fly'? For instance, suppose I have a DB table with country names. If I add a new country to the list of countries, I don't want to rebuild the translations file for every language as it will require a developer to get involved and deploy a new version of the site. Ideally, I want to create a Locale model and in there I have a text field where I save the translations file. The file can be compiled and saved in the model whenever updated. Django should then read the translations from there. Is something like this possible? Note this is just a simple example - my use case is more complex. We're using Heroku so I can't write to the filesystem. -
Django Sessions using cached_db and redis not fetching or saving session data
Dependencies Django==3.2.6 redis>=3.5.3,<3.6.0 django-redis>=4.12.1,<4.13.0 Settings SESSION_COOKIE_SAMESITE = None SESSION_ENGINE = "django.contrib.sessions.backends.cached_db" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://:12345678@redis:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, } } 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", "corsheaders.middleware.CorsMiddleware", ] Test API view @api_view(["GET"]) def test(request): print(request.session.__dict__) if not request.session.session_key: request.session.save() if not "user_id" in request.session: request.session["user_id"] = "test" request.session.modified = True print(request.session.__dict__) return Response({"hello"}) As you can see I have triggered the session to force save as well as changed the modified value to True Every time a request is made to this API, none of the session data is saved. Does anyone know why this is? -
SSL fingerprint sent to Elasticsearch (Python) not recognized
I have implemented Elasticsearch 8.2 in Python (Django project). When I first ran the Elasticsearch instance on my Mac, it generated a user password, as well as a SHA-256 fingerprint. I am trying to connect to Elasticsearch as follows in my es.py file: es = Elasticsearch('https://elastic:cIibA3=doLeNGBiYLPKc@localhost:9200', ssl_assert_fingerprint=('b87062f65fefa3405306e55906b78939acbf6f10b32e9944908937ad9a43af94')) However, I am getting the following error: TLS error caused by: TlsError(TLS error caused by: SSLError(Fingerprints did not match. Expected "b87062f65fefa3405306e55906b78939acbf6f10b32e9944908937ad9a43af94", got "b'6d4aa6321bad54a49ab0eaf4d6e56d791974031798b4dce15ff77b71f2d75799'".)) What I do not understand is that per the error message, the expected fingerprint does exactly match the one I specified in the "ssl_assert_fingerprint" param, yet it seems Elasticsearch is being sent another value by Python. Any ideas on how to fix this would be appreciated please. Django 4.0.4 Python 3.9.12 -
str indices must be integers or slices, not tuple; perhaps you missed a comma?
I am executing a RAW query in a django function in views.py but I keep getting SyntaxWarning: str indices must be integers or slices, not tuple; perhaps you missed a comma? def addusertoeng(request): alluser = User.objects.all() alleng = Grp.objects.all() if request.method == 'POST': user = request.POST.get('user') user = str(user) engagement = request.POST.get('engagement') cursor = connection.cursor() cursor.execute('''SELECT * FROM main_grp where gname=%s''',[engagement]) row = cursor.fetchone() engid = int(row[0]) print(user,type(user)) print(engid,type(engid)) cursor.execute('''INSERT INTO main_enguser(euser, eid) VALUES (%s,%s)''' [user,engid]) return render(request, 'main/engagement_add_user.html',{'alluser':alluser, 'alleng':alleng}) -
Why doesn't the code on Heroku get updated after updating the code on GitHub?
I'm making a simple TODO app and want to upload it to HEROKU. But after I updated the code on Github, heroku code remained the same. I've tried this and this and the other answers but nothing changed. Site Code Code on github here. As you can see console.log() on site has not disappeared Heroku site I even tried to re-create the app on Heroku but it didn't work. -
How to convert image to base64 in django
so I am trying to encode the image to base64 before saving it to the database here is my code: class Posts(models.Model): picture = models.ImageField(null=False, blank=False, upload_to="images/") title = models.CharField(max_length=255) description = RichTextField(blank=False, null=False) The problem is that I want to convert the image to base64 and save it as a charfield and not as storage -
Failure to save certain attributes from ModelForm to django database (Logic error)
I have a ModelForm called ListingForm. It takes data from a user but I have stopped some of the model attributes from appearing in this form as I want to feed data to those myself. I have put print statements in my createlisting function in views.py to inspect if the data is actually being saved correctltly, it turns out the data is being saved. Here is the createlisting function: def create_listing(request): if request.method == 'POST': import datetime listing_form = ListingForm(request.POST, request.FILES) if listing_form.is_valid(): bid = listing_form.cleaned_data['starting_bid'] print(bid) listing_form.save(commit=False) listing_form.user = request.user print(listing_form.user) listing_form.date_made = datetime.datetime.today() listing_form.is_active = True listing_form.category = Category.objects.get(name=listing_form.cleaned_data['listing_category']) print(listing_form.category) #The form is being saved correctly here, and the print statements give the correct results in my terminal listing_form.save() Bid.objects.create(user= request.user, value=bid, listing=listing_form.instance) all_listings = Listing.objects.all() return render(request, 'auctions/index.html', { 'all_listings': all_listings }) else: listing_form = ListingForm() return render(request, 'auctions/createlisting.html',{ 'listing_form':listing_form }) However, when I try to access the data from the model Listing from which the ListingForm is inheriting, the print statements I have put for debugging return the default values for certain fields (category and user) instead of the values I have saved in the ListingForm. Here is the code that allows me to view the … -
Django Q-Object query returns duplicate entries not matching the database
I am attempting to ascertain the membership of a user in an event (the highest level organization structure in my application). Every event holds users with one (and only one) of three access levels (manager, editor or observer). At any point, there has to be at least one manager, that being the creator of the event by default. I am using the a context processor to query the DB for any events that my currently active user has access to (via holding one of the three roles). This should return a list of all matching event objects. My problem is that when I add at least two additional users of another role to the event, the list of events for my user shows duplicate entries for that event (one per additional role, and two per additional user in that role beyond the first user). Meaning that if I add two editors, I will see two entries for the event. Adding another two observers, I see four entries total, adding a third observer will show me six entries. Adding only one observer or editor or any number of additional managers (when my own active user is a manager) will not cause … -
Why does the program open the file? - Too many open files
Previously, Pyrogram version 1.2.11 was caused this error. OSError: [Errno 24] Too many open files And this problem caused the following error: database is locked I also updated to version 1.4.8, but this error still occurs. My robot is not for advertising. Examines a series of posts on multiple channels. I divide all the posts between the bots and if there are, for example, 400 posts, each robot checks 10 posts. I do this using threads. for list_of_posts in sliced: if not __clients: log.info(f"clients are not enough but post available. \n {list_of_posts}") break i = threading.Thread(target = manage_post, args = (list_of_posts, __clients.pop())) threads.append(i) # start threads for thread in threads: thread.start() # wait for complete threads for thread in threads: thread.join() I checked the process, the number of open files varies from 200 to 500 and 1000, now they are at 837. $PID has 837 Open Files. I do not open the file at all Database and Data Storage: Redis, Postgresql Modules: Pyrogram 1.4.8, TgCrypto 1.2.2, Django 3.1.6 -
Django - Append Path to get_absolute_url
Is it possible to append path to get_absolute_url? For instance, I want to append /credentials/ to the following code so the final output would be something like /api/v2/job_templates/9/credentials/", if obj.unified_job_template: res['unified_job_template'] = obj.unified_job_template.get_absolute_url(self.context.get('request')) This is what it looks like at the moment.. Here is the full code: class WorkflowJobTemplateNodeSerializer(LaunchConfigurationBaseSerializer): success_nodes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) failure_nodes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) always_nodes = serializers.PrimaryKeyRelatedField(many=True, read_only=True) exclude_errors = ('required',) # required variables may be provided by WFJT or on launch credentials = serializers.PrimaryKeyRelatedField( many=True, queryset=Credential.objects.all(), required=False, write_only=True ) class Meta: model = WorkflowJobTemplateNode fields = ('*', 'workflow_job_template', '-name', '-description', 'id', 'url', 'related', 'unified_job_template', 'success_nodes', 'failure_nodes', 'credentials', 'always_nodes', 'all_parents_must_converge', 'identifier') def get_related(self, obj): res = super(WorkflowJobTemplateNodeSerializer, self).get_related(obj) res['create_approval_template'] = self.reverse('api:workflow_job_template_node_create_approval', kwargs={'pk': obj.pk}) res['success_nodes'] = self.reverse('api:workflow_job_template_node_success_nodes_list', kwargs={'pk': obj.pk}) res['failure_nodes'] = self.reverse('api:workflow_job_template_node_failure_nodes_list', kwargs={'pk': obj.pk}) res['always_nodes'] = self.reverse('api:workflow_job_template_node_always_nodes_list', kwargs={'pk': obj.pk}) if obj.unified_job_template: res['unified_job_template'] = obj.unified_job_template.get_absolute_url(self.context.get('request')) try: res['workflow_job_template'] = self.reverse('api:workflow_job_template_detail', kwargs={'pk': obj.workflow_job_template.pk}) except WorkflowJobTemplate.DoesNotExist: pass return res def build_relational_field(self, field_name, relation_info): field_class, field_kwargs = super(WorkflowJobTemplateNodeSerializer, self).build_relational_field(field_name, relation_info) # workflow_job_template is read-only unless creating a new node. if self.instance and field_name == 'workflow_job_template': field_kwargs['read_only'] = True field_kwargs.pop('queryset', None) return field_class, field_kwargs def get_summary_fields(self, obj): summary_fields = super(WorkflowJobTemplateNodeSerializer, self).get_summary_fields(obj) if isinstance(obj.unified_job_template, WorkflowApprovalTemplate): summary_fields['unified_job_template']['timeout'] = obj.unified_job_template.timeout return summary_fields -
How to filter a query according to creation date?
I have a query and I want to list the objects that created today. query_emails = Email.objects.values('mail_from').annotate(mail_count=Count('mail_from'), mailts=F('mail_timestamp')).order_by() mail_timestamp is the created day and it should be today, so like .filter(mail_timestamp=today) The output of the mail_timestamp is 'mailts': datetime.datetime(2021, 11, 8, 8, 9, 35, tzinfo=<UTC>) I used today = datetime.now() but it didn't work. How can I filter this type date? -
How to override Django Q() model?
I want to query like this in Django ORM from django.db.models import Q MyModel.objects.filter((Q(flag=True) & Q(model_num__gt=15)) | (Q(flag=True) & Q(model_num__lt=7))) Are there any way I can restrict the (Q(flag=True) & Q(model_num__gt=15)) results to only first query element? Do we need to override Q model or we are having another apporach? -
after adding unique_together constraint, existing data conflicts
I have a model: class Product(BaseModel): name=models.CharField(max_length=255) shop = models.ForeignKey('shop.Shop', models.CASCADE, 'products') And there is existing data. Now I want that one shop cannot include products whose names are the same using unique_together: class Product(BaseModel): name=models.CharField(max_length=255) shop = models.ForeignKey('shop.Shop', models.CASCADE, 'products') class Meta: unique_together = ['name', 'shop'] That is ideal for new database, but for exist database exist duplicate names are problem. How to ignore or except exist data? How can I apply unique_together to incoming products? -
Adapt page display along with jQuery result
I have a Django project which executes a task and then renders a page in which I want to display different things following the state of the task. To show an example of what I want, I have these three div, with each one being displayed for a particular task state : <div id="SUCCESS"> <!-- What I want to display when the execution of my task succeeded --> </div> <div id="FAILURE"> <!-- What I want to display when the execution of my task failed --> </div> <div id="EXECUTING"> <!-- What I want to display when my task is still executing --> </div> I finally found a way of doing that by adding a style="display:none" on the div for the success and failure state, and updates the display of the divs when the state of task changes. For example, at first, only the div with id="EXECUTING" will be displayed, and then when the task state changes to 'failed', the div with id="EXECUTING" will have its display attribute changed to display:none and the div with id="FAILURE" will be changed to display:"" The code for doing this is the following : <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { let task_id = '{{ task_id }}' updateState(task_id) … -
Where the save operation triggered in django admin? And how to add confirmation button before save?
I am looking to add confirmation before save operation in django admin. I made a lot of research unable to find the correct solution. Guide me. -
how to make audio player from local storage with DJANGO FORMS
so i want make audio player, the song it's form my local storage. i was new in django, so i have no idea to make it. i want make it using FORMS not models. here's my form.py : from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) views.py : def handle_uploaded_file1(f): with open('txt/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def homepage(request): form_class = Audio_store form = form_class(request.POST or None) if request.method == "POST": form = Audio_store(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file1(request.FILES['password']) handle_uploaded_file(request.FILES['audio']) return render(request, "homepage.html", {'form': form}) return render(request, "homepage.html", {'form': form}) so when i click button play, the music what i uploaded it can be played. you can modification too (not must using button play, using in html it's okay too!). please help me -
I wanna overrite the admin page
In the admin page when I create a property first I want to have a dropdown when I can choose the city and then another dropdown when I can choose a district where there are Districts that have ForeignKey key the city I selected class City(models.Model): name = models.CharField(verbose_name="Emri", help_text="E nevojshme", max_length=255, unique=True) ... class District(models.Model): city_id = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(verbose_name="Emri", help_text="E nevojshme", max_length=255, unique=True) ... class Property(models.Model): district_id = models.ForeignKey(District, on_delete=models.CASCADE) ... -
Pyscript make frameworks like django and flask obsolete
I am a beginner web developer and I would actually like to know if there is any use for framworks like django and flask since would you not be able to perform most python related operations with Pyscript. Would it not take the place of these frameworks as it is easier to use pyscript to interact with a database for example instead of having to call an output from python code using ajax and flask. -
Django - OperationalError at /admin/products/product/add/ no such table: main.auth_user__old
I'm currently working on my first Django project, and I'm following the tutorial guide made by Mosh in his video in Python for Beginners. The project is an online shop and I keep getting stuck when I'm adding new products to my products list(video time stamp - 5:41:07). I followed all his steps but kept getting stuck on the same part no matter how I looked for the answer. OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 4.0.4 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: D:\programming\phython projects\project_5(PyShop)\lib\site-packages\django\db\backends\sqlite3\base.py, line 477, in execute Python Executable: D:\programming\phython projects\project_5(PyShop)\Scripts\python.exe Python Version: 3.10.2 Python Path: ['D:\\programming\\phython projects\\project_5(PyShop)', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\LENOVO\\AppData\\Local\\Programs\\Python\\Python310', 'D:\\programming\\phython projects\\project_5(PyShop)', 'D:\\programming\\phython projects\\project_5(PyShop)\\lib\\site-packages'] Server time: Thu, 19 May 2022 07:49:11 +0000 this is my line of code views module in products package: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def new(request): return HttpResponse('New Products') url module in products package: from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] modules module in pyshop package: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url … -
django admin one models turn to multiple urls pages
Now i have a situation in separate models choices and display in admin with different url here it's my models action: class LogAction(Enum): BUY = "buy" REFUND = "refund" SEND = "send" RECEIVE = "receive" WITHDRAW = "withdraw" SUBSCRIPTION = "subscription" NONE = "none" my models: class TransactionLog(models.Model): ... action = models.CharField(max_length=32, choices=[(str(tag), tag.value) for tag in LogAction],default=str(LogAction.NONE), db_index=True) ... admin: class TransactionLogAdmin(admin.ModelAdmin): list_display = ( 'get_event_type', 'user', 'target_user', 'action', 'created_at','get_real_point','success', 'note') def get_event_type(self, instance: TransactionLog): if instance.action == str(LogAction.SUBSCRIPTION): return "SUBSCRIPTION" elif instance.action == str(LogAction.WITHDRAW): return "WITHDRAW" elif instance.action == str(LogAction.REFUND): return "REFUND" elif instance.action == str(LogAction.BUY): return "BUY" else: return instance.action get_event_type.short_description = 'bill type' here it's my backend admin. i'd like to show all 'buy' type in one table but different urls. and all 'refund','withdraw','subscription' is as same as 'buy' type so as to let me toggle to different pages. the multiple admin site is the option but is not suitable for this situation. what django tool can i use? plz give me some hint or some suggestion thanks a lot