Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
¿why the discount is not seen in the template with javascript?
I have problem showing discount result in input (created with django) The result of the multiplication does appear and using the same logic I implemented it for the descent point, however, although the code is very similar, it is not displayed I do not put all the django code because it seems that it is ok because it does read the result of the multiplication, it seems that it is more my logic error in javascript clicking on the button should give both results, which it does not do, it only shows one I add the image of the result function multiplicar(){ var quantity=parseInt(document.getElementById('id_quantity').value); var unit_price=parseInt(document.getElementById('id_unit_price').value); var percent=parseInt(document.getElementById('id_descuento').value); var total_price=document.getElementById('id_total_price'); var total=document.getElementById('id_total'); total_price.value=quantity*unit_price; console.log(total_price); total.value=(percent*total_price)/100; console.log(total); } <!-- Parts --> <h3>Partes</h3> <section> <div> <form> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Partes</h4> <p class="card-title-desc">Agrega las partes que se incluirán</p> <div class="table-responsive"> <table class="table table-bordered table-nowrap align-middle" id="childTable1"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div class="form-check"> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn … -
In Django, how do I access and display the full name of a user in an Admin filter, when the full name is a foreign key value?
I am using the default Django admin and User model. I'm trying to add a field to list_filter where the field's value is username. But I would like to display the user first_name and last_name in the filter. I'm not sure how to access those user values from the admin. Here's a little code that doesn't work: list_filter = ('status', 'assignee_full_name') @property def assignee_full_name(self, obj): return obj.assignee.first_name + obj.assignee_last_name (assignee is the field I'm sorting on, that's the one with the value that equals the username.) This code as written doesn't work. The error message is <class 'intake.admin.ClientAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'assignee_first_name', which does not refer to a Field. What do I need to do differently to get assignee.first_name and assignee_last_name into a form that will be recognized or displayed by list_filter? There's a similar question at Django Display User as user Full Name in Admin Field, in fact this code was derived from that answer, but the accepted answer is unsatisfactory; as it says right in the answer, it "doesn't work". I appreciate that the questions are substantially similar, but the answer provided does not answer the question. -
How do I change an environment variable only during tests in Django?
I have a class that extends the root TestCase. I would like to set an environment variable in each of the tests that extend this class so that I don't cycles on unnecessary API queries. When I place the patch decorator outside of the class, it appears to have no effect. When I place the patch decorator just above the setUp, the patch appears to only last through the duration of the setUp. import mock, os from django.test import TestCase #patching here seems to have no effect class TCommerceTestCase(TestCase): @mock.patch.dict(os.environ, { "INSIDE_TEST": "True" }) def setUp(self): self.assertEqual(os.environ["INSIDE_TEST"], "True") # works! def test_inside_test(self): self.assertEqual(os.environ["INSIDE_TEST"], "True") # Fails! How do I patch an environment variable in a Django test (without manually patching to every function?) -
Bokeh & Django: RuntimeError("Models must be owned by only a single document")
I am making some bokeh plots using python bokeh and django. I'm trying to put these bokeh plots in a row, but this fails at the line: script, div = components(row(sample_plot, variant_plot, sizing_mode='scale_width')) in the code below. If i try to render a single plot generated with this method, it works. The error message i get is: I'm very confused why this is happening when i put my plots in a row. ERROR (exception.py:118; 04-11-2021 16:56:58): Internal Server Error: / Traceback (most recent call last): File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/hts_django/config/env/lib/python3.6/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/path/2/ma/viewz/HTS/views.py", line 932, in get script, div = components(plot_row) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/embed/standalone.py", line 216, in components with OutputDocumentFor(models, apply_theme=theme): File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/embed/util.py", line 134, in OutputDocumentFor doc.add_root(model) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 321, in add_root self._pop_all_models_freeze() File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 1104, in _pop_all_models_freeze self._recompute_all_models() File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/document/document.py", line 1127, in _recompute_all_models a._attach_document(self) File "/home/hts_django/config/env/lib/python3.6/site-packages/bokeh/model.py", line 692, in _attach_document raise RuntimeError("Models must be … -
Django stops serving static css files; but static images keep working
Template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width = device-width, initial-scale = 1"> <link rel="stylesheet" href="{% static "css/custom/nav.css" %}"> <link rel="stylesheet" href="{% static "css/custom/fonts.css" %}"> </head> <body> <div> <figure> <img src="{% static 'icons/logo.png' %}" alt=""> </figure> </div> </body> settings: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "webapp/static", ] STATIC_ROOT = "django_static" Problem: Django doesn't load static files. The browser throws: [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (nav.css, line 0) Not found: http://127.0.0.1:8000/static/css/custom/nav.css But, the images in static files work quite well. The URL for the main logo gets rendered to: http://127.0.0.1:8000/static/icons/logo.png Pictures get served without a problem, css doesn't. This happened in my opinion random. I had this issue formerly on a different page where css for the admin page apparently just stopped working and I couldn't figure out why. Now it happened for all css files on a bigger project that I can't just scrap and restart. I have no idea why this happens or how to troubleshoot this. I changed all static paths around, did collectstatic several times, added static paths to urls.py... Nothing changed. Edit: as I don't … -
Django - Send notification to user after new like
I'm searching for a method to notify an user if another user liked his/her post. For example instagram is giving you an alert: "this_user liked your post". Is there a way to do with djangos integrated messages framework? So far I got the logic for like a post (simple post request). I want to send the notification to the author of the post so after post.save() method. Someone know how to do? -
How to get mysqlclient to work with pipenv?
After installing mysqlclient with 'pipenv install mysqlclient' and attempting to runserver I was getting this error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
why does Twilio work in Egypt and doesn't work in India?
I'm working on the project and doing some integration with OPT Twilio by phone verification. now I should type the code of the country I work in to receive the correct phone number so, in Egypt when I type: +20... it works for me and I succeeded in log into my page but when I use the Indian code key which is: +91 it doesn't work I don't have any idea where is the problem located in! also, I searched for the countries that Twilio work with then, I noticed that page: https://www.visitnorthwest.com/country-codes/91-country-code/ that refers to Twilio can work with India so, any hint or help, please thank you in advance -
Instantiating two classes from a csv result in just one class getting instantiated
I have a csv file, values in certain columns are used to create objects of a class, values in other columns are used to create objects of a different class. def bulk_cliente_creation_from_csv(self): with open(self.file.path, encoding='utf-8-sig') as f: reader = csv.DictReader(f, delimiter=';') try: portfolio_clienti = [Cliente(ragione_sociale=row['Ragione Sociale'], telefono=row['Telefono'], piva=row['Partita Iva'].zfill(11), email=row['Email'] ) for row in reader] Cliente.objects.bulk_create(portfolio_clienti, ignore_conflicts=True) except DataError as e: print('ERROR!!!', e) try: qs_sl = [SedeLegale(indirizzo=row['indirizzo sede legale'], cap=row['CAP sede legale'], citta=row['Citt� sede legale'], provincia=row['Provincia sede legale'] ) for row in reader] SedeLegale.objects.bulk_create(qs_sl, ignore_conflicts=True) except DataError as e: print('ERROR!!!', e) # some non-relevant code, I'm 100% sure the error is above. Objects get instantiated just for the class which comes first (Cliente in this case), and correctly inserted in the DB. The second list comprehension is completely ignored. No error, no traceback, nothing, nada. The second try block gets executed, but qs_sl = [SedeLegale(indirizzo=row['indirizzo sede legale'], cap=row['CAP sede legale'], citta=row['Citt� sede legale'], provincia=row['Provincia sede legale'] ) for row in reader] just gets ignored like it was commented out. If I switch the order of the try/except blocks, just the objects of the class in the first block get correctly created and inserted in the DB. Removing the try/except blocks … -
filtering objects in django with special rules
How can you do a filter and do something like this in django model.objects.filter(user_id = request.user.id , thing != 0) I mean i wnat do something that it get only objects that their thing in not 0 . -
how to make fields optional? DRF
I use django-rest-framework and I want the "role" and "function" fields to be optional when creating a statement. Please, tell me how can I do this? I tried some tricks, example: I tried: function = FunctionsCreateSerializer(write_only=True, allow_null=True) and class Meta: ... optional_fields = [...] but I got "function": [ "This field is required." ] when I try: function = FunctionsCreateSerializer(write_only=True, required=False) I get: KeyError at /api/user/ 'function'' I really don't understand how I could change my serializers models.py class Operator(models.Model): ... role = models.ForeignKey("OperatorRole", related_name="operator", on_delete=models.CASCADE, null=True, blank=True) class OperatorRole(models.Model): function = models.ManyToManyField("FunctionRole", null=True) role = models.TextField( max_length=2, choices=Role.choices, default=Role.THERMIST ) class FunctionRole(models.Model): function = models.TextField( max_length=4, choices=Function.choices, default=Function.TPST, blank=True, null=True, ) serizlizers.py class UserSerializer(serializers.ModelSerializer): ... role = RoleSerializer() function = FunctionsCreateSerializer(write_only=True) class Meta: model = models.Operator fields = ["id", "username", "password", "email", "is_active", "fio", "position", "phone", "role", "function", "created", "updated"] class FunctionsSerializer(serializers.ModelSerializer): def to_representation(self, instance): return instance.function class Meta: model = models.FunctionRole fields = ("function",) class FunctionsCreateSerializer(serializers.ModelSerializer): function = serializers.MultipleChoiceField(choices=models.Function) class Meta: model = models.FunctionRole fields = ("function",) validators = [] class RoleSerializer(serializers.ModelSerializer): functions = FunctionsSerializer(many=True, read_only=True, source='function', required=False) class Meta: model = models.OperatorRole fields = ("role", "functions",) views.py class UserList(generics.ListCreateAPIView): queryset = models.Operator.objects.all() serializer_class = serializers.UserSerializer permission_classes = … -
Duplication Issue (Django Project) - ON FIREFOX ONLY
I have a duplication issue, it's happen on Firefox browser only, not on Chrome nor on Safari. When a user post a post, it's created twice, twice in the database. I am wondering why this happing on Firefox only? I cannot debug it or provide you with any codes as this is happing in one browser only. This code is helpful but not for Firefox: $('.prevent_multiple').click(function() { $(this).prop('disabled', true); $(this).parents('form:first').submit(); }); -
Polymorphic Django CreateView
I'm using Django 3.2.9 and have three classes BaseClass, Class1 and Class2, with Class1 and Class2 inheriting from BaseClass. Ideally, I'd like to use a CreateView an UpdateView and a DetailView to manage these classes rather than writing my own View. Is it possible to create a single CreateView that will take some context (type_name, say) and will then receive model=Class1 or model=Class2 automatically (along with the form_class and template_name? These classes are quite closely related, but similar enough that I want their create to be at the same URL. Or am I better off just writing a View that handles this all directly without any of the convenience features of the Django generic views? -
Queryset more funcionally
I have a question whether the code is acceptable, or is there another possibility with a more optimal way out of this situation My one model look like that: class ModelA(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) manga = models.ManyToManyField(Manga, through='ModelB') def manga_list(self): return ModelB.objects.filter(user=self.pk).all() def manga_list_reading(self): return ModelB.objects.filter(user=self.pk, type=utils.READING).all() and second model look like that: class ModelB(models.Model): user = models.ForeignKey(ModelA, on_delete=models.CASCADE, ) manga = models.ForeignKey(Manga, on_delete=models.CASCADE) type = models.CharField(max_length=30, choices=utils.LIST_PROFILE_CHOICES, null=False, blank=False) so my question is about this def list return, is it some another option for do it ? -
how to convert a form data that contains image files to json file using in python django and i am not using django restframe work just python&django
@csrf_exempt def registerSeller(request): print(request.body) data = json.loads(request.body.decode('utf-8')) i am new for django and trying to build api with out django restframework and this is the output for request.body but it gives me error AttributeError: 'bytes' object has no attribute 'read' request.body b'-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="username"\r\n\r\nabe7\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="password"\r\n\r\n123\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="phonenumber"\r\n\r\n091010101\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="email"\r\n\r\nemail@gmial.com\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="shop_description"\r\n\r\ndescription new\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="shop_name"\r\n\r\nname new\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="images"\r\n\r\n[object File],[object File],[object File]\r\n-----------------------------344288735834045826241553250616--\r\n' -
Cannot connect to mssql database using Django (Mac OS)
My mssql database is inside the docker container. When trying to connect to the database using azure data studio I don't get any errors, whereas when I'm trying to connect to the db using Django I get the following error: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/mssql/base.py", line 230, in _cursor conn = super()._cursor() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return … -
How to send continuous response in python Django?
I want to run the following command and its sending output to template def nikto(request): context = {} host = request.GET.get('host', False) nikto_output = os.popen('nikto -h ' + request.GET['host']).read() # context['nikto_output'] = nikto_output context['nikto_output']=nikto_output return render(request,'nikto.html',context) # return render(request,'nikto.html',context) but it's first performing a complete task and then sent to the template, till then webpage is loading, I want to display one-by-one line output. if you know of any solution, please let me know. -
Don't want django makemigration to create a table in database as the I already have the table in the database
I already have a table name browser in my database and when I create a new django project and run python3 manage.py makemigrations command it adds a new table name BrowserAddition_browser in the database. How should I stop django from making a new table and use the current table which is present in the database.Thanks in advance for your help. This is model => model that i want to use in django browser(created before the project) and BrowserAddition_browser (create by django) -
django admin site foreign key from dropdown to search_field
Im a bit stuck at why a foreign key drop-down field in admin site is not changing to a search field. I read the documentation that states: These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation: search_fields = ['foreign_key__related_fieldname'] I have two models: class Company(models.Model): company = models.CharField(max_length=100) class User(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE) When I want to create a user manually via admin site I get a drop-down list of possible companies as foreign keys I though that this solution should change the drop-down to a search field but it isnt. What am I doing wrong here? How to change this foreign key field to a search field? admin.py from django.contrib import admin from .models import Company, User class MyAdmin(admin.ModelAdmin): search_fields = ['company__company'] admin.site.register(Company) admin.site.register(User, MyAdmin) -
django how to change database with click button on new window and close, refresh the main page?
I made 'alert list' page. (alert_list.html) and when I click the button, it renders detail page uses pk on new window. (alert_detail.html) But , I have some problem with handle this. The things what I want to do is.. change Event.event_status value to 0. close new window(detail page) refresh main page(alert list page) <alert_list.html> {% for event_alert in event_list %} {% if event_alert.event_status == 1 %} <div class="col-1 red"> <div class="p-3 rounded-2" id="dash_board_patient_alert"> <a href="{% url 'Alert Detail' event_alert.event_id %}">{{event_alert.member_id}} {{event_alert.event_type}}</a> </div> </div> {% endif %} {% endfor %} {{event_alert_activate_count}} {{pink_block}} {% for _ in pink_block %} <div class="col-1 pink"> <div class="p-3 rounded-2" id="dash_board_patient_alert"> <a href="#"></a> </div> </div> {% endfor %} <alert_detail.html> {% for event_alert in event_list %} <form method="POST" class="post-form" action ="{% url 'Alert Update' event_alert.pk %}"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary" id="patient_alert_result_confirm"> Confirm </button> </form> {% endfor %} <alert_update.html> I don't have any idea.. help me this page <views.py> def alert_list(request): Event.objects.order_by('-event_time')[:12] event_alert_activate_count = Event.objects.filter(event_status__startswith='1')[:12].count() pink_block = int(12) event_list = Event.objects.order_by('-event_time') context = { 'event_alert_activate_count': event_alert_activate_count, 'event_list' : event_list, 'pink_block' : pink_block } return render(request, 'dashboard/alert_list.html', context) def alertDetail(request,pk): event = get_object_or_404(Event, pk=pk) event_list = Event.objects.order_by('-event_time')[:1] context = {'event_list': event_list, 'event' : event,} … -
Django prefetch m2m through model
I have the following models: class Block(MPTTModel): # some fields links = models.ManyToManyField('self', through='BlockLink', symmetrical=False) class BlockLink(models.Model): source = models.ForeignKey( 'Block', on_delete=models.CASCADE, related_name='source_block' ) destination = models.ForeignKey( 'Block', on_delete=models.PROTECT, related_name='destination_block', null=True ) is_valid = models.BooleanField(default=False) With that, I can access the through model using: my_block.links.through.objects.filter(source=my_block.id) My problem is, that I access the blocks in a loop, and each of the blocks creates an own query to select the through model. So for 5000 blocks, we have 5000 additional queries. How can prevent this. Is there any way of annotating or prefetching the through model? What I tried? I tried the solution from Django prefetch through table using .prefetch_related('blocklink_set') but that ends up in the following error: Cannot find 'blocklink_set' on Block object, 'blocklink_set' is an invalid parameter to prefetch_related() Second try was .prefetch_related( Prefetch('blocklink', queryset=BlockLink.objects.all()), ) but that also ends in an error. -
amazon face rekognition changing request object
I am working on an image proctoring project, after including Amazon S3 bucket storage, i am receiving different request object from js(client) previously I was able to decode the request.body but after integrating S3 it's not working , it's sending me bytes, I am confused does S3 make any changes to request or Django middleware ? def post(self,request): frame_data = json.loads(request.body.decode('utf-8')) print(frame_data) actual_image = data_uri_to_cv2_img(frame_data['img_frame']) push_frame(actual_image,'register',frame_data['mode']) #push data when capture button is clicked on client if frame_data['mode'] == 'mentoring': try: random_img = ImageFrames.objects.filter(frame_captype__frame_captype = 'register',frame_captype__frame_cap_mode ='random').last().image_frame last_img = ImageFrames.objects.filter(frame_captype__frame_captype = 'register',frame_captype__frame_cap_mode='mentoring').last().image_frame res = compare_faces(random_img,last_img) if res['FaceMatches'][0]['Similarity'] > 90: compare_status = True else: compare_status = False data obj i am sending from client img_frame= { img_frame:data, <--- this is image in bytes mode:'mentoring' } var save_frame = (img_frame) => { if (img_frame.mode != 'random') { img_frame['mode'] = 'mentoring' } fetch( '/save_frame/', { method:'POST', body: JSON.stringify(img_frame) } ).then((resp)=>{ return resp.json() }).then((resp_data) data i am receiving after S3 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAADhCAYAAAByfIirAAAgAElEQVR4nMy795PcZp7mqX9lZ3ZudqbddKtlWhKbFClDkSJF0Ym+isUy6YHMBJCJ9FnesDxZJMt7X1k+K8t77w2r6J0o7yhRnuazPxS3e29m7uIi7uJ2f3jiDQBvAMiIxAfP9/s+eC4ixkp4jIzWoGA0yIgGG6LgRG+yodNLiIINg9GC3mLBZLOj18oYjAqCqCIYnJgMLgwGFYPBhE40oDUa0YlWBEnGareh+p044hxIVg2yoEE26bAKBiSLCavZiFUwYTEZMUVHYzwTgVGvQTSaseglzHoRwWhEMGoxGTQImmjM+hhsNg12JQpV0uBSonFaInHLIqrVhNdhwSlbkAUrqqSgWgXsFj0ui4G8s8mUlRdRWVVKSdkFSoou0dHWSH9vG0P9nXR3NdPV1URvKEB/KMD0RA9Ts32Mj/cxNNhLa2OAzk -
(DJANGO) retrieving data from html form using GET/POST
This is part of the CS50W courseware Project 1. I have tried to retrieve a user input from a form using a get method. However, the search_query variable in views.py does not have any input. I then changed the get methods to post methods and it worked. Why is that so? layout.html(get method) <form action="{% url 'search' %}" method="GET"> <input type="search" name="search_query" placeholder="Search Encyclopedia"> </form> views.py(get method) def search(request): search_query = request.GET['search_query'] if search_query in util.list_entries(): return redirect('entry_page', title=search_query) for entry in util.list_entries(): if search_query in entry: return redirect('search_results') layout.html(post method) <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="search" name="search_query" placeholder="Search Encyclopedia"> </form> views.py(post method) def search(request): search_query = request.POST['search_query'] if search_query in util.list_entries(): return redirect('entry_page', title=search_query) for entry in util.list_entries(): if search_query in entry: return redirect('search_results') -
What is the connection between autocomplete_fields and JS in Media class?
I use Django. My admin.py: class CardInlineAdmin(admin.StackedInline): model = Card autocomplete_fields = ['project', 'course', 'vacancy', 'news', ] @admin.register(Section) class SectionAdmin(admin.ModelAdmin): list_display = ('name', 'id', 'priority', 'is_active',) inlines = (CardInlineAdmin,) search_fields = ['project', 'course', 'vacancy', 'news'] class Media: js = ( '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', 'js/card_in_section.js', ) If I open SectionAdmin on admin page the file card_in_section.js will not work. If I remove autocomplete_fields from CardInlineAdmin the file card_in_section.js will work. What is the reason of such behavior? -
How to count validate formset?
How to count how much the filled fields in formset object ? For example, I have a formset of form and each form has ChoiceField. How do I count the total filled ChoiceField in formset when each form of the formset is validated ? Thank you.