Dajax example doesnt work - django

So I'm trying to get the hang of Dajaxice for Django. Everything was fine till I used Dajaxice, but just I tried Dajax I gat trouble.
I made a new project and inside it an example app. So then I made a button - Button 1 in a template which uses a function in ajax.py, this worked fine. Button 2 did not work though, which uses the second function in ajax.py. I have pasted the index.html and ajax.py code below. How can I get the Button 2 to work, and make it do what I want it to do.
index.html
{% load dajaxice_templatetags %}
{% dajaxice_js_import %}
<input type="button" value="Button 1" onclick="Dajaxice.example.sayhello(my_js_callback);"/>
<br>
<input type="text" id="text"/>
<input type="button" value="Button 2" onclick="Dajaxice.example.saytext(my_js_callback, {'text':$('#text').val()});"/>
<script type="text/javascript">
function my_js_callback(data){
alert(data.message);
}
</script>
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def sayhello(request):
return simplejson.dumps({'message':'Hello World!'})
#dajaxice_register
def saytext(request, text):
return simplejson.dumps({'message':'%s' % text})

this has been said multiple times over the last few years. The Dajaxice project is a bad idea and you should just use JQuery and AJAX instead to post/receive data to your django view.
The author has stated on his Github page; "These days using this project is a bad idea."

Related

HTMX for messages from the backend in django

I wanted to use HTMX to show messages from django backend after a lot of trial and error I ended up with a working solution, that I want to leave behind for anyone looking for it - also, please feel free to post your suggestions. Unfortunately, besides a little example from the htmx-django package, there is almost no tutorial material available. Be sure to check the example out, as it covers some basics specially for django users!
For HTMX we need a little element somewhere in the DOM that HTMX can work (swap for example) with. Place for example a
<div id="msg">
{% include "app/messages-partial.html" %}
</div>
somewhere on your index.html. Now we want to use this element to fill it with content, if the need arises. Let's say we click a button, that communicates with a view and the answer gets posted. In django the response is created using render:
class TestView(TemplateView):
template_name = "index.html"
def get(self, request, *args, **kwargs):
...
class_code = """class='alert alert-dismissible fade show'"""
msg_str = """testmessage"""
msg_btn = """<button type='button' class='close' data-dismiss='alert'>x</button>"""
msg = mark_safe(f"""<div {classcode}>{msg_str}{msg_btn}</div>""")
return render(request, "app/messages-partial.html", {"msg": msg})
and a corresponding path in urls.py:
path("action/", views.TestView.as_view(), name = "test"),
I created a simple messages-partial.html:
{% if msg %}
{{ msg }}
{% endif %}
So what I wanted is, when I triggered the the view, the {{ msg }} gets replaced (swapped) by HTMX to the content of the response. Therefore I implement the HTMX part somewhere else on the index.html as follows:
<div class="..."
hx-get="/action"
hx-swap="innerHTML"
hx-target="#msg" >
<button class="btn btn-primary">TEST</button>
</div>
The former <div id="msg">...</div> will swap with {{ msg }} (and I included the typical django-messages close button).
Thanks to the htmx discord channel where friendly people shared their knowledge with me.

Calling a django function from html button

I am new to django.
What i am trying to do is to run a django function from my "main.py" file when a html button is pressed.
what I've done is created a button in html:
<input type="button" value="Formatting excel" onclick="excel_formatting">
And then in my "main.py " I have:
def excel_formatting():
print("hello world")
return()
The website loads fine, but when i press the button nothing is printed in the terminal. i must be doing something wrong.
you can have a button that is a link and when the user presses the button it will redirect them to the link which will activate the function.
views.py
def button(request):
print('hello')
urls.py
from . import views as main_views
path('button/', main_views.button, name="button"),
index.html
<a href="{% url 'button' %}" class="btn btn-primary">Button</button>

How can I register a custom filter in Django

