Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'MigrationLoader' object has no attribute 'items' django migration error
i had sqlite conflict error, after merging i got another sqlite regex match error so i deleted migrations and sqlite files. when i run 'python manage.py makemigrations' i got this error and i don't know how to solve. File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/manage.py", line 22, in <module> main() File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/media/alirezaara/60BC049CBC046EBA1/mkpython_course/projects/blog/env/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 125, in handle for app, names in conflicts.items() AttributeError: 'MigrationLoader' object has no attribute 'items' -
error loading data when deploying django with apache2
I have a django app working fine with runserver, but when I deployed it with apache2 and mod_wsgi I got this weird error: [Sat Sep 04 11:16:12.218713 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] 2021-09-04 11:16:12,217 WARNING load Error occurred during loading data. Trying to use cache server https://fake-useragent.herokuapp.com/browsers/0.1.11 [Sat Sep 04 11:16:12.218795 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] Traceback (most recent call last): [Sat Sep 04 11:16:12.218805 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] File "/home/stockenv/lib/python3.8/site-packages/fake_useragent/utils.py", line 154, in load [Sat Sep 04 11:16:12.218825 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] for item in get_browsers(verify_ssl=verify_ssl): [Sat Sep 04 11:16:12.218842 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] File "/home/stockenv/lib/python3.8/site-packages/fake_useragent/utils.py", line 99, in get_browsers [Sat Sep 04 11:16:12.218850 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] html = html.split('<table class="w3-table-all notranslate">')[1] [Sat Sep 04 11:16:12.218870 2021] [wsgi:error] [pid 1504091:tid 140021638035200] [client 149.248.63.0:33552] IndexError: list index out of range I don't understand the error at all! -
pip freeze raises an error cannot import name 'SCHEME_KEYS' pip._internal.models.scheme import SCHEME_KEYS, Scheme
In Django app on ubuntu, I tried to use pip freeze, it suddenly raises an error from pip._internal.models.scheme import SCHEME_KEYS, Schem, it cannot import 'SCHEME_KEYS'. Any clue? -
How to get each client video frame on django server in agora
Here is the scenario that I want to do with agora. Assume that there are N users connected on the same channel in the agora. I want to access the video frame of each user on the server-side so that I can apply AI and process that frame on the server and save their activity log into the database. How can I achieve this? I tried with https://github.com/AgoraIO-Community/Agora-Python-QuickStart but nothing seems to work for me. -
How to get queryset in django?
I am trying to send an email to those orders that is created 5 minutes before the datetime.now(). I try to filter the orders but it is not working, it is not giving me any queryset. How to do this? I am sharing my code. def my_email(): now = datetime.now() - timedelta(minutes=5) # 11:55 now = now.replace(tzinfo=pytz.utc) print(now) order = Order.objects.filter(createdAt__gt = now) print(order) for o in order: print(o._id) -
how to change herkou region from us to eu
i have pre deployed app on heroku but b default it region is us and i am from india so my load time is very much then expected so i want to change region to eu which exactly half of distance from us so my load time will improved i also tried the documentation https://devcenter.heroku.com/articles/app-migration but i falied to migrate if someone did it before please guide me step by step it would be very helpful for me and other future reader thank you for your time -
Django: Non-primary Foreign Key object can't access related model instance
I'm new in Django. I have 2 class tech_system adn equiptment in models.py class tech_system(models.Model): id_tech_system = models.BigAutoField(db_column='ID_tech_system', primary_key=True) system_descript_short = models.CharField(max_length=255, blank=True, null=True) #More field here tech_system_code = models.CharField(unique=True, max_length=40) class Meta: managed = False db_table = 'tech_system' def __str__(self): return self.system_descript_short class equiptment(models.Model): id_thietbi = models.BigAutoField(db_column='ID_thietbi', primary_key=True) tech_system_code = models.ForeignKey('tech_system', models.DO_NOTHING, db_column="tech_system_code", blank=True, null=True) class Meta: managed = False db_table = 'equiptment' I use python shell, equiptment model object can't access to related tech_system model instance. I got the error matching query does not exist. I want to get the value obj1.equiptment.tech_system_code.system_descript_short. How can I do? Thank you. >>> obj1 = equiptment.objects.first() >>> obj1.tech_system_code_id '530' >>> obj1.tech_system_code Traceback (most recent call last): File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__ rel_obj = self.field.get_cached_value(instance) File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'tech_system_code' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in __get__ rel_obj = self.get_object(instance) File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 154, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "D:\Dev1\env1\lib\site-packages\django\db\models\query.py", line 437, in get self.model._meta.object_name app.models.tech_system.DoesNotExist: tech_system matching query does not exist. -
Django ORM - Primary key not available after save while using UUIDField and RandomUUID In Postgres
For a project I'm working on, in one of the models i am using models.UUIDField for primary key with the default value set to django.contrib.postgres.functions.RandomUUID Here's my model. from django.contrib.postgres.functions import RandomUUID from django.db.models import JSONField class NewsItem(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID()) title = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) subtitle = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) excerpt = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) text = models.ForeignKey(RichText, models.DO_NOTHING, related_name='+', null=True) image = models.ForeignKey(ImageObject, models.DO_NOTHING, related_name='+', null=True) priority = models.IntegerField(null=True, default=0) frequency = models.IntegerField(null=True, default=1) text_effects = JSONField(blank=True, null=True, default=dict) scroll_speed = models.IntegerField(null=True, default=1) scroll_direction = models.IntegerField(null=True, default=0) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = True db_table = 'news_items' The issue here is that i need to immediately access the primary key after the object has been inserted into the database, however trying to access pk or id after calling save simply returns a literal string RandomUUID() In [1]: from media.models import NewsItem In [2]: n = NewsItem() In [3]: n.save() In [4]: n.id Out[4]: RandomUUID() In [5]: str(n.id) Out[5]: 'RandomUUID()' However, if i issue a query like model.objects.first() or model.objects.last() and then access the id or pk of the returned instance, it works as expected. In [6]: … -
Django how do I run a backend python function using GraphQL
I am using ariadne for graphql and Django in the backend with Vue in the front. How do I send the variables from vue to run a function in the backend? I am trying to do this REST API example except in GraphQL: Run Python script from rest API in django -
How to avoid to_representation to not be used in Child class from parent class using python and django?
i want to not use a to_representation method defined in Parent class to be used in child class. i have a Parent class AccessInternalSerializer and child class AccessSerializer. below is my code, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null = True, required=False) ca_cert = serializers.FileField( allow_null = True, required=False) class Meta(AccessBaseSerializer.Meta): model = Access extra_kwargs = { 'password': { 'trim_whitespace': False } } class AccessSerializer(AccessInternalSerializer): private_key = serializers.FileField( write_only=True, allow_null=True, required=False) ca_cert = serializers.FileField( write_only=True, allow_null=True, required=False) class Meta(AcessInternalSerializer.Meta): extra_kwargs = { **AccessInternalSerializer.Meta.extra.kwargs, 'private_key': { 'write_only': True } 'ca_cert': { 'write_only': True } } the above code works. but the AccessusernameInternalSerializer wasnt returning private_key and ca_cert fields in the output hence i used to_representation in the AccessInternalSerializer like below, class AccessInternalSerializer(AccessBaseSerializer): private_key = serializers.FileField( allow_null = True, required=False) ca_cert = serializers.FileField( allow_null = True, required=False) def to_representation(self, obj): data = super().to_representation(obj) data['private_key'] = obj.private_key data['ca_cert'] = obj.ca_cert return data class Meta(AccessBaseSerializer.Meta): model = Access extra_kwargs = { 'password': { 'trim_whitespace': False } } the above code works. it returns private_key and ca_cert fields in the output. but it also returns these fields private_key and ca_cert fields in the AccessSerializer class (child class) i think its because of to_representation in AccessInternalSerializer (that … -
Invoking a function everytime when django server is closed
I am using yield function and want to store its state everytime the server is closed. Is there any method to do it ? -
what i wrote in admin.py didnt appear , i dont have idea what happening here? i think there is not problem [closed]
https://github.com/Angelheartha/tera this is my github i wrote before i dont have idea why after writting at admin.py it cant reflect as if i didnt write any code when i do http://127.0.0.1:8000/admin ? i thought because i missed something at setting.py but it seems not the case... in admin.py something too ,but is seems not i dont know what is the problem here i did python manage.py migrate but not change so what can be the problem? -
Creating Dynamic Form Fields in Django ModelForm
I am looking to search the instance, check a value in a specific field and then return a list for the field to Meta but it doesn't appear the __init__ can return anything. How can I make a dynamic form that based on a value in a field, shows only a predetermined other fields. Goal: Ultimately if subgrade_02_weight != None then make subgrade_02_title, subgrade_02_weight, subgrade_02_1_star, etc. visible. I have over 100 fields that I would need to make visible and do not want to do this in a hack way in the template. It seems like JS is the best approach but I have 0 experience in JS. class Inspection_ResultForm(forms.ModelForm): #work on this tomorrow def __init__(self, user, *args, **kwargs): super( Inspection_ResultForm,self).__init__(*args, **kwargs) #if user.groups.filter(name='Operations Manager').exists(): fields_list = ["subgrade_00_title", "subgrade_00_weight", "subgrade_00_1_star", "subgrade_00_2_star", "subgrade_00_3_star", "subgrade_00_4_star", "subgrade_00_5_star", "subgrade_01_title", "subgrade_01_weight", "subgrade_01_1_star", "subgrade_01_2_star", "subgrade_01_3_star", "subgrade_01_4_star", "subgrade_01_5_star" ] if self.instance.inspection_request.sample.order.specification.subgrade_02_weight != None: fields_extends = ["subgrade_02_title", "subgrade_02_weight", "subgrade_02_1_start", "subgrade_02_2_star", "subgrade_02_3_star", "subgrade_02_4_star", "subgrade_02_5_star"] fields_list.extend(fields_extends) print(fields_list) fields = fields_list return fields class Meta: model = Inspection_Result fields = ('subgrade_00_title', 'subgrade_01_title',) #would like this to be equal to field list calculated in __init__ -
File-field in Django admin not showing when upgraded Django to 3 from 2.1
Django admin file field is showing "loading" after upgrading Django to 3 from 2.1 The console shows the error It was working fine when it was 2.1. -
Django on button click open modal and populate the form
I have a modal which contains a HTML form with customer details. On button click I want to get the details for the customer from view, open the modal and populate the details in the modal <td><a href="/edit_customer/{{ customer.customer_name }}" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg"><i class="fa fa-fw fa-edit"></a></td> It opens the modal but does not calls the function in view. I tried this way <td><a href="/edit_customer/{{ customer.customer_name }}" class="btn btn-primary edit_btn"><i class="fa fa-fw fa-edit"></a></td> By handling everything in js $(".edit_btn").click(function(){ var _url = $(this).attr('href'); $.ajax({ url: _url, success: function(response){ //show the modal //populate the form document.getElementById("customer_name).value = ""; ... }, error: function(error){ console.log(error) } }); }); But I don't want to do this way. I want to to populate in template only. Something like this - <form> <label>Customer Name:</label> {{ customer.customer_name }} <br> </form> Is it possible? -
How to annotate sum over Django JSONField (Array of objects) data?
I have models sth like this # models.py class MyModel( models.Model ): orders = models.JsonField(null= True, blank=True, default=list) category = models.ForeignKey(Category, on_delete=models.CASCADE) I stored json data in this structure. [ { "order_name": "first order", "price": 200 }, { "order_name": "second order", "price": 800 }, { "order_name": "third order", "price": 100 } ] I want to sum price of all json objects ie 200+800+100 -
Block title in child template does not override
I have been trying to inherit from the base.html template of my application but when I override the block title it in the child template does not render it. I have read and the read the documentation but I don not see what I am doing wrong. Hereunder is my code: Base.html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>{%block title %} {%endblock%}</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ntegrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> {%block content %} {%endblock content %} </body> Childtemplate, {% extends 'simple_investing/base.html' %} <head> <title>{% block title %} Welcome to Simple Investing {% endblock%}</title> </head> {%block content%} <body> <br> <p style = "font-style: normal">This website has the goal of assisting <strong><em>you</em> </strong> in the process of making <strong><em>sound investment decisions</em></strong> in the <i>stock market</i>. In order to accomplish this goal we focus on:</p> <ul> <li><p> Basic concepts that everyone should know before making an investment.</p></li> <li><p> Providing the tools necessary to analyze the fundamentals of any public company. You can create a portfolio of companies that you are interested in.</li><p> </ul> <br> <p>Let's start by learning the main <a href ="http://127.0.0.1:8000/concepts">concepts.</a> </p> <p>If you already have a … -
Django Form Not Sending File via Modal
I'm trying to upload a file via a form inside a bootstrap modal. request.POST correctly shows the file name in QueryDict, but request.FILES shows an empty MultiValueDict. For comparison, I also tried another version of the form that is exposed in the page, which seems to be working perfectly. What's the difference? Thanks. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <!-- UPLOAD FILE --> <form action="." method='post' enctype="multipart/form-data"> {% csrf_token %} {{ file_form.as_p }} <input type="submit" value="Upload"> </form> <!-- MODAL VERSION --> <a href="#" type="button" class="btn" data-toggle="modal" data-target="#statusModal"> Modal </a> <div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">UPLOAD FILE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action =".?&status=status-update" enctype="multipart/form-data" method = "post"> <div class="modal-body"> {% csrf_token %} {{ file_form.as_p }} </div> <div class="modal-footer"> <input class="btn green-button" type = "submit" value = "Send"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </body> </html> views.py: from django.shortcuts import render, redirect from upload_file.forms import FileForm from upload_file.models import File def index(request): if request.method == "POST": print(request.POST) print(request.FILES) file_form … -
Django: How can I create a function in models to get the username that made that post and also in views
I am creating a forum and i’ve been paralized with this problem, i can’t create a model to get the username of the user that made a post in the forum, i made a search and found nothing hope someone can help me -
Requests in Vuejs returning different response than Postman from django-rest-framework backend
I have been trying to implement the Twitch user authorization code flow. I am working on getting the authorization url generated from the django backend and pass it to my Vue front end so the user can open the user authorization page. Postman recovers the generated url perfectly however when i try to do the same in Vue using Requests it is giving me an entirely different object. Object { _events: {…}, _eventsCount: 1, _maxListeners: undefined, uri: {…}, method: "POST", readable: true, writable: true, explicitMethod: true, _qs: {…}, _auth: {…}, … } auth.js:37:12 and here is what Postman returns "{'url': 'https://id.twitch.tv/oauth2/authorize', 'client_id': 'xxx', 'redirect_uri': 'http://localhost:8000/api/twitch/callback', 'grant_type': 'token', 'scope': 'user_read'}" I'm not sure what could be causing this. Below is the code used to get to this point. urls.py from django.conf.urls import url from django.urls import include, path from better_auth import views urlpatterns = [ url(r'^api/token$', views.get_twitch_token), url(r'^api/auth/login$', views.get_twitch_user_token_uri), url(r'^api/auth/twitch/callback$', views.save_twitch_user_token), ] views.py import json import os import requests from django.http.response import JsonResponse from rest_framework.decorators import api_view from rest_framework import status # get user access token @api_view(['POST']) def get_twitch_user_token_uri(request): endpoint = "https://id.twitch.tv/oauth2/authorize" token_url = { 'url': endpoint, 'client_id': settings['TWITCH_CLIENT_ID'], 'redirect_uri': settings['TWITCH_REDIRECT_URI'], 'grant_type': 'token', 'scope': 'user_read' } Json = json.dumps(token_url) Json = … -
can't passe form's attrs in ModelForm to Template
I'm trying to set a ModelForm, but when I don't get the attrs that I set in my Form in the Template. also I wan't to get the date input in the format dd/mm/yyyy, this is my model: class Delivery(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name=_("delivery_user")) full_name_reciever = models.CharField(_("Reciever Full Name"), max_length=50) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.CharField(max_length=250) destination_city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=_("delivery_city")) destination_post_code = models.CharField(max_length=20) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) boxes_number = models.PositiveIntegerField(_("Number of Boxes"), default=1) boxes_wight = models.PositiveIntegerField(_("Boxes Wight"), default=1) boxes_volume = models.PositiveIntegerField(_("Boxes Volume"), default=0) document = models.FileField( help_text=_("Delivery Documets"), verbose_name=_("Delivery Certificates"), upload_to="documents/deliveries_documents/", ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) billing_status = models.BooleanField(default=False) delivery_status = models.BooleanField(default=False) class Meta: ordering = ("-created_at",) verbose_name = _("Delivery") verbose_name_plural = _("Deliveries") def __str__(self): return str(self.created_at) The ModelForm: class UserDeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = [ "full_name_reciever", "pickup_address", "destination_address", "destination_city", "destination_post_code", "operation_date", "boxes_number", "boxes_wight", "boxes_volume", "document", "invoice", "delivery_key", "billing_status", "delivery_status", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["full_name_reciever"].widget.attrs.update( {"class": "form-control mb-2 delivery-form", "Placeholder": "full name reciever "} ) self.fields["pickup_address"].widget.attrs.update( {"class": "form-control mb-2 delivery-form", "Placeholder": "pickup address "} … -
How to solve django.utils.datastructures.MultiValueDictKeyError: 'image'
details.html <html> <head> <title> Python button script </title> </head> <body> <h1>Hello</h1> {% if Button_number != 0 %} <form method="POST"> {% csrf_token %} <select name="buttonColor" id="buttonColor"> <option selected disabled="true">Select color</option> <option value="Red">Red</option> <option value="Blue">Blue</option> <option value="Green">Green</option> </select> <input type="submit" value="Insert" /> </form> {% endif %} </body> </html> home.html <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <form action="/external/" method="post" enctype="multipart/form-data"> {% csrf_token %} Input Image: <input type="file" name="image" required> <br><br> <input type="submit" value="Enter Image"> </form> </body> </html> views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pytesseract from PIL import Image from .models import insertbutton from django.contrib import messages def button(request): return render(request,'home.html') def external(request): imagetry=request.FILES['image'] print("image is ",imagetry) fs=FileSystemStorage() filename=fs.save(imagetry.name,imagetry) print(filename) im = Image.open(imagetry) text = pytesseract.image_to_string(im) #-------------image processing--------------- return render(request, 'details.html', {'Button_number': Button_number, 'button_heights': button_heights, 'button_widths': button_widths }) def allData(request): if request.method == "POST": if request.POST.get('buttonColor'): saveValue = insertbutton() saveValue.buttonColor = request.POST.get('buttonColor') saveValue.save() return render(request, 'another.html') else: return render(request, 'another.html') urls.py from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.button, name='home'), path('external/', views.external, name='script'), path('external/details', views.external, name='script'), path('another/', views.allData), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The error After inserting color. [04/Sep/2021 02:17:07] "POST /external/ HTTP/1.1" 200 704 Internal Server Error: /external/ Traceback (most recent call last): … -
Django <div>{% block content %}
This is probably a silly question, but can you put a <div> stage around Django's {% block content %}? <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'property/style.css' %}"> {% block head %} {% endblock %} </head> <body> <div class = "row"> <div class = "column left"> {% block left %} {% endblock %} </div> <div class = "column center"> {% block center %} {% endblock %} <div class = "column right"> {% block right %} {% endblock %} </div> </div> </body> <HTML> and my CSS * { box-sizing: border-box; } body { color: var(--text_color); background-color: var(--background_color); font-family: var(--font); font-size: var(--font_size); } .column { float: left; padding: var(--padding); height: 300px; } .left, .right { width: 25%; } .center { width: 50%; } .row:after { content: ""; display: table; clear: both; } I am trying to make each {% block %} be a column without having to write the <div> for each template. However, my HTML output is stacking them on top of each other instead of side by side. -
Many to many relationship does not work with django-safedelete as i want
I am using a library called django-safedelete to avoid permanently deleting records from the database, the technique is called "safedelete". Here is the documentation of the library https://django-safedelete.readthedocs.io/en/latest/managers.html I have a problem and it is that when I softdelete a record in the intermediate table between Actor and Film (Participation) the QuerySet ignores it completely, I mean when I execute a query to know in which film an actor has been, the Queryset ignores that the intermediate register that links the actor and the film is softdelete and shows in any case the films in which the actor has participated. here is an example of what happens: >>> Actor.objects.get (pk = 1) <Actor: Actor object (1)> >>> Film.objects.get (pk = 1) <Film: Film object (1)> >>> Participation.objects.all_with_deleted (). Values ('id', 'actor', 'film', 'deleted') <SafeDeleteQueryset [{'id': 1, 'actor': 1, 'film': 1, 'deleted': datetime.datetime (2021, 9, 4, 0, 43, 50, 125046, tzinfo = <UTC>) }]> >>> Actor.objects.get (pk = 1) .films.all () <SafeDeleteQueryset [<Film: Film object (1)>]> As you can see, it ignores that the participation record is softdelete and also shows the film in which the actor participated, what I need is not to show that the actor participated in that … -
How should I go about building a hard-coded image search website?
I have collected some images over time and I have categorised them into different category, let's say some are of cats, dogs, houses etc. you get the point!Now I want to create a simple hardcoded search engine, which return the images, let's say if I type dogs then it should return all the dog images which I have, I have no idea how to go about doing it, would anyone tell me how should I go about doing it? I have just created a beautiful search bar and that's it! Any help would be much appreciated :) I want to create this website and host it for other people to use My current skills are HTML5, CSS3, lil bit of JS & Django!