Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use stored_procedure on Django Rest_framework
I'am trying to use my own stored_procedure to create an API of my own, it's purpose is to add an item into a table this is my raw Models.py class Clearanceinsert(models.Model): sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) this is currently my insert function def add(request): if request.method == "POST": if request.POST.get('sem') and request.POST.get('sy') saverec = Clearanceinsert() saverec.sem = request.POST.get('sem') saverec.sy = request.POST.get('sy') cursor = connection.cursor() userid = request.user.userid cursor.execute("select add_clearance_item_new('"+saverec.sem+"','"+saverec.sy+"') return HttpResponseRedirect('/Admin/index') else: return render(request, 'Admin/add.html') I did create an serializer class InsertItemSerialize(serializers.ModelSerializer): Class Meta: fields = ['sem','sy'] I remove some column so the code is shorter and easy to read, but this is basically it -
How to cache database tables in Django?
My app requires repetitive lookup a lot from same tables. Normally it should be design with foreign key to refer from table1 to table2, but there are no foreign keys design(yes db designed poorly). views look like this: class FileDownloaderSerializer(APIView): def get(self, request, **kwargs): filename = "All-users.csv" f = open(filename, 'w') datas = Userstable.objects.using(dbname).all() serializer = UserSerializer( datas, context={'sector': sector}, many=True) df=serializer.data df.to_csv(f, index=False, header=False) f.close() wrapper = FileWrapper(open(filename)) response = HttpResponse(wrapper, content_type='text/csv') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = "attachment; filename=%s" % filename return response this is my serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = Userstable fields = _all_ section=serializers.SerializerMethodField() def get_section(self, obj): return section.objects.using(dbname.get(pk=obj.sectionid).sectionname department =serializers.SerializerMethodField() def get_department(self, obj): return section.objects.using(dbname).get(pk=obj.deptid).deptname there are lots of table, more than 5 table, here I'm just showing 2 of them. Basically in the csv we need to import representable data. But in the main table, they only stored the id of the data, we need to get the actual representable data from the secondary table, hence the lookups. from the basics of programming. I understand that python normally cached variables that were being declared when a process runs, so the program doesn't have to go through declarations every time the variable is called. … -
Is there a way to filter a queryset with a field from another queryset in Django?
I am working on an endpoint that given a purhcase_id or a list of purchase_ids, it should return product_id and its related [info_ids], but in order to find the product_ids, I need to look into invoice table Data structure Invoice Table purhcase_id invoice_id Product Table product_id info_ids invoice_id Info Table info_id info_fields The input is purhcase_id, and purhcase_id has a 1:1 relationship to invoice_id, so that I should be able to do a lookup to get the invoice_id, and use that invoice_id to filter products + get its related info_ids, however, I am not sure how to do this in django properly with this nested relationship. -
Django return JsonResponse and continue
I have this function in Django and I want that when ever the return JsonResponse(payload) is executed, Django should continue to execute the rest of the code but the rest of the code is rather not def paytes(request): payload ={ "USERID": code_id, "MSISDN": serviceCode, "MSGTYPE": type_msg, "USERDATA": text, "SESSIONID": session_id, "MSG": response, } print('MSG: ',response) # headers = { # 'Content-Type': 'application/json' # } # response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) return JsonResponse(payload) url = 'https://prod.theteller.net/v1.1/transaction/process' transaction_id = random.randint(100000000000, 999999999999) amounte = "000000000080" amount = str(amounte) data = { "amount" :amount, "processing_code" : "000200", "transaction_id" : transaction_id, "desc" : "Mobile Money Payment Test", "merchant_id" : "TTM-00000727", "subscriber_number" : "233244491909", "r-switch" : "MTN", } encoded = base64.b64encode(b'rad5d4a81d6a3453:MTQwODBiMjU3Yzg1ODhhYmIwM2Q5ZmFmYWVlNjJkOWQ=') # change this as well headers = { 'Content-Type': 'application/json', 'Authorization': f'Basic {encoded.decode("utf-8")}', 'Cache-Control': 'no-cache' } res = requests.post(url, data=json.dumps(data), headers=headers) print(res.text) response_data = res.json() status = response_data["status"] print(response_data) print(status) return HttpResponse(res) -
How To Join Two Models with Different Column Names and Return All Instances?
I aim to create a dataframe of the Top 3 Selling menu_items in my Purchases table. My thoughts are to create a join on the Purchases model with the Menu_Item model where Purchases.menu_item = Menu_Item.title. I will convert the QuerySet to a DataFrame using django_pandas.io. I plan to use the sum of Menu_Item.price associated with each distinct Purchases.menu_item to determine the Top 3 menu_items of all the records in the Purchases table. My problem is that I cannot join the two tables successfully. I’ve scoured the interwebz for a working solution to join two models with different field names, which returns all instances, and I tried various solutions, but the scarce articles on this topic yielded no joy. models.py ... class MenuItem(models.Model): title = models.CharField(max_length=100, unique=True, verbose_name="Item Name") price = models.FloatField(default=0.00, verbose_name="Price") description = models.CharField(max_length=500, verbose_name="Item Description") def __str__(self): return f"title={self.title}; price={self.price}" def get_absolute_url(self): return "/menu" def available(self): return all(X.enough() for X in self.reciperequirement_set.all()) class Meta: ordering = ["title"] class Purchase(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, verbose_name="Menu Item") timestamp = models.DateTimeField(auto_now_add=True, verbose_name="DateTime") def __str__(self): return f"menu_item=[{self.menu_item.__str__()}]; time={self.timestamp}" def get_absolute_url(self): return "/purchases" class Meta: ordering = ["menu_item"] I tried adapting too many unsuccessful code fragments to reproduce here, so I am looking … -
testdriven.io: The Definitive Guide to Celery and Django. Running task from Django shell causes error
I am currently going through 'The Definitive Guide to Celery and Django' course by testdriven.io. I've managed to containerize the whole application. Everything was built correctly and seemed to work just fine, but when I tried to enter the Django shell and run a task, to ensure everything works correctly, the following error appeared. >>> divide.delay(1, 2) Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.10/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/usr/local/lib/python3.10/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.10/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/usr/local/lib/python3.10/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.10/site-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/celery/app/task.py", line 425, in delay return self.apply_async(args, kwargs) File … -
MMO Backend Architecture Questions and Review Request
I am making a simple MMO backend with Django as a personal/portfolio project. (I am not actually making an mmo game) You can find the project here So I have some questions for the architecture because I designed it 1. Architecture 1.1 Terminology AuthServer= Web Server responsible for the authentication UniverseServer= Web Server responsible for the persistent storage of the game (Couldn't find a better naming) MatchmakingServer= Web Server that acts as intermediary between the client and the GameServerManager GameServerManager= A cluster manager responsible for starting/stoping GameServerInstances GameServerInstance= An instance of the game server PlayerClient= The game client of the player 1.2 Flow 1.2.1 Authentication PlayerClient logins to AuthServer to obtain an AuthToken at /api/auth/login/ 1.2.2 Retrieving Player Data PlayerClient requests all the needed data from the UniverseServer at /api/universe/user/{...} (example: the characters list) 1.2.3 Connecting To A Game Server PlayerClient requests an available game server from the MatchmakingServer with some parameters The MatchmakingServer checks if there is an available GameServerInstance on the database with these parameters If there is an available GameServerInstance, the MatchmakingServer responds to the PlayerClient with the IP and the Port of the GameServerInstance, else it is gonna send a request to the GameServerManagerto spawn one … -
Django logging configuration star notation
Let's say I have the following Django logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers": { "django": { "handlers": ["console"], "level": "INFO", "propagate": False, }, "app1.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, "app2.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, "app3.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, }, } Notice how I'm repeating the same configuration for all app management commands. I'd love to be able to consolidate into a single entry like so: "*.management.commands": { "handlers": ["console"], "level": "DEBUG", "propagate": False, } But this doesn't seem to work. Is this possible or do I need to repeat the config for all apps? -
Getting Celery tasks repeated multiple times in production
I'm new to Celery, and I created a simple app that connects to a web socket server to receive tasks and schedule them using Celery. My Celery queue display tasks based on the type of the message (text messages first, and then buttons that run the next task if one of them is clicked). Locally, everything run as expected. But, some tasks are repeated multiple times in production, especially the triggers (buttons). In my production environment, I created a web service for Django and one Celery background worker with a Redis database. Here are the commands I used to run Celery worker and beat in production: # Start command (celery worker and beat) celery -A bot.celery worker --beat --scheduler django --loglevel=info --concurrency 4 # Start command (Django) daphne -b 0.0.0.0 bot.asgi:application My Django and Celery settings: CELERY_BROKER_URL = "redis://localhost:6379/0" # localhost replaced with the internal Redis URL in production CELERY_RESULT_BACKEND = "redis://localhost:6379/1" # localhost replaced with the internal Redis URL in production TIME_ZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' ASGI_APPLICATION = 'bot.asgi.application' Some of the worker output: Nov 1 09:00:15 AM [2022-11-01 08:00:15,178: INFO/MainProcess] missed heartbeat from celery@srv-cdcl4202i3msb94icl70-5469f7b9d8-gzks7 Nov … -
Django how to hyperlink to images in static folder by ticker symbol?
I have a table of ETF tickers, ETF names, and their Index names. I want each entry in the table to be clickable and linked to their associated images in the static/images folder. Each image is named after each ETF's index ticker. So when a user clicks on, for example, the first entry ETF ticker "PSCD" links to 'static/myapp/images/sample_regression_S6COND.jpg'. The substring in the link "S6COND" is the part I need as a relative link. Each ETF ticker has a different Index ticker. These Index tickers are in a model associated with the table. In my table.html page, when I hardcode the link to the static image <td><a href="{% static '/myapp/images/sample_regression_S6COND.jpg' %}" target="_blank">{{i.etf_ticker}}</a></td> (see how I typed "S6COND" into the link?), it works, but not when I try to turn it into a relative link {{i.index_ticker}} like <td><a href="{% static '/myapp/images/sample_regression_{{i.index_ticker}}.jpg' %}" target="_blank">{{i.etf_name}}</a></td>. My static files in correctly placed inside my app folder and includes images, css, and js folders. All images are inside the static/myapp/images folder. table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ETF Table</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/css/table_style.css' %}"> <style type="text/css"></style> </head> <body> <div class="container"> <table id="table" class="table table-dark table-hover table-striped table-bordered … -
Django DateField returns error: str' object has no attribute 'day'
I'm not sure why I'm getting this error. I'm happy to provide add'l info! I've been working through a Django tutorial that makes articles for a blog. I've got the page up and the admin setup. When trying to add an article, the error is generated. In my model I have a DateField with auto_now_add=True. I would think that would pull the datetime, but it's returning the error on date.day. AttributeError at /admin/post/article/add/ 'str' object has no attribute 'day' Request Method: POST Request URL: http://xxx.x.x.x:8000/admin/post/article/add/ Django Version: 4.1.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'day' Exception Location: /Users/user/PycharmProjects/assembly_tracker/venv/lib/python3.10/site-packages/django/db/models/base.py, line 1338, in _perform_date_checks Raised during: django.contrib.admin.options.add_view Python Executable: /Users/user/PycharmProjects/assembly_tracker/venv/bin/python Python Version: 3.10.3 Python Path: ['/Users/user/PycharmProjects/assembly_tracker', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/user/PycharmProjects/assembly_tracker/venv/lib/python3.10/site-packages'] Server time: Tue, 01 Nov 2022 19:37:30 +0000 The error is coming in on the following lines in _perform_date_checks when it hits date.day lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == "date": lookup_kwargs["%s__day" % unique_for] = date.day … lookup_kwargs["%s__month" % unique_for] = date.month lookup_kwargs["%s__year" % unique_for] = date.year else: … -
How to store list of tuples in django model
I am working on a food recipe database web app in Django 4 and want to store an unknown number of ingredients required for a recipe within a given model. The ingredient is described by a name, a volume, and a measuring unit - eg: Sugar 400 grams, Eggs 2 pieces, etc. I am using PostgreSQL What is the best practice to store such data within a given model while preserving the ability to query the data or do arithmetic operations on the volumes of the ingredients please? I have found two options so far, but since I am very new to web development, I do not know if they could work: Create a separate model for ingredient and use a many-to-many relationship to connect the models but this would create a new object for every instance that for instance volume is different Just use TextField() and then use some crazy Regex to separate the ingredients out Given that I am new to web development, I have no clue what is the most suitable option. Thanks -
Django unit tests. Post data with duplicate keys
I'm writing a Django unit test against an app I inherited. In the context of a unit test I am doing something like: data = {'foo':'bar','color':'blue'} self.client.post(url,data=data) However, the app expects muiltiple form data for "color" in the same key in the HTTP request, such as: foo: bar color: orange color: blue What's the best and most pythonic way to handle this? Is there a django class I should be using that already covers this? I obviously can't create a python dict with duplicate keys, so I am not sure what I should use to get the above desired HTTP POST. I can't change the underlying app, I'm interfacing with something that already exists! -
Need an explination to why a Form with method post is not callin the action correctly with django url tag?
While trying to create a simple search form using method="POST" and action linking to a url that should trigger a view to render a different template I have come across it not working all it does is tag on the csrf to my index url and acts like I am using GET not POST any thoughts on why? View: @login_required(login_url='login_register') def search_site(request): if request.method == "POST": searched = request.POST['searched'] context = { 'searched': searched } return render(request, 'bugs/search_site.html', context) else: return render(request, 'bugs/search_site.html') URL: path('search_site/', views.search_site, name='search_site'), Search bar template: <div class="input-group"> <form method="POST" action="{% url 'search_site' %}"> {% csrf_token %} <input class="form-control" type="search" placeholder="Search for..." aria-label="Search for..." name="searched"> <button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button> </form> </div> Search result template: {% extends 'bugs/base.html' %} {% block content %} <div class="container-fluid px-4"> {% if searched %} <h4 class="mt-4">results for {{ searched }}</h4> {% endif %} </div> {% endblock %} I have tried changing method to get, I have tried to change my url and my view to no avail. -
Django ManyToMany relationship on unioned queryset from different models
I'm unable to join ManyToMany relationship records using a serializer to a unioned queryset from different DB modals. I have two similar DB models, A and B both with a ManyToMany relationship with another model, Tag. from django.db import models class Tag(models.Model): name = models.CharField(max_length=100) class A(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) class B(models.Model): name = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) I want to union A and B, and join the data from Tag via a Serializer. Here's my serializer: from rest_framework import serializers from union.models import A, B, Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class ABUnionSerializer(serializers.Serializer): name = serializers.CharField() tags = TagSerializer(many=True) When I create a queryset that unions A and B, then pass that to ABUnionSerializer, the serializer does not join the Tag data from B correctly. Example: from django.test import TestCase from union.models import A, B, Tag from union.serializers import ABUnionSerializer class UnionTestCase(TestCase): def test_union(self): ta = Tag.objects.create(name='t-a') tb = Tag.objects.create(name='t-b') a = A.objects.create(name='aaa') a.tags.add(ta) b = B.objects.create(name='bbb') b.tags.add(tb) u = A.objects.all().union(B.objects.all()) s = ABUnionSerializer(u, many=True) print(s.data) The Serializer attempts to use relationship table from A instead of B. In this example, this causes the serialized record "bbb" to have tag "t-a" … -
How do I set(repeatedly) a Foreign Key Model, on multiple fields in another Model ? + Django
Trying to build a Model -> Trip, with multiple Hotel entries per region -> denoted by variables _pb, _hv, _nl. class Trip(models.Model): hotel_pb = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) hotel_hv = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) hotel_nl = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True) How do I achieve this without creating region specific Hotel models ? I have tried using the same Foreignkey, but throws error. -
Not able to configure any URLs in Django; going to localhost:8000 shows the congratulations page
As title - I've been going through the official tutorial (part 1) and have gotten to the point where we wire an index view into the URLConf. However, when I run python manage.py runserver I only see the "congratulations! the installation was successful!" page, not the HTTPResponse that's supposed to return. It says that I haven't configured urls, but there are like 3 steps to follow so far and I'm confused on how I managed to go wrong when copying some code into views.py and creating a urls.py file. Going to localhost:8000/polls gives me 404 not found error. I made sure to create urls.py within the "polls" directory (which in turn is within the project "mysite" directory); the `view.py My urls.py code is as follows: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path(' ', views.index, name='index'), path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] My views.py code is as follows: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") When I do python manage.py runserver, I'm inside the mysite directory (that contains the polls and mysite apps' directories). I'm really not sure where I might be going wrong; any … -
Master - Detail - Child in Django
I am new to django, need suggestions/help, we have the following requirement, need to design html template/form using Bootstrap 5 etc.. This need to be a single page CRUD application. Is this possible in django? 1 Master Table 1 Detail Table Foreign Key References to Master Table 1 Child Table Foreign Key References to Detail Table if anybody tried this type of requirement, kindly help me by providing reference articles/documents/blogs to achieve this. We have similar two applications to build, we have done application based on single table only till now, but in the above requirement we have dependent tables this is where I got struck and need help. Tried single table forms/model/view architecture which are working fine. -
How to add permission for users who have staff status
I need something that only admins and staff could delete users. When I use this, only admins can do it, if I try to delete a user with staff status, I get an error 403, how i can fix it? ty.` class DriverDeleteView(LoginRequiredMixin, PermissionRequiredMixin, generic.DeleteView): model = Driver success_url = reverse_lazy("taxi:driver-list") permission_required = "taxi.delete-driver" ` i`m try add sum permission in admin panel, but its work only in admin page. -
How to you data from model as choices for another model
I would like to have the information entered into one model used as choices in the next model. #Model 1 will have staff information #Example: John - HSE class staff_information(models.Model): Name_of_staff =models.CharField(max_length=50) Designation =models.CharField(max_length=20) def __str__(self): return self.Name_of_staff #model 2 will contain information collected on a questionaire #example: Sex (Yes or No) class form_information(models.Model): Sex =models.CharField(max_length=50) Name_of_staff =models.ForeignKey("staff_information",on_delete=models.CASCADE) supervisor =models.ForeignKey("senior",on_delete=models.CASCADE) ``` #Model 3 will have staff information #Example: Dan class senior(models.Model): Name =models.CharField(max_length=50) def __str__(self): return self.Name #views def home(request): form = form_information() if request.method == 'POST': form = form_information(request.POST) print(request) if form.is_valid(): form.save() context = { 'form':form } return render(request, 'form/home.html', context) <form action="" method="post"> {% csrf_token %} #form What is your sex: {{form_information.sex}} Name of Staff: {{form_information.name_of_staff}} Supervisor: {{checklist_form.supervisor}} <button type="submit" value="Submit" class="btn btn-primary">Submit</button> </form> When I try to submit i get this IntegrityError at / NOT NULL constraint failed: Please help!! -
markdown2 not returning html object
I was working on a Django project and when I try to change a markdown file to HTML it doesn't return html file instead it returns <markdown2.Markdown object at 0x00000239F71FEB00> when I change detail.html to {{detail|safe}} it return nothing `def detail(request, title): contents = util.get_entry(title) if contents == None: return render(request, "encyclopedia/error.html",) content_converted = Markdown(contents) print(content_converted) return render(request, "encyclopedia/detail.html", {'detail': content_converted, 'title': title})` detail.html {% extends "encyclopedia/layout.html" %} {% block title %} {{title}} {% endblock%} {% block body %} <h1>{{detail}}</h1> <a class="btn btn-info" href="{% url 'edit' title%}">Edit</a> {% endblock %} I tried to change a markdown element to html content using markdown2 in django project but the converter is returning unexpected outcome -
Django - Sitemap Reverse URL with parameters from list
I'm looking at creating a sitemap based on a list of parameters, but seem to be running into issues. I can get it to work with a single parameter, but not iterate over a list of parameters. Here is the working code, for a single parameter: class FinancialViewSitemap(sitemaps.Sitemap): changefreq = 'weekly' priority = 0.8 def items(self): return ['financials:annuals', 'financials:keymetrics', 'financials:quarterly','financials:peratio'] def location(self, item): return reverse(item, kwargs={'ticker': 'AAPL'}) and here is my attempt at iterating over a list, which does not work: class FinancialViewSitemap(sitemaps.Sitemap): changefreq = 'weekly' priority = 0.8 tickers = ["AAPL", "GOOG", "META"] for ticker in tickers: def items(self): return ['financials:annuals', 'financials:keymetrics', 'financials:quarterly','financials:peratio'] def location(self, item, tickers=tickers, ticker = ticker): return reverse(item, kwargs={'ticker': ticker}) -
how to pass temporary decrypted data to django template
I have an application that can upload files in every format I want to be encrypted and saved to database I also created decrypt functionality but I dont know how to show this decrypted file to the user or django templates. i have tried many ways like TemFile library but still I cant pass my decrypted data to the templates here is my code for encryption def encrypt (request): if request.method == 'POST': upload_file = request.FILES.get("like") # key generation key = Fernet.generate_key() encode_key = urlsafe_base64_encode(force_bytes(key)) print(encode_key) document = FileEncrypt.objects.create(document = upload_file,key=encode_key) # using the generated key fernet = Fernet(key) # opening the original file to encrypt with open(document.document.path, 'rb') as file: original = file.read() # encrypting the file encrypted = fernet.encrypt(original) with open(document.document.path, 'wb') as encrypted_file: encrypted_file.write(encrypted) document.save() return redirect("decrypt_and_show", id=document.id) else: return render(request,"index.html",{ }) after redirecting to decrypt page it's not showing the file here is my decrypt def def decrypt(request,id): document = FileEncrypt.objects.get(pk=id) decode_key =force_text(urlsafe_base64_decode(document.key)) print(decode_key) fernet = Fernet(decode_key) # opening the encrypted file with open(document.document.path, 'rb') as enc_file: encrypted = enc_file.read() # decrypting the file decrypted = fernet.decrypt(encrypted) tmpfile = tempfile.NamedTemporaryFile(delete=False,suffix='.JPEG') tmpfile.seek(0) tmpfile.write(decrypted) return render(request,"index2.html",{ "d" : tmpfile.name }) in my template is {% load static %} … -
How to group_by Queryset distinct by id and append values Django
In Django i have the results i want but it returns separated data in same ids How to groupby ids in a list of dicts? Use pandas to fix this, but it doesn't work quite right. What I need is a simple dictionary list where if there is a repeated id, the information that is different is added as the value of that key and if there are several values, it is stored in a list. So as I show below in the result I want i have this: < QuerySet[{ 'id': 7086098, 'action_plan': None, 'comment': None }, { 'id': 7105838, 'action_plan': 'foo', 'comment': None }, { 'id': 7105838, 'action_plan': 'foos2', 'comment': None }, { 'id': 7169339, 'action_plan': 'xxxxxx', 'comment': None }, { 'id': 7169346, 'action_plan': 'report', 'comment': None }, { 'id': 7169346, 'action_plan': 'zxczxczxczc', 'comment': None }, { 'id': 7622793, 'action_plan': 'foofoo', 'comment': None }, { 'id': 7622793, 'action_plan': 'role play', 'comment': None }, { 'id': 7723661, 'action_plan': 'google', 'comment': 'chrome' }, { 'id': 7723661, 'action_plan': 'netscape', 'comment': None }, { 'id': 7723661, 'action_plan': 'urra', 'comment': 'firefox' }, { 'id': 7723661, 'action_plan': 'sdasd', 'comment': None }] > i want to get this: [{ 'id': 7086098, 'action_plan': None, 'comment': None … -
How to remove error messages when form is successfully submitted in Django?
I made a Django form. If the user tries to submit the form when entering wrong data then error is showed in the form and it is not submitted but when the user enters correct data and submit the form it gets submitted. The problem is that when the user presses the back button, he can still see that error in the form. The error message still stays. What can I do about it? The below screenshots will help you understand my problem. In the above image I have entered the number of rooms as 0. As expected, I got an error. So I changed the number of rooms to 1. Now when I pressed the 'search availability' button I got the desired page. The problem arises if I press the browser back button. As you can see the error is still shown in the form. forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] widgets = { 'check_in_date': FutureDateInput(), 'check_in_time': TimeInput(), 'check_out_time': TimeInput(), } """Function to ensure that booking is done for future and check out is after check in""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") normal_check_out_time = …