I want to register a simple filter in Django in order to concat two strings in a template. I found many questions about this here, but seemingly no answer solves my problem.
settings.py
'MedAbrDirk.apps.MedabrdirkConfig',
'MedAbrDirk.templatetags',
MedAbrDirk/templatetags/my_tags.py
from django import template
register = template.Library()
#register.filter
def kette(arg1,arg2):
return str(arg1) + str(arg2)
MedAbrDirk/templates/MedAbrDirk/base.html
{% load my_tags %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li class="dropdown">
Rechnungen<span class="caret"></span>
<ul class="dropdown-menu">
{{'test'|kette:'test2'}}
<li>Rechnung eingeben<span class="sr-only">(current)</span></li>
Still, in the browser I get: "Invalid filter: 'kette'"
I have no idea what causes this. I have deleted the pychache folder, I have restarted my gunicorn several times.
Any advice?
docs To register custom filter with decorators you can do either of
# function name is taken as filter name
#register.filter
def kette(arg1, arg2):
# code
OR
# value in name argument is taken as filter name
#register.filter(name='kette')
def kette(arg1, arg2):
# code
You can either add name name argument in filter() or remove the parenthesis from filter()
You say you have a init.py file. In-order for python to consider it as a package __init__.py file should be there in templatetags folder. Not init.py.
So, In your app folder you should see a structure like this for custom template tags:
MedAbrDirk/ #app folder
MedAbrDirk/templatetags/
MedAbrDirk/templatetags/__init__.py # should have double underscore on both the sides
MedAbrDirk/templatetags/my_tags.py
Thanks for your help. It seems I figured it out by accident. In another app I also had a folder templatetags with a file my_tags.py. I thought these would be separately handled by Django. Obviously this is not the case.
So, after renaming the module, now it works.

How to make chromium headless wait till the reactjs is loaded with the data from the fetch call

I have a Django project and recently I am trying to convert the front end to react one view at a time. I am using Django-hardcopy(https://github.com/loftylabs/django-hardcopy) to create a pdf report for me which was working for Django templates.
But now that I am using react, the chrome headless does not wait till the fetch call is completed and just prints out the empty page in the pdf as react first renders the DOM element (so the data is still not fetched).
I did go through some StackOverflow answers like using
--virtual-time-budget=10000
But did not work.
I tried to delay the reportview with
import time
time.sleep(5)
I really cannot use react to render pdf at this moment because of some other restrictions.
Is there any way to do this?
If you guys need any more info let me know.
Just an overview of the code I have:
views.py
class ReportView(LoginRequiredMixin, PDFViewMixin):
def get_context_data(self, pk, **kwargs):
....
mytemplate.html
<div class="react-baseline-div">
<div id="baseline-energy-root"></div>
</div>
{% compress js %}
<script src="{% static 'react/build_files/_reactify.js' %}"></script>
<script src="/static/react/build_files/baseline_energy.chunk.js"></script>
<script src="/static/react/build_files/main.baseline_energy.chunk.js"></script>
{% endcompress %}
This has the react build files and the <div> that connects to react app(react app renders perfectly) Just not in the pdf.

Django form "takes exactly 1 argument (2 given) " error - possibly related to CSRF?

I am attempting a fairly simple form on Django 1.3, and am trying to understand how CSRF works.
I think I've followed the three steps detailed on the Django site, but am still unable to make the form work.
The form displays when the URL is loaded, however upon hitting the submit button, I get the following error:
TypeError at /txt/ txt() takes exactly
1 argument (2 given)
Here's the actual code:
views.py:
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
def txt(request):
if request.method == 'POST':
msg="txt received"
else:
msg="nothing in POST"
return render_to_response('base.html', locals(), context_instance=RequestContext(request))
The HTML:
<body>
<form action="txt/" method="POST">{% csrf_token %}
From <input type="text" name="From"><br>
To <input type="text" name="To"><br>
Body <input type="text" name="Body"><br>
<input type="submit" value="Search">
</form>
{{ msg }}
</body>
I know I haven't done a forms.py etc. but I was just trying to get the basic functionality up and going. I think this code would have worked in previous versions of Django, and am unsure why its not working this time.
The error looks like your view function is getting more arguments than it is setup to accept. As you have it shown above, the view only accepts a single argument: the request.
If your URL pattern for this view is configured with a capturing group, or you are adding extra arguments via the optional dictionary or the kwargs parameter to url(), then those extra arguments will be given to the view function and could cause the error you're seeing.