Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add data-bs-toggle & data-bs-target to my script - Datatables
I want to make a web application on django platform using datatables. I get the data from the database with json and bring it to the screen. I was able to add -edit and -delete buttons as you can see in the photo, but I cannot add functionality to these buttons with javascript. How can I add data-toggle and data-target attributes inside ? In addition, I want to send the id of data in the row with data-target, so that I can edit the data. Thank you for help! enter image description here ..... "ajax": "/json", "columns": [ {"data": "id"}, {"data": "code"}, {"data": "muestra"}, {"data": "ship"}, {"data": "num"}, {"data": "enc"}, {"data": "obv"}, // {"data": "result"}, {"data": "created_at"}, {data: null, render: function ( data, type, row ) { return '<a class="btn btn-outline-success text-center" title="Edit row"><i class="fa-solid fa-pen-to-square" style="color:green !important;"></i></a>'; } }, {data: null, render: function ( data, type, row ) { return '<a class="btn btn-outline-danger text-center" title="Delete row"><i class="fa-solid fa-delete-left" style="color:red !important;"></i></a>'; } }, ], ..... $( "#example" ).on('click','tr a', function() { var tr = $(this).closest('tr'); var data = table.row(tr).data(); console.log(data.id); $($(this).attr('data-bs-toggle','modal')); $($(this).attr('data-bs-target','#editModaldata.id')).model("show"); }); -
I got http instead of https file path in Django
I am working on a project where I users can upload pdf files and sign a signature on it. Although, this implementation works well on local machine which uses http requests, however after I deploy it on a server, the file path's uploaded to the server returns an http path instead of https. Here is models.py from django.db import models from utils.mixins import BaseModelMixin import os from utils import pdf_processor from django.core.files.base import File import requests import time class DocumentFromUrl(BaseModelMixin): pdf_url = models.URLField() rental_bon_number = models.CharField(max_length=255) dossier = models.CharField(max_length=255) company = models.CharField(max_length=255) company_username = models.CharField(max_length=255) user_email = models.EmailField() client_email = models.EmailField() client_username = models.CharField(max_length=255) validity_date = models.CharField(max_length=255) language = models.CharField(max_length=255, null=True, blank=True) message = models.CharField(max_length=255, null=True, blank=True) pdf = models.FileField(null=True, blank=True, upload_to='url_pdf') fields = ['pdf_url', 'rental_bon_number', 'dossier', 'company', 'username', 'user_email', 'client_email', 'client_username', 'language', 'message', "validity_date"] def download_pdf(self): filename = f'media/temp/{time.time()}.pdf' with requests.get(self.pdf_url, stream=True) as r: with open(filename, 'wb') as file: for chunk in r.iter_content(chunk_size=1024): file.write(chunk) return filename def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.pdf: return downloaded_pdf = self.download_pdf() other_part = pdf_processor.pdf_from_dict( {x: y for x, y in self.__dict__.items() if x in self.fields}) merged_files = pdf_processor.merge_pdf_files( [downloaded_pdf, other_part]) self.pdf = File(open(merged_files, 'rb'), name=merged_files.split('/')[-1]) self.save() As you see in the above … -
Platfrom hooks not found when deploying to AWS
I am trying to deploy a django app to elastic beanstalk. This worked well initially but I have recently made a change to the database models and so need to migrate these in the production environment. Looking at old logs I can see there was not a problem with this previously, but now the migrate command is not found: 2022/05/23 07:45:34.726621 [INFO] Executing instruction: RunAppDeployPostDeployHooks 2022/05/23 07:45:34.726634 [INFO] Executing platform hooks in .platform/hooks/postdeploy/ 2022/05/23 07:45:34.726654 [INFO] The dir .platform/hooks/postdeploy/ does not exist I am deploying using eb deploy and I the path mywebsite/.platfrom/hooks/postdeploy/01_migrate.sh exists. Does anyone know why it is not being found? -
How to use django unit tests with elasticsearch?
I use django unit tests to test my application. It worked very well until today. I integrated elasticsearch to the project with the 2 modules django_elasticsearch_dsl and django_elasticsearch_dsl_drf. Since then, almost none of my unit tests are working. I got the same trace for all failed tests: Traceback (most recent call last): File "/home/aurelien/dev/gsport/accounting_bo/tests.py", line 66, in setUp club = create_club() File "/home/aurelien/dev/gsport/dashboard/tests.py", line 38, in create_club club.save() File "/home/aurelien/dev/gsport/clubs/models.py", line 81, in save super().save(*args, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/db/models/base.py", line 739, in save self.save_base(using=using, force_insert=force_insert, File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/db/models/base.py", line 787, in save_base post_save.send( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/signals.py", line 58, in handle_save registry.update(instance) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/registries.py", line 141, in update doc().update(instance, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 225, in update return self._bulk( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 202, in _bulk return self.bulk(*args, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/django_elasticsearch_dsl/documents.py", line 151, in bulk response = bulk(client=self._get_connection(), actions=actions, **kwargs) File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 410, in bulk for ok, item in streaming_bulk( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 329, in streaming_bulk for data, (ok, info) in zip( File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 256, in _process_bulk_chunk for item in gen: File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 195, in _process_bulk_chunk_error raise error File "/home/aurelien/dev/gsport/venv/lib/python3.10/site-packages/elasticsearch/helpers/actions.py", line 240, in _process_bulk_chunk resp … -
How to Handel Create , Update and Delete Image with Django Signals?
I have these Models, I want to change the Name of the Photos in this Pattern (ProductName-ImageId.jpg) I want help in changing the Name of the file, in Update and delete it? is it the Best Practice for doing This? models: class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, null=False, blank=False) describtion = models.TextField() price = models.FloatField() inventory = models.PositiveIntegerField() created_time = models.DateTimeField(auto_now_add=True) last_updated_time = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.name def get_absolute_url(self)->str: return reverse("shop:product", kwargs={"pk": self.pk}) @property def photos(self): return ProductImage.objects.filter(product=self) @property def base_photo(self): return self.photos.first().image class ProductImage(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="products/photos") product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self) -> str: return self.product.name signals: from django.db.models.signals import post_delete , post_save from django.dispatch import receiver from .models import ProductImage import os from pathlib import Path from django.conf import settings # This Work On Delete @receiver(post_delete, sender=ProductImage) def my_handler(sender,instance:ProductImage, **kwargs): # Delete the Image after delete the Entry Path(instance.image.path).unlink() @receiver(post_save, sender=ProductImage) def my_handler(sender,instance:ProductImage,created, **kwargs): print() print(instance.image.name) print(instance.image.path) print() if created: old_path =Path( instance.image.path) instance.image.name = f"{instance.product.name}-{instance.id}.jpg" new_path = settings.BASE_DIR / f"media/products/photos/{instance.image.name}" old_path.rename(new_path) instance.save() print(instance.image.path) the two Methods work but when I rename the File the Path Change before Signal : E:\Programming\Python\Django Projects\Django-shop-app\media\products\photos\c-d-x-PDX_a_82obo-unsplash.jpg after Signal : E:\Programming\Python\Django Projects\Django-shop-app\media\Headphones-16.jpg -
Why doesn't Django recognize create_user() when I want to create a User?
I want to create User with User.objects.create_user(username,email,password) where User impored from from django.contrib.auth.models import User but Django doesn't recognize create_user() and When I want to definition of it VsCode says:No Definition found for 'create_user'. I use Django 4.0.4 and python 3.10.4 -
Django validation errors not showing up
So, I was learning Django from a tutorial and came across form validation. The tutor's version had errors pop-up on screen when validation failed but nothing shows up on my form. Here is my forms.py. from django import forms from django.core import validators def check_for_z(value): if value[0].lower() != 'z': raise forms.ValidationError('Name should start with z') class FormName(forms.Form): name = forms.CharField(validators = [check_for_z]) email =forms.EmailField() text = forms.CharField(widget=forms.Textarea) This is my views.py file. from django.shortcuts import render from myformapp import forms def form_name_view(request): form = forms.FormName() if request.method == 'POST': filled_form = forms.FormName(request.POST) if filled_form.is_valid(): # print the form data to terminal print("Validation success") print('Name: ' + filled_form.cleaned_data['name']) print('Email: ' + filled_form.cleaned_data['email']) print('Text: ' + filled_form.cleaned_data['text']) return render(request, 'myformapp/formpage.html', {'form' : form}) And this is my template for the page. <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Form Page</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> </head> <body> <div class="container"> <form method="post"> {{form.as_p}} {% csrf_token %} <input type="submit" class="btn btn-primary" value="Submit"> </form> </div> </body> </html> So whenever i enter a name that's not beginning with z i am supposed to get an exception on the screen but nothing shows up. My … -
Form data is passing in html table
I am submitting the form data by using fetch API and then I want to show some variable values in HTML table. But it's not working as it's supposed to be. I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST['options_value'] value=request.POST['value'] print(options_value,value) context={"options_value":options_value, "value":value} return render(request, 'index.html',context) index.html <form method="POST" action="" id="form"> {% csrf_token %} <select class="form-select" aria-label="Default select example" name="options_value" id="options_value" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </form> <table style="display: table" id="table"> <tbody> <tr> <th scope="row">ProfileUID :</th> <td>{{options_value}}</td> </tr> <tr> <th scope="row">First Nane :</th> <td>{{value}}</td> </tr> </tbody> </table> <script> let form = document.getElementById("form"); let options_value = document.getElementById("options_value"); let val = document.getElementById("value"); const … -
Django: assigning multiple values to a model field
I'm trying to make a 'friendlist' function in django models and I'm having some problems. In my app, every user can make a name card. I want to let the users add each others as 'friends'(just like fb), so that I can make a friendlist for them. This is what my models.py looks like so far. from django.db import models from django.contrib.auth.models import User # Create your models here. class Card(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="cards") # friend_list = models.???? I'd like to add a 'friend_list' attribute, which can store other cards' informations(I'm thinking of their pk values). Later, I'd like to iterate those values so that I can use it to make a friendlist in the template. For example, "George's name card" should have information of its friends' cards' pk value. Is there a way to save multiple values in one attribute? -
Iterate and append the value in JSON in python
I'm trying to the iterate and append the QId and Answer from the payload, desired output would be like 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&18|Yes&&19|Yes&&. I have tried to get only 12|Yes&& and 13|Yes&& separately. All I wanted is to concatenate QId and Answer before it saves to the database. How could I achieve this Qstans = str(qid)+'|'+ answer+'&&' this line which append the values payload 0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…} 1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…} 2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…} 3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…} 4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…} 5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…} 6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…} What I tried @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': data = [] cursor = connection.cursor() for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') print('sid--', sid) TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action … -
Making backup of db skiping part of data in django
I need to make backup of production db, for development purpose. but whole db is to heavy and take too long to restore it fully locally. so I need to drop part of data, but I don't want to drop whole models. Is there any package that would allow me to write script that would chose which data would be present in backup before making it without actually deleting this data from production db? -
How to add a search field for Django Admin Change/Add forms?
CONTEXT I am making a birthday app where the Admin can input their friends birthdays and gifts they wish to buy for them. The gifts are in a separate table and the friends_birthday table refers to this gifts table by a manytomanyfield. When creating a piece of data for their friend (i.e. firstname, birthday, etc.) the Admin must first create a gift for them via the gift table, then create a row in the 'friends_user' table that adds their info and gift(s). Problem When the Admin is adding the gifts to their friends, the default setting is a box populated by many gifts, some of which they are assigning to their other friends. However, if the project scales, then the box would overflow and simply highlighting the choices would not work. Hence, I want to create a search bar in the add/change form in Django Admin. Any ideas? Thanks in advance. -
Python nested json
Can any one have solution for this, i want there should be api data in this manner ?? I wanted api data in for similar state comes in one hood rather than seprate, different state data can be different obj, data = [{ state_name:New_jersi, data:{ category:Phishing, sub_cat_data:[{ name:SubCat1, count:20 }, { name:SubCat2, count:30 }] } category: malware, sub_cat_data:[{ name:SubCat1, count:20 }, { name:SubCat2, count:30 }] }, { state_name:Washinton, data:{ category:Phishing, data:[{ name:SubCat1, count:20 }, { name:SubCat2, count:30 }] } }] But may api response be: { "state": "South Carolina", "state_count": 2, "Website Compromise/Intrusion": { "sub_category": { "Insecure Direct Object Reference": 2, "Memory Corruption": 2, "SQLI": 1, "Stack Overflow": 1, "XSRF": 1, "Heap Overflow": 1, "Security Misconfiguration": 1 } } }, { "state": "South Carolina", "state_count": 1, "Phishing": { "sub_category": { "Spear Phishing Attacks": 2, "Fast Flux": 2, "Rock fish": 2, "Identify Theft/Social Engineering": 1, "Phishing Redirector": 1, "Pharming": 1, "Exploitation of Hardware Vulnerability": 1 } } }, i wanted same state data be in same object buut in my case state data comes in seprate object because of data comes through category, rather that seprate. My logic are below cat_count = incnum.values('incident_category__cat_name','incident_category__cat_id').annotate(count=Count('incident_category__cat_id')) subcat_count = incnum.values('incident_sub_category__sub_cat_name','incident_sub_category__cat_id','incident_sub_category__id').annotate(count=Count('incident_sub_category__cat_id')) reporter_state_count1 = incnum.values('incident_category__cat_id','reporter__comp_individual_state','reporter__comp_individual_state__name').annotate(count=Count('incident_category__cat_id')) for x, … -
Django with React: csrf token is undefined in cookies
part of react code: settings.py: views.py: btw, @ensurecsrf decorator is useless and will give you 403 forbidden error about csrf being not set any idea? -
pip install confluent-kafka gives error in mac
When i tried pip install confluent-kafka got the following error #include <librdkafka/rdkafka.h> ^~~~~~~~~~~~~~~~~~~~~~ 1 error generated. error: command '/usr/bin/gcc' failed with exit code 1 I'm using python version 3.9 and macOs Monterey -
How can I fix the paginator and the filter problem for Django?
To simply explain, I have a model product with columns: (Product model): name type (Order model): order price quantity I am using the django built-in Paginator and the django-filter. The paginator works so well and it really filters the items but the problem is, when the paginator is involved, the "Next" or "Previous" button I created will not work well to see the filtered items on the next or previous page because it reloads the whole template and the filter form will be erased. Example: I have mouse and keyboard as "choices" on the "Type" column of the product. I have 25 mice, and the paginator divides it by 10. I can filter the items and shows 3 pages for the mice but when I turn to the next page, the keyboard items will show because the filter form is reset. Any help or suggestion will be appreciated. I need to hear any thoughts for this. -
TemplateSyntaxError: 'for' statements should use the format 'for x in y'
I'm creating a listing page that emulates Stack Overflow's page limit feature; a user can choose to modify the number of questions listed whether it be 10, 15, or 25 on a page. In the process of creating an URL link for each page limit number within the template it's raising the following error: TemplateSyntaxError: 'for' statements should use the format 'for x in y': for limit in [10, 15, 25] What is it about the template for-loop that is causing this error to be raised? @register.simple_tag(takes_context=True) def set_page_number_url(context, page=None, limit=None): request = context['request'] request_resolver = resolve(request.path) query_string = QueryDict(request.META['QUERY_STRING']) query_tab, search_query = [ query_string.get("tab", "newest"), query_string.get("q") ] if page: page_data = { "pagesize": page.paginator.per_page, "page": page.number, "tab": query_tab, } else: page_data = { 'pagesize': limit, 'page': 1, 'tab': query_tab } _path = f"posts:{request_resolver.url_name}" if request_resolver.url_name == "tagged": tags = "+".join(tag for tag in context['tags']) path = reverse(_path, kwargs={'tags': tags}) query_string = urlencode(page_data) return f"{path}?{query_string}" if request_resolver.url_name == "search" and search_query: page_data.update({'q': search_query}) query_string = urlencode(page_data) path = reverse(_path) return f"{path}?{query_string}" <div class="page_range_options_wrapper"> {% for limit in [10, 15, 25] %} <a class="inactive_page page_num" href="{% set_page_number_url limit %}">{{ limit }}</a> {% endfor %} </div> -
Heroku Django postgres migration merge: psycopg2.errors.DuplicateTable: relation already exists
This is a Heroku-specific issue with a Django project 1.11.24 running Python 3.6.5 and a Heroku postgres database. During testing of two different branches during development, different conflicting migration files were deployed at different times to the Heroku server. We recognized this, and have now merged the migrations, but the order the Heroku psql db schema was migrated is out of order with the current migration files. As a result, specific tables already exist, so on deploy applying the updated merged migration files errs with: psycopg2.errors.DuplicateTable: relation "table_foo" already exists In heroku run python manage.py showmigrations -a appname all of the migrations are shown as having run. We've followed Heroku's docs and done the following: Rolled back the app itself to before when the conflicting migrations took place and were run (https://blog.heroku.com/releases-and-rollbacks) Rolled back the postgres db itself to a datetime before when the conflicting migrations took place and were run (https://devcenter.heroku.com/articles/heroku-postgres-rollback) However, despite both app and db rollbacks, when we check the db tables themselves in the rollback in pql shell with \dt, the table causing the DuplicateTable err still exists, so the db rollback doesn't actually seem to effect the django_migrations table. It's Heroku, so we can't fake … -
Why am I getting a "The connection was reset" error when trying to run my Django application on a Docker container?
I'm trying to containerize my Django app for the millionth time, and always seem to keep running to issues with mysql connection (or permissions?) issues. I still don't really understand what's going on during this process, and I keep running into the same general error. I'm seriously about to pull my hair out. Can someone please point out where I'm going wrong when trying to set up the container? My config files are at the end of this post. I'm in my project root (where my docker-compose.yml resides), and I try running docker-compose up --build. But, I get this error sportsbet-web-1 | Watching for file changes with StatReloader sportsbet-web-1 | Exception in thread django-main-thread: sportsbet-web-1 | Traceback (most recent call last): sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection sportsbet-web-1 | self.connect() sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner sportsbet-web-1 | return func(*args, **kwargs) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect sportsbet-web-1 | self.connection = self.get_new_connection(conn_params) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner sportsbet-web-1 | return func(*args, **kwargs) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection sportsbet-web-1 | connection = Database.connect(**conn_params) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/MySQLdb/__init__.py", line 130, in Connect sportsbet-web-1 | return Connection(*args, **kwargs) sportsbet-web-1 | File … -
OneToOne connection between User and Profile in Django
I am creating an app in django in which after user model is created, via the signal I create a profile: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() But as far as I feel, this does not guarantees me that profile id always equals user's one Is there any smart way to do this safer? I think about creating a signal which will delete profile model after user one and opposite, but I still feel that not all cases are covered -
Django login user never come true
I am having problems with my Django login. The below if statement (if user is not None:) always resolves as false, so it moves onto the else. I'm not sure why and I would appreciate any help Thanks VIEWS.PY from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.contrib import messages # Create your views here. def login_user(request): if request.method == 'post': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index.html') else: messages.success(request,("there is an error....")) return redirect('login') else: return render (request ,'login.html', {}) urls.py from django.urls import path from accounts import views urlpatterns = [ path('login_user', views.login_user ,name= 'login'), ] main urls.py "" from django.contrib import admin from django.urls import path,include from availability import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('availability.urls'), name='index'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls')), ] ''' And here is the login form: <form action="" method="post"> {% csrf_token %} <div class="input-group mb-3"> <input type="text" class="form-control" name='username' placeholder="username"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input type="password" class="form-control" name='password' placeholder="Password"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <div class="col-8"> <div class="icheck-primary"> <input type="checkbox" id="remember"> <label for="remember"> … -
fetch data from pre-existing table and paste it into view of another django model
How can I make realtime changes of my view using django model and a pre existing table ? I have a table of random data of people like this people table and I have a model with class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) voyageur = models.PositiveIntegerField(default=1) # set to current time created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) # user who posted this user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title I want the data from the people table to be changed in the memo textfields in real time as I change the value of voyageur which can be associated to the primary key of "people" visualize in real time data as I change value of voyageur is this possible ? do I have to pass from a front end app like react to do that ? -
Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\\Z']
I'm doing a tutorial from django, and i getting this error when trying to add an href button, i use django 4.0.4 version and python 3.9 version. Models.py class Producto(models.Model): serie_producto = models.CharField(max_length=30) nombre = models.CharField(max_length=30) codigo = models.CharField(max_length=15) marca = models.CharField(max_length=30) precio = models.IntegerField() created_date = models.DateTimeField(default=timezone.now) urls.py ... urlpatterns = [ ... path('agregar/<int:producto_id>/', agregar_producto, name="Add"), ... ] template catalogo that causes te error. The message error highlights {% url 'Add' producto.id %} {% for producto in response %} <div class="col-6"> <div class="card" style="height: 10rem; width: 23rem; margin: 5px 0px;"> <div class="card-body"> <h5 class="card-tittle">{{producto.nombre}}</h5> <p class="card-text">{{producto.marca}}</p> <p class="card-text">{{producto.precio}}</p> <a href="{% url 'Add' producto.id %}" class="btn btn-primary">Agregar al carrito</a> </div> </div> </div> {% endfor %} view.py from tienda.models import Producto from tienda.carrito import Carrito def catalogo(request): url = "http://127.0.0.1:8000/api/Producto/" response = requests.get(url, auth=('admin','duoc')) datos = response.json() return render(request, 'catalogo.html', {'response' : datos }) def agregar_producto(request, producto_id): carrito = Carrito(request) producto = Producto.objects.get(id=producto_id) carrito.agregar(producto) return redirect("Tienda") The Problem When i got to the catalogo template i get the before mentioned error, the api works perfectly when i dont use the {% url 'Add' producto.id %}, i think that is something with the id, cant read it maybe??, i dont know if … -
How to make Django using Pillow to crop only new image?
I can make Django crop images, but I got a problem. When I go to change form to update one of the images, all images got cropped again and again after every new save - which means all images get smaller and smaller. How to make Django only crop new images and leave old images alone? Each of my images got a crop count field - when set to 0 the image could be cropped and if set to 1 the image could not be cropped. Each image also got a created_date field which automatically generated a timestamp. Can any of these extra fields be used to create a condition in which an image won't get cropped twice when a whole model got updated? Example: product 1 = got image_1, image_2, image_3, -- image_1 got crop_count and created_date fields, same goes for all other images. -- I want is to go to image_1 to update it with a newer image, and I don't want to see image_2 and image_3 got cropped - but only image_1 gets cropped. How? I know how to use signal in Django, so should this be post-save or pre-save? -
Email Not Sending in AWS SES
Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com' EMAIL_HOST_USER = config('SMTP_USER') EMAIL_HOST_PASSWORD = config('SMTP_PW') EMAIL_PORT = 587 VERIFIED_IDENTITY = config('VERIFIED_IDENTITY') I have a verified email in my AWS SES and I am trying to send a message. I get a sent message everytime I use my contact form but no message actually gets sent. if 'contactForm' in request.POST: #print('Contact form') contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact_form.save() email_subject = f'New contact {contact_form.cleaned_data["email"]}: {contact_form.cleaned_data["subject"]}' email_message = contact_form.cleaned_data['message'] print(email_subject,email_message) try: send_mail(email_subject, email_message,settings.VERIFIED_IDENTITY,[settings.VERIFIED_IDENTITY]) except BadHeaderError: print('bad')