Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get a column from a django model to a javascript array
Hello everyone I am new in Django I am looking for solution to get a column ("names") from a Django model to a JavaScript array so when I write console.log (T) it returns the list of the names any help please NB : please give the solution Well detailed because I am a beginner (Django part : what should I do, and JavaScript part too) -
Why some libraries in simple vanilla Js require NPM?
I am pretty new to js. And I am looking to learn js. Recently I came across one library called bounce.js which is animation library. Which require NPM to install but why? I am dont want to use NPM (or any packet Manager) they havent provided min.js file to direct import in scrpit tag?? Why??. Similarly for Tailwind it require NPM. And as NPM require it means I need vercel to deploy and all stuff. 2) As I use django I dont know how to install NPM modules in my templates. Please help me clear out from this mess. -
HTMX websockets with Django channels
I try to connect a Django channels Consumer to a HTMX ext-ws element, but I can't get a step further. class MessageConsumer(WebsocketConsumer): def connect(self): self.accept() print("connect") self.send( "type": "websocket.send", "text": "<div id='message'>Hi!</div>" ) ... <head> ... <script src="{% static 'common/js/htmx/htmx.min.js' %}" defer></script> <script src="{% static 'common/js/htmx/ext/ws.js' %}" defer></script> ... </head> ... The HTMX.js and the ws.ss gets loaded correctly at the client's browser. <div id="messages-container" hx-ws="connect:/ws/messages/" {# hx-ext="ws" ws-connect="/ws/messages/" does not work at all #} > <div id="message"></div> </div> If I use the old HTMX-builtin hx-ws method, at least the websocket connects. But I can't get a message to the HTMX element (I thought the #message div should be replaced). If I use the new-style (HTMX extension) syntax (hx-ext="ws" ws-connect...) Can anyone point me to the right direction? -
How to auto refresh API tokens in my backend?
I'm using Pinterest and Facebook API to get some data, the problem is that I don't know how to auto refresh them when they expire. Both tokens are store in my Django backend in setting.py -
Smartcard authentication using Django
Is there a way to enable CAC authentication with Django? I've been looking at articles stating to use OpenSSL, pkcs11, etc, but no clue on how to actually get python to parse x509 certificates. Goal is to be able to authenticate users via their smart cards on a custom django web server i'm building out. So far, I've gotten it to work locally by using bash pkcs11-tool to parse cac certs, but no clue on how to do this server-side if a user was to browse to my webserver to be prompted for a cac cert. hope this makes sense. -
create multiple workbooks with xlsxwriter in Django/Python
I am in the middle of a reporting function which will break up reports into different workbooks then zip the files and send them out to users. At this time, I get a successful book for the second iteration, but the first iteration seems to be overridden/lost when the bytesIO object reinitializes on subsequent iterations. def runPullReports(): sharedOrderFxs.sendEmail([], 'Starting..', "Running") start = datetime.date(2022, 7, 7) #now start += datetime.timedelta(2)#running sunday means we've already run tuesday labels dateList = [start + datetime.timedelta(days=x) for x in range(4)] food_programs = list(refModels.FoodProgram.objects.all().values_list('id', flat=True)) pack_list = ['HOT PACK', 'COLD PACK'] workBookList = [] SA = refModels.ServiceArea.objects.all() for service_area in SA: fileName = str(service_area.name) + '.xlsx' output = BytesIO() ## Other Processing here irrelevant to the question book.close() output.seek(0) # resetting BytesIO() buffer before we add workbooks to the list, since we're using BytesIO again in the generate_zip function workBookList.append((fileName, output)) archive = generate_zip(workBookList) dateRange = f'{dateList[0].month}-{dateList[0].day}_{dateList[-1]}' #email send fnx sending archive. The Zip/Email function: def generate_zip(files): zip_buffer = BytesIO() with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file: for fName, file in files: zip_file.writestr(fName, file.read()) zip_file.close() zip_buffer.seek(0) return zip_buffer.getvalue() -
Handling static files and venv during deployment to AWS EB
I have my Django project up static files set-up like this: STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [(BASE_DIR / 'staticfiles'), ] I add static to .gitignore, this way I put my files in staticfiles folder and upload them to git. And on the deployment server I run collectstatic to move them to the static folder. This worked ok until I decided to move the project to AWS EB. Because I have to run collectstatic before eb deploy it ignores my static folder during deployment (since it is in .gitignore). A solution I used before was adding .ebignore with staticfiles in it instead of static. Only with this project it throws an error: An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/ve/lib64: no such file or directory From what I've read it has something to do with simlinks in aws cli that were created for my venv folder ve. But I can't find a fix for it. So I have two questions: What is the proper way to handle static files with Django? How to remove venv folder from eb? -
Django email contact me form
So I'm working on this django web app and I want to create a contact me form for my client. My client wants the users of his website to be able to send him emails directly from the form available on the platform. But my client uses a free yahoo email address. I'm kind of confused of where to begin. But here is my suggested approach see if you can give me an advice: 1- create a form in the forms.py with the different fields of the form. 2 - link the form to the template. 3- create the view for the contact form. 4- add the path in the url pattern. I read an article that says I need to go through an email service like SendGrid to actually send an email. But it said that I need a professional account to be able to do it. I really appreciate your attention. -
How do I override this pattern? django
I'm trying to override the template located in the forms/templates/django/forms/widgets/input_option.html directory, but it's not working for me. Is it possible to do this at all? -
Publishing Django project in EC2 AWS instance
I am trying to publish a Django Web page in an instance of AWS. I have configured the EC2 instance based on Windows machine, with elastic IP to get a fixed public IP. However, when I try to run the Django project, I can only assign the private IP. In this case, if, after running the project, I try to access the Web from the public IP, I cannot access the Web site (just an error message from the browser warning about the impossibility to access the site). Below, the two snapshots of the execution. While the first one shows how with the private IP it works, the second one depicts the error I am receiving. I have tried with the 0:8000, but also with <public_IP>:8000 without success. In the case of setting the public IP, I got Error: That IP address can't be assigned to. Last but not least, in the settings.py file, I have included ALLOWED_HOSTS = ['*']. Could you let me know how to proceed, please? Many thanks in advance. -
Nginx and Django/Wagtail : Origin checking failed - null does not match any trusted origins
When i try to log on my admin page in wagtail, i get this error. My settings.py has this line : CSRF_TRUSTED_ORIGINS = ["http://localhost","http://domain","http://server_ip","https://localhost","https://domain","https://server_ip"] Where server_ip is my ip and domain is my domain. However the error message might to be dealing with nginx : the origin is not present in the request as django finds null as origin. I have a reverse_proxy set in nginx as follows: location /api { proxy_pass http://backend:8000/api; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 20M; } What can I add so django finds a correct origin? -
Django Friends all declined
I am trying to add friends in a django app and I try to do it with this way. I created a new table named Friends where there is no foreign key. It looks like this: class Friends(models.Model): name = models.CharField(max_length=200) hisname = models.CharField(max_length=200) answer = models.CharField(max_length=200) And in the views.py I wrote: def seeit(request,aname): friends = Friends.objects.filter(hisname=aname).all() if request.method == 'POST': for i in friends: if 'accept' in request.POST: request3 = Friends.objects.filter(name=i.name).first() setattr(request3,'answer', 'yes') request3.save() elif 'decline' in request.POST: request2 = Friends.objects.filter(name='5319').first() request2.answer = 'no' request2.save() return render(request,'all.html',{'requests':friends}) In all.html it just shows the friend requests and you can accept or decline it. But when I run it I don't get an error but if for example, I declined a friend request then all of them are declined and if I accept one then all of them are accepted. What should I do? Thanks. -
Frameworks for 2022
I study computer engineering and recently I got a job as Full Stack Wordpress Developer I bought 3 courses on Udemy 2 about PHP and OOP and 1 for Laravel but after searching on the internet I saw that PHP and frameworks like Laravel and Symphony are dying and they aren't matched for frameworks like Nodejs,ASP.NET MVC and etc,is that true?And if it does where am i focus on? I am thinking about MERN (MongoDB, Expressjs, Reacyjs, Nodejs) courses and django, will they give me a better future? -
Why is my url parameter undefined in Django?
I'm trying to pass a url parameter to a Django's generic DeleteView. I've included the parameter in my urls.py, but it still comes back undefined. This is my code: My view in views.py: class Delete(post_id, DeleteView): #error on this line ... Urls.py urlpatterns=[ ... path('delete/<uuid:post_id/', views.delete.as_view(), name='DeleteView'), ... I have no clue what the issue is, as I've passed variables to views before dong this same simple process. I have also tried passing Deleteview first like class Delete(DeleteVew, post_id): but that didn't work either. Thank you for your time. -
Django pass Sql query data as context
I want to pass the result of sql query as context to template file in the given manner- The following are the contents of the view file:- m1 = medium + "%" if medium!='' else "%" s1 = size + "%" if size!='' else "%" a1 = age + "" if age!='' else ">0" c1 = city + "%" if city!='' else "%" raw_query = "SELECT i.item_name, i.artist_name_id, i.medium, i.size, i.image_url_1, image_url_2 from home_itemlist as i JOIN home_userdetail hu ON hu.user_id = i.artist_name_id WHERE i.medium ilike '"+ m1 +"' and i.size ilike '"+ s1 +"' and hu.age "+ a1 +" and hu.city ilike '"+ c1 +"' " cursor = connection.cursor() cursor.execute(raw_query) # results = cursor.fetchall() results = [] print(results) for row in cursor.fetchall(): print(row) The template.html file:- <div class="row"> {% for itemlist in itemlists %} <div class="col-md-3 mb-2"> <span class="card h-100"> <a href="{{ itemlist.get_absolute_url }}"><img src="{{ itemlist.image_url_1 }}" class="card-img-top" alt="image"></a> <div class="card-body text-center"> <h5 class="card-title"><a href="{{ itemlist.get_absolute_url }}">{{ itemlist.item_name }}</a></h5> <span>{{ itemlist.artist_name }};</span> <span>{{ itemlist.medium }};</span> <span>{{ itemlist.size }};</span> <span>{{ itemlist.description|truncatechars:"10" }}</span> {% comment %} <a href="{{ itemlist.get_absolute_url }}" class="d-grid btn btn-primary">View Details</a> {% endcomment %} </div> </span> </div> {% endfor %} </div> -
RichTextUploadingField in django 2.2.6 not show in admin panel
i have a problem with my website that is the ckeditor filed when i use RichTextUploadingField it not show in admin panel , but when i use RichTextField it work and show perfect in admin panel but i want the RichTextUploadingField to upload pic so what is the problem here and how to fix it .. models.py : from django.db import models from django.urls import reverse from django.utils.text import slugify from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class Android(models.Model): app_content = RichTextUploadingField(blank=True,null=True) urls.py: path('ckeditor', include('ckeditor_uploader.urls')), settings.py: INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = "media/" STATIC_URL = '/static/' STATIC_ROOT = os.path.join('/home/myapp/public_html/static') -
How can I fix 'IntegerField' object has no attribute 'is_hidden'?
Form kept working well till before adding this('product_price':forms.IntegerField(widget=forms.FileInput(attrs={'class': 'form-control'}))). Where did the actual problem occur? How can I fix this bellow error? forms.py: class add_product_info(forms.ModelForm): class Meta: model = Products fields = ('product_title','product_price') widgets = { 'product_title':forms.TextInput(attrs={'class':'form-control'}), 'product_price':forms.IntegerField(widget=forms.FileInput(attrs={'class': 'form-control'})) } template: <form action="" method="POST" class="needs-validation" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <div class="d-flex align-items-center"> <button type="submit" class="btn btn-outline-dark ms-auto" style="font-size: 13px;">Add</button> </div> </form> Error: AttributeError at /add_product/ 'IntegerField' object has no attribute 'is_hidden' Request Method: GET Request URL: http://127.0.0.1:8000/add_product/ Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'IntegerField' object has no attribute 'is_hidden' Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\forms\boundfield.py, line 214, in is_hidden Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce ' 'site\\env\\lib\\site-packages'] Server time: Tue, 05 Jul 2022 17:47:30 +0000 -
django form field displayed out of order
I have this form and model for a group: class GroupForm(forms.ModelForm): class Meta: model = Group fields = ('leader', 'description', 'size', 'max_size', 'motto') widgets = { 'size': forms.CheckboxInput(attrs={'id': 'size'}), 'max_size': forms.TextInput(attrs={'type': 'hidden', 'id': 'maxSize'}), } The creator of the group has an option to check yes for size and on doing so, I used javascript to change the type of max_size to show. In my create_group.html template: <script> let size = document.getElementById('size') let maxSize = document.getElementById('maxSize') let checked = false size.onclick = () => { checked = !checked if (checked === true) { maxSize.type = 'show' } else { maxSize.type = 'hidden' } } </script> Now, this works fine, the only problem is that the fields are displayed out of order. When the page loads, max_size is false and its field is not displayed. Which is good. However, when the user checks that group has a size, and, subsequently, the max_size has a display of show, the field shows up after the motto field and not in its correct order according to fields = ('leader', 'description', 'size', 'max_size', 'motto'). Furthermore, the max_size field is included inside the motto element itself and not as its own field: vs. the other fields … -
Can not run Django project
I´m having a problem running my old django project. Its giving an error after i run py manage.py. I tryed to use the command py manage.py makemigrations Traceback (most recent call last):File "C:\Users\ricardo martins\Downloads\LES-fosquito\LES-fosquito\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Users\ricardo martins\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\ricardo martins\Downloads\LES-fosquito\LES-fosquito\processes\admin.py", line 4, in <module> from tinymce.widgets import TinyMCE ModuleNotFoundError: No module named 'tinymce' -
How to override admin.ModelAdmin class from site-packages?
i want to override help_text for some model in site-packages. but i obviously can't just change it in package because it will not be saved after updating packages and some other actions. crontab = models.ForeignKey( CrontabSchedule, on_delete=models.CASCADE, null=True, blank=True, verbose_name=_('crontab'), help_text=_('Use one of interval/crontab'), ) probably i have to create some app and override the whole thing in admin.py but i'm not sure it is a good practice. also there is option with localize i consider but i still will have to create an app for that. -
Django materialized view migration problem on update
We are building a library in Django (v4.0) with Postgres (v13). This library is going to be the core for our company, so we have to be careful with the migrations. The problem is with Django migrations when we update the base table for any materialized view. Models: Base class Customer(models.Model): external_id = models.CharField(max_length=50, unique=True) class Meta: db_table = "customer" Materialized View class CustomerDetailView(models.Model): id = models.CharField(max_length=50, primary_key=True) external_id = models.CharField(max_length=50, unique=True) class Meta: managed = False db_table = "customer_detail_view" Migrations: "0001_initial.py" Created by Django class Migration(migrations.Migration): ... operations = [ migrations.CreateModel( name='CustomerDetailView', fields=[ ('id', models.CharField(max_length=50, primary_key=True, serialize=False)), ('external_id', models.CharField(blank=True, max_length=50)), ], options={ 'db_table': 'customer_detail_view', 'managed': False, }, ), migrations.CreateModel( name='Customer', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('external_id', models.CharField(blank=True, max_length=50, null=True, unique=True)) ], options={ 'db_table': 'customer', }, ), "0002_customer_detail_view.py" Created manually class Migration(migrations.Migration): dependencies = [ ("customers", "0001_initial"), ] operations = [ migrations.RunSQL( """ DROP MATERIALIZED VIEW IF EXISTS customer_detail_view; CREATE MATERIALIZED VIEW customer_detail_view AS SELECT cus.id, cus.external_id, FROM customer cus; CREATE UNIQUE INDEX customer_detail_view_pk ON customer_detail_view(external_id); """, "DROP MATERIALIZED VIEW customer_detail_view" ) ] "0003_alter_customer_external_id.py" Created by Django after a dummy modification on the base table class Migration(migrations.Migration): dependencies = [ ('customers', '0002_customer_detail_view'), ] operations = [ migrations.AlterField( model_name='customer', name='external_id', … -
Running django application via SSH on Windows
This question is related to the testdriven.io series of articles on how to build and deploy your Django application. In detail, my question is relatad to the second article of the three. Everything works fine as we build locally the application with nginx and gunicorn. Then, he uses a linux command ssh user@your-ip-or-domain to connect to the host, which I think might be the name of the domain he suggests to create with freenom.com. Now, I am on a Windows machine and have no idea how to perform this operation that he does not explain (should we copy the project on a virtualbox with linux? should you run an image of linux with docker?). The article I am referring is this in the "Running the Containers" paragraph. I am looking for a deeper explanation of that phase. Thanks a lot. which I do not know how to perform on Windows. -
Remove all items from cart after checkout in Django
I have a simple e-commerce app, and I'm trying to clear the cart after pressing the 'Proceed to checkout' button. After pressing it I should redirect to cart and I shouldn't see any OrderItem in the cart. Also the database instance should be deleted. How can I do? store/models.py class Item(models.Model): name = models.CharField(max_length=50) price = models.FloatField() def __str__(self): return self.name class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" def get_total_item_price(self): return self.quantity*self.item.price def get_final_price(self): return self.get_total_item_price() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total store/views.py class HomepageView(generic.ListView): model = Item template_name= 'store/index.html' context_object_name = 'item_list' class DetailView(generic.DetailView): model = Item template_name='store/detail.html' class CartView(generic.View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'store/cart.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return redirect("/") def checkout(request, user_id): #code to remove all items from cart return redirect('store:cart', user_id=user_id) -
Why do my if condition is not executing as expected in Django template?
what i am supposed to do? Okay, so I have a registration form and I want to verify if django message == "password not strong enough" and if this condition is true then execute this HTML code snippet <div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert"> <p style="margin-top: 0; margin-bottom: 0rem; text-align: center;"> Your password is not strong enough. New passwords must: <li>Be at least minimum eight to maximum 16 characters long.</li> <li>Contain one or more numbers.</li> <li>With at least one small and one capital letter.</li> <li>Include at least one special character like: [@#(/)+]</li> </p> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> and if the above code doesn't execute then show a message coming from my Django views, which is written as follows <div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert"> <p style="margin-top: 0; margin-bottom: 0rem; text-align: center;" {% if message.tags %} {% endif %}> {{ message }} </p> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> message conditions from views.py file if username_exists: messages.warning(request, "Username is not available") if email_exists: messages.warning(request, "Email id is already registered") if not pass_match: messages.warning(request, "Grr.. password does not match") if not … -
TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile while using eyed3
so i was using eyed3 to show information about song like artist and etc. but when i tried using it in django, it goes error : TypeError: expected str, bytes or os.PathLike object, not TemporaryUploadedFile i just tried like example, but it's not work. here's my views.py: def homepage(request): form = AudioForm() last_audio = Audio_store.objects.all().last() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): audio = form.cleaned_data.get("audio") print(audio) audios = eyed3.load(audio) print (audios.tag.artist) print (audios.tag.album) print (audios.tag.title) context={'form':form, 'last_audio':audio} print(context) form.save() return render(request, "homepage.html", context=context) context={'form':form, 'last_audio':last_audio} return render(request, "homepage.html", context=context)