Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending a POST request through Javascript on Django - failed to retrieve data
I'm trying to send a POST request to my Django view using plain javascript (I don't want any unnecessary libraries involved). The data is not sent through a form, but by using fetch. For now I just want to be able to manipulate the request.POSTin my views.py, nothing more. Here's my code: Javascript let article = document.querySelector('article') articleId = article.getAttribute('data-product-id') # some other stuff fetch("{% url 'shop:shoplist' 1 %}", { method: 'POST', dataType: "application/json", data: {'article_id': articleId}, headers: {'X-CSRFToken': csrf_token} }) Python if request.method == 'POST': testing = request.POST return JsonResponse({'test': testing}) The request is sent, the csrftoken is received correctly, but the request.POST returns just <QueryDict: {}>, instead of what I'm expecting (headers, data...). I've searched and found a lot of similar questions, the most similar one being this one, but still I can't seem to find a solution. Any idea? -
How to render ete3 tree in django template?
I'm very new in django and ete3 toolkit programming. I want to generate phylogenetic tree with ete3 toolkit in views.py and render tree's svg image to template. When i tried like below views.py matrix = """ #Names\tcol1\tcol2\tcol3\tcol4\tcol5\tcol6\tcol7 A\t-1.23\t-0.81\t1.79\t0.78\t-0.42\t-0.69\t0.58 B\t-1.76\t-0.94\t1.16\t0.36\t0.41\t-0.35\t1.12 C\t-2.19\t0.13\t0.65\t-0.51\t0.52\t1.04\t0.36 D\t-1.22\t-0.98\t0.79\t-0.76\t-0.29\t1.54\t0.93 E\t-1.47\t-0.83\t0.85\t0.07\t-0.81\t1.53\t0.65 F\t-1.04\t-1.11\t0.87\t-0.14\t-0.80\t1.74\t0.48 G\t-1.57\t-1.17\t1.29\t0.23\t-0.20\t1.17\t0.26 H\t-1.53\t-1.25\t0.59\t-0.30\t0.32\t1.41\t0.77 """ header = 'col1\tcol2\tcol3\tcol4\tcol5\tcol6\tcol7'.split('\t') t = ClusterTree("(((A,B),(C,(D,E))),(F,(G,H)));",text_array=matrix) tree_style = TreeStyle() setup_heatmap(t, tree_style, header) tree_style.show_scale = False tree_style.show_leaf_name = True tree_style.draw_guiding_lines=True context['svg'] = t.render('tree_2.svg', tree_style=tree_style) return render(self.request, self.template_name, context) template.html <div> {{svg|safe}} </div> and I got this dictionary formed string {'nodes': [], 'faces': [[181.0, 30.5, 190.0, 45.5, 3, 'A'], [191.5, 27.5, 212.5, 48.5, 3, None], [211.5, 27.5, 232.5, 48.5, 3, None], [231.5, 27.5, 252.5, 48.5, 3, None], [251.5, 27.5, 272.5, 48.5, 3, None], [271.5, 27.5, 292.5, 48.5, 3, None], [291.5, 27.5, 312.5, 48.5, 3, None], [311.5, 27.5, 332.5, 48.5, 3, None], [181.0, 50.5, 190.0, 65.5, 4, 'B'], [191.5, 47.5, 212.5, 68.5, 4, None], [211.5, 47.5, 232.5, 68.5, 4, None], [231.5, 47.5, 252.5, 68.5, 4, None], [251.5, 47.5, 272.5, 68.5, 4, None], [271.5, 47.5, 292.5, 68.5, 4, None], [291.5, 47.5, 312.5, 68.5, 4, None], [311.5, 47.5, 332.5, 68.5, 4, None], [181.0, 70.5, 191.0, 85.5, 6, 'C'], [191.5, 67.5, 212.5, 88.5, 6, None], [211.5, 67.5, 232.5, 88.5, 6, β¦ -
Django - How can I manage custom payments between users on my platform with Stripe?
I'm trying to create a platform with multiple functionalities, and one of them is a crowfunding of projects, in which the users can post a project and ask for funds. (like kickstarter or indiegogo). I'm working with Django 2.0, Python 3.6 and PostgreSQL and I want to use Stripe for payments. I also read a bunch of the Stripe's API Documentation, and I have some ideas for doing this, but this will be my first API implementation so I would like to do it well (more even talking about payment systems). The main question is: How can I do that multiple users realize payments to another for one project ONLY when the goals of that project are reached? What I think that is the better is to use (Stripe Connect) Express/Custom Accounts to create an account for each user that posts a Project, so I can redirect all the payments to that account. The thing is that I also want to apply a fee for my platform. And I don't know exactly how can I do this. I imagine that Stripe give an option for that to evade doing two transactions in my own backend (one for the project's user β¦ -
Breadcrumbs for Django site
I would like to use this app for generate the breadcrumbs on my site. When I insert the tags in my base template html, I don't see nothing. What I've wrong? The version of django that I use(2.1) is supported. Below my base.html {% load static %} {% load django_bootstrap_breadcrumbs %} <!doctype html> <html lang="it"> <head> ..... </head> <body> <div id="carouselFade" class="carousel slide carousel-fade" data-ride="carousel"> ..... </div> {% if request.user.is_authenticated %} <div class="bg-dark"> ..... </div> {% endif %} <nav class="navbar navbar-expand-lg navbar-light bg-light shadow sticky-top"> ..... </nav> <div class=""> {% block breadcrumbs %} {% clear_breadcrumbs %} {% breadcrumb "Home" "list_service" %} {% endblock %} </div> <div class="container-fluid mt-3"> {% block content %} {% endblock content %} </div> <footer class="mt-3 rounded"> ..... </footer> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </body> </html> list_service is the name of the home path: path("", ListServices.as_view(), name="list_service"), -
How to create dinamic model from request User
i'would like create dinamic model in Django with the request user. Example the user need create 4 leves for categories for products or 10,20, etc... how i create this tables(models). in a form the user write numbers of levels categories and next i should create this tables with this structure: ________________________ name| description |state| _________________________ firs| first categ | 1 | ....| ............|.....| and this for each level. but i dont know how create this please any suggest or idea.. sorry but dont write code but i dont know where to start. -
Check in a Django template if all parameters are available for URL-generation (#NoReverseMatch)
Description I have a HTML template that is used by several views. It's all the same but one HTML link is different. So I thought about checking in the template what's the request.path and change the link accordingly. Problem Because not all parameters are passed to the template by all views I get an NoReverseMatch. This was my idea for the template: {% url "first" as first_url %} {% if first_url in request.path %} <button type="button" onclick="$.get("{% url 'foo' a b c %}");">Foo</button> {% endif %} {% url "second" as second_url %} {% if second_url in request.path %} <button type="button" onclick="$.get("{% url 'bar' a %}");">Bar</button> {% endif %} Question Is there a way to use Django's {% url %} though not all parameters are available? Or do you need to extend the template? -
Changing table name of a model in view
I need to change the table name of a model during the process: in my view: def list_tables(request, *args, **kwargs): for suffix in range(0, 100): my_model._meta.db_table = "table_name_{}".format(suffix) print(my_model.objects.all().query) and the result is: SELECT "table_name_0"."field_1", "table_name_0"."field_2" from "table_name_0" SELECT "table_name_0"."field_1", "table_name_0"."field_2" from "table_name_1" So when I change the _meta.db_table in process, it changes the table names in select and from statement in the first query, but in the second query it changes from statement but the table name in select remains as in previous table_name. So I got this error in second query: django.db.utils.ProgrammingError: missing FROM-clause entry for table "... Anyone has any offer for me? -
Getting 3 previous items in django queryset
I know there are similar questions but they don't answer mine. Say I have a sequence of letters: A B C D E F G I want to pass only 3 letters to my template based on a specific letter, and those 3 letters must be previous ones. For example, If this letter is D then it must be: A B C If it's E then it's: B C D and etc. I understand the way slicing works but all I can do is to get the first 3 letters of my query set: context['words'] = WordsAndLetters.objects.exclude(letter=letter).order_by('letter')[:3] I'm also excluding my specific letter to just show 3 previous. How can I get to the right result? -
How to get key(column name)-value pair from a Select query using default connection in Django
I have 4 application in one Django Project. I am using the default Postgres database connection which I have included it in my setting.py file. The object django.db.connection represents the default database connection. To use the database connection, I call connection.cursor() to get a cursor object. Then, call cursor.execute(sql, [params]) to execute the raw Postgres queries and cursor.fetchone() or cursor.fetchall() to return the resulting rows. Now, in one application I want to use the (connection.cursor(cursor_factory = psycopg2.extras.RealDictCursor)) to get the records in a key(column name)-value pair, which is provided by psycopg2.connect but the default connection that I have is not compatible with cursor_factory = psycopg2.extras.RealDictCursor. How do I get a key(column name)-value pair from the database by using the default connection? from django.db import connection cur = (connection.cursor(cursor_factory = psycopg2.extras.RealDictCursor) cur.execute("SELECT * FROM sometable") data= cur.fetchall() ERROR: cursor() got an unexpected keyword argument 'cursor_factory' -
django request transport to custom database backend
My team is developing secure django project and we stacked with transport Django request into custom database backend. We made such an algorithm for GSSAPI(SPNEGO) authentication in django and delegating user credentials for server querying on behalf of user: if 'HTTP_AUTHORIZATION' in request.META: kind, initial_client_token = request.META['HTTP_AUTHORIZATION'].split(' ', 1) if kind == 'Negotiate': server = 'HTTP@server.domain.ru' _ignore_result, krb_context = kerberos.authGSSServerInit(server) kerberos.authGSSServerStep(krb_context, initial_client_token) principal = kerberos.authGSSServerUserName(krb_context) _ignore_result = kerberos.authGSSServerStoreDelegate(krb_context) conn = psycopg2.connect( host='krb5-dbhost', user=principal, dbname='db', ) cursor = conn.cursor() cursor.execute("SELECT version()") records = cursor.fetchall() this works well in django-view. Kerberos server can authorize user and cache krb5-ticket for credentials delegation to query in psycopg. Now we need to inject it into django. We want is inherit postgresql database backend like this: from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper class CustomDatabaseWrapper(DatabaseWrapper): def __init__(self, *args, **kwargs): super(CustomDatabaseWrapper, self).__init__(*args, **kwargs) def get_connection_params(self): '''We need to customize this function, We need get request here when query processed by web interface,''' #.... the source code could be here, but it is not necessary return conn_params So the question is: "How can we get request.META (for get user`s Negotiate token) in get_connection_params() function, and how can we divide users request from web interface from management commands." Sorry for my english β¦ -
chined dropdown menu using Django and ajax does not work
I have two models with one to many relation. In html form I want the second dropdown menu changes based on the first dropdown menu selection. The following are the models: class Post_Category(models.Model): category_name = models.CharField(max_length=64, unique=True) class Post_Sub_Category(models.Model): category_name = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category_name = models.CharField(max_length=64) Here is the html form: <form id="headerform" class="breadcrumbs-form" method="GET" action="{% url 'search' %}" data-action="" name="headerform" enctype="multipart/form-data" formnovalidate data-sub-categories-url="{% url 'ajax_load_subcategories' %}"> <ul class="breadcrumbs" id="menu"> <!-- category options --> <span> <li class="crumb section"> <select name="h_qcc" onchange="headerform.submit()"> <option value="{{category_name}}"> {{category_name}} </option> </option> {% for category in all_p_categories %} {% if category.category_name != category_name %} <option value="{{category.category_name}}"> {{category.category_name}} </option> {% endif %} {% endfor %} </select> </li> </span> <!-- sub_category options --> <span> <li class="crumb category"> <select class="js-only" name="h_qsc" onchange="headerform.submit()"> <option value="{{sub_category_name}}"> {{sub_category_name}} </option> {% for sub_category in all_p_sub_category %} {% if sub_category.sub_category_name != sub_category_name %} <option value="{{sub_category.sub_category_name}}"> {{sub_category.sub_category_name}} </option> {% endif %} {% endfor %} </select> </li> </span> </ul> </form> the Ajax script : <!-- to load subcategory based on category selection --> <script type="text/javascript"> $("#id_category_name").change(function(){ var url_subΩcategory = $("#headerform").attr("data-sub-categories-url"); // get the url of the load_subcategories view var categoryId = $(this).val(); // get the selected category ID from the HTML input $.ajax({ // initialize an β¦ -
Package installed with venv not found in Django settings
I started my django project with venv. I created a venv and installed django there. Now I needed another package django-ckeditor and I installed it with pip inside my venv this way. (env) X@Z:~/work/mod/website$ pip install django-ckeditor And it was installed successfully. If I go to my python-shell from Pycharm and type import ckeditor there's no error. But when I try to include it in the django settings.py django does not find it. I included it in the INSTALLED_APPS section and the library name I included is ckeditor. My project structure is venv mysite |--mysite |--settings.py How to resolve this issue? -
Iteration of dictionary in django template
i have a data in json format. { "0": { "id": "35", "user_id": "1922", "amount": "100", "currency_id": "153", "content_ids": "17408", "invoice_id": "9622f3f5b248d", "order_number": "17288421SJ152931K", "gateway_response": "{\"TIMESTAMP\":\"2018-10-25T14:33:46Z\",\"CORRELATIONID\":\"9622f3f5b248d\",\"ACK\":\"Success\",\"VERSION\":\"57.0\",\"BUILD\":\"46457558\",\"AMT\":\"100.00\",\"CURRENCYCODE\":\"USD\",\"AVSCODE\":\"Y\",\"CVV2MATCH\":\"S\",\"TRANSACTIONID\":\"17288421SJ152931K\"}", "created_date": "2018-10-25 20:03:44", "ordered_on": "Thu, Oct 25th '18", "currency_code": "USD", "currency_symbol": "$", "content_details": { "fid": "17408", "id": "4f6b08955b1fc1049cc51869f36b1853", "name": "Carol of the Bells SATB - arr. Jay Rouse", "story": null, "content_types_id": "6", "app_id": "5", "permalink": "carol-of-the-bells-satb-arr-jay-rouse" }, "poster_url": "http://devstudio.cnedocent.com/img/No-Image-Vertical.png", "seller_details": { "email": "afixi.gayadhar@gmail.com", "first_name": "Gayadhar khilar" }, "price_details": { "price": "100", "price_id": "1", "code": "USD", "symbol": "$" } }, "code": 200, "status": "OK" } I am trying to iterate in django template respective items.I am getting this data by rendering it from view.py end return render(request,self.template_name,{'data':r.json()}) and iterating it in django template,problem is i have one set of data so it should iterate once but its getting iterate thrice! In frontend its showing one full data and other twos are empty with respective htmls. I have double checked that i'm getiing one dictionary not three! So where am i getting wrong! Please be correcting me. {% for k,v in data.items %} <tr> <td width="10%"><img src="{{v.poster_url}}" width="163" height="105" class="img-responsive"></td> <td width="30%" data-title="File Name"> <div class="order_heading">{{v.content_details.name}} <span>Sellar: {{v.seller_details.first_name}}<br/></span> <!--License up to: 19 August, 2019--> </div> </td> β¦ -
Django: using html templates TemplateDoesNotExist
I've been writing my first Django app and hit a problem with using templates. No matter how I format the url for the template I receive the TemplateDoesNotExist error. My html is nest in views/ with the core template being views/template.html. I have tried: myapp/views/template.html views/template.html templates/views/template.html <full path to app>/<all variations> None of which can locate the template. I understand the TEMPLATE_DIRS variable may be set at project level but this is app-specific and the views/ directory is not purely for templates. I don't think I should add to the url_patterns since the template shouldn't be accessible directly. I've got this far without them but need to clean up the app. Any advice? -
Adding the primary key to the serializer
I want to add the id field, which is the primary key to each object, in the list I'm returning in my models.py: class Category(models.Model): name = models.CharField(max_length=200) in my serializers.py: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') in my views.py: class ListCategoriesView(generics.ListAPIView): """ Provides a get method handler. """ serializer_class = CategorySerializer def get(self, request, *args, **kwargs): serialized_categories = [] all_categories = Category.objects.all() for category in all_categories: """ I'm filling the object here with the id , and the name """ serialized_item = CategorySerializer(data={ "id": category.id, "name": category.name }) if serialized_item.is_valid(): serialized_categories.append(serialized_item.data) return Response( data=serialized_categories, status=status.HTTP_200_OK ) I'm getting the below reponse : I want to get this response just with the id field added: -
Tips on speeding up django views?
I am trying to do some data analysis for a company(sales, stock, yearly progression and so on). However, I'm finding that the calculation time is enormous(almost 1 minute for a single page with a single line graph). I'ce already checked the queries and they take around 2 seconds(still a lot, but whatever). Using django-debug-toolbar, I've seen that request rendering(which I suppose is the page's view) takes around 50 seconds. Do you guys have any idea of how I could Speed that up? This is the code: Main function for the graph: def get_data_progression(years): result = {} for year in reversed(years): result[year] = { "uscite": 0, "entrate": 0, "magazzino": { "val": 0, "nbr": 0 }, "valorizzazione": 0, "months": [] } for i in range(1, 13): entrate = 0#get_entrate_month(year, i) uscite = 0#get_uscite_month(year, i) m_val, m_nb = get_magazzino_month(year, i) result[year]["months"].append({ "entrate": entrate, "uscite": uscite, "magazzino": m_val, }) result[year]["entrate"] = entrate result[year]["uscite"] = uscite result[year]["magazzino"]["val"] = m_val result[year]["magazzino"]["nbr"] = m_nb result[year]["valorizzazione"] = result[year]["magazzino"]["val"] + result[year]["entrate"] - result[year]["uscite"] return result And this is the function I am trying to optimize. I've left out irrelevant parts: what you see is what takes 50 seconds to load: def get_magazzino_month(year, month): from magazzino.models import ddt_in_item, omaggi_item, inventario_item β¦ -
Django: template display value from many to many through table
I have 3 models and I'm trying to acces and display datas from the "through" table on a many-to-many relation (Django). I try to display 3 things : the artwork image, the translation language used the translated name of the artwork I'm failling to do the last one. It it from the "through" link of the many to many relation); any idea ? Models.py : class Language(models.Model): LANG = ( ('FR', 'FR'), ('EN', 'EN'), ) lang_selected = models.CharField(max_length=3, choices=LANG, verbose_name='Availlable language') def __str__(self): return self.lang_selected class Artwork(models.Model): artwork_image = models.CharField(max_length=100, null=True, verbose_name="Artwork image") version = models.ManyToManyField(Language, through='Artwork_language', verbose_name="link artwork -> language") def __str__(self): return self.artwork_image class Artwork_language(models.Model): Artwork = models.ForeignKey(Artwork, on_delete=models.CASCADE) Language = models.ForeignKey(Language, on_delete=models.CASCADE) artwork_name = models.CharField(max_length=100, null=True, verbose_name="Artwork name") def __str__(self): return str(self.Artwork) + " translated to " + str(self.Language) views.py class Accueil(TemplateView): template_name = 'isa/accueil.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['artwork'] = Artwork.objects.all() context['language'] = Language.objects.all() context['artwork_language'] = Artwork_language.objects.all() return context Template (accueil.html) <h1>Image | Language translation | Translated name</h1> {% for artwork in artwork %} Image : {{ artwork.artwork_image }} <br/> {% comment %} Langue de traduction : {% endcomment %} {% for lang in artwork.version.all %} Language translation : {{ lang }} <br/> Translated β¦ -
How to start a daemon process which can use some django feature?
I have a django project run on the server. Now need to write another long running process(not web server). I hope that the process can use some feature that my django project already provided. Like ORM. For example, I hope to query the db with models I defined in django So how to do it please? -
django migration createsuperuser
I wanted to create a superuser but everytime I run python3 manage.py createsuperuser it says You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. Can you help me please? I'm using Python 3 and Django 2.1.2 -
Loop within django query
Using this link and this link I have written the following code to query for businesses that are within a radius of one of my branches. from django.db.models import Func, F from li_app.models import Branch, Business class Sin(Func): function = 'SIN' class Cos(Func): function = 'COS' class Acos(Func): function = 'ACOS' class Radians(Func): function = 'RADIANS' class Degrees(Func): function = 'DEGREES' def filter_within_distance( branch_kwargs, business_kwargs, radius ): KM_PER_DEGREE = 111.045 branch = Branch.objects.filter(**branch_kwargs)[0] lat_point = branch.branch_latitude long_point = branch.branch_longitude radlat = Radians(lat_point) radlong = Radians(long_point) radflat = Radians(F('business_latitude')) radflong = Radians(F('business_longitude')) Expression = KM_PER_DEGREE * Degrees(Acos(Cos(radlat) * Cos(radflat) * Cos(radflong - radlong) + Sin(radlat) * Sin(radflat))) latitude_delta = radius / KM_PER_DEGREE longitude_delta = radius / (KM_PER_DEGREE * Cos(radlat)) lat_range = (float(lat_point) - latitude_delta, float(lat_point) + latitude_delta) long_range = (float(long_point) - longitude_delta, float(long_point) + longitude_delta) business_kwargs['business_latitude__range'] = lat_range business_kwargs['business_longitude__range'] = long_range return Business.objects.filter(**business_kwargs).annotate(distance=Expression).filter(distance__lte=radius).order_by('distance') Now I would like to modify the above query so that I get all of the businesses within radius of all of my branches. I would like to avoid python loops so if there is any way I can perform loops within the query then that would be awesome. -
Django with uwsgi+nginx serving on http, but once i add listen on 443 and ssl on; doesnt work anymore
I am trying to put my site live, and it work fine on http, but when to use ssl certificates and https I add listen to 443 and ssl on in /etc/nginx/sites-available/drlandivar.conf it doest load anything anymore. here is my /etc/nginx/sites-available/drlandivar.conf upstream django { server 0.0.0.0:8080; } server { listen 443; server_name drlandivar.com www.drlandivar.com; charset utf-8; client_max_body_size 75M; # adjust to taste ssl on; ssl_certificate /etc/nginx/ssl/drlandivar.com/server.crt; ssl_certificate_key /etc/nginx/ssl/drlandivar.com/server.key; location /media { alias /opt/virtualenv/landivarpj/media; } location /static { alias /opt/virtualenv/landivarpj/static; } location / { include /opt/virtualenv/landivarpj/uwsgi_params; include proxy_params; proxy_pass https://django; } } my /etc/nginx/proxy_params proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; #proxy_set_header X-Forwarded-Proto $scheme; in my django project i have in settings: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') i believe its something wrong in proxy_params or in the proxy_pass https://django; regards -
How to precache django html templates using a service worker
I am converting my Django project to a progressive web app, and i am trying to precache my my files for them to be available offline. My problem is, I dont know how to locate my templates (e.g. homepage.html, index.html) to precache them using my service worker. I placed my service worker inside the static folder. My current folder structure looks like this: main/ -- migrations/ -- static/ ---- js/ ------ core/ ------ plugins/ ------ app.js ---- css/ ---- img/ ---- templates/ ------ base.html ------ about.html ------ homepage.html ----*serviceWorker.js* -- __init.py__ -- admin.py -- apps.py -- models.py -- views.py my_second_app/ -- migrations/ -- static/ ---- js/ ------ index.js ---- css/ ---- img/ ---- templates/ ------ base.html ------ user.html ------ page.html -- __init__.py How can I map the HTML templates for my main app and my_second_app on my serviceWorker.js inside the static folder? Thanks in advance for anyone who could help. And let me know if I am doing it wrong :) Anyway, I have successfully precached the static files. This is my code sample. const precached = [ '/', '/screener/', '/accounts/login/', '/accounts/signup/', '/assets/js/now-ui-dashboard.js', '/assets/js/core/bootstrap.min.js', '/assets/js/core/jquery-ui.min.js', '/assets/js/core/jquery.3.2.1.min.js', '/assets/js/plugins/chart.bundle.min.js', '/assets/css/accounts.css', '/assets/css/bootstrap.min.css', '/assets/css/now-ui-dashboard.css', '/assets/css/user.css', '/assets/fonts/nucleo-outline.ttf' ] self.addEventListener('install', function (event) { event.waitUntil( caches.open(staticCacheName).then(cache => β¦ -
Handle POST/GET forms with Django
I'm using different forms (POST and GET) in my Django web application and Bootstrap modal to do that. In my template, user can choose some documents, submit the list of documents which is picked up to a Django form (CustomerForm) in my modal. This CustomerForm lets to send an email with user informations previously filled. My CustomerForm looks like this : class CustomerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) self.fields['country'].empty_label = _('Select a country') self.fields['country'].queryset = self.fields['country'].queryset.order_by('name') self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields['country'].required = True self.fields['institution'].required = False class Meta: model = Customer fields = ['email', 'first_name', 'last_name', 'country', 'institution'] widgets = { 'email': forms.TextInput(attrs={'placeholder': _('name@example.com')}), 'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}), 'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}), 'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}), } I have views.py file : class HomeView(CreateView, FormView): """ Render the home page """ template_name = 'index.html' form_class = CustomerForm def get_context_data(self, **kwargs): # display some things # ... if "DocumentSelected" in self.request.GET: checkbox_list = self.request.GET.getlist('DocumentChoice') document = Document.objects.filter(id__in=checkbox_list) kwargs['selected_document'] = document return super(HomeView, self).get_context_data(**kwargs) def form_valid(self, form): email = form.cleaned_data['email'] country = form.cleaned_data['country'] for checkbox in self.request.GET.getlist('DocumentChoice'): document = Document.objects.get(id=checkbox) token = self.gen_token(email) now = timezone.now() expiration = now + settings.DOWNLOAD_VALIDITY β¦ -
django 2.1 receive delete request
i working on convert golang application in django and i have small problem, i need to receive DELETE request in django on specific path, this is the request : [25/Oct/2018 16:08:31] "DELETE /invitations/3 HTTP/1.1" 404 4815 this is urls.py re_path(r'^invitations/?$', invitation_views.invitationView.as_view(), name='api_invitation'), this is my invitationView class class invitationView(APIView): authentication_classes = (BearerTokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) parser_classes = (JSONParser, FormParser) #........ def delete(self, request, invitation_id=None, format=None): print("Hello, i'm %s!" % request.method) My problem is, way return 404 and not execute my class ? anothers requests from this class is still working, only delete not working. where i wrong ? -
render jsonschema as a form with django-jsonschema-form or django-schemulator
Pieces of JSON Schema are easily used with frontend JavaScript libraries like Angular, React and Alpaca to create an html form with validation. This should also work with a Python solution django-jsonschema-form or django-schemulator but I am new to Django and having a lot of trouble working it out.. Here is a screenshot from the video from AlpacaJS which communicates easily what this is supposed to achieve: I have done some testing with the two libraries above, and the former seems much better maintained and less buggy, the only one of the two in PyPI. My directory tree created by Django 1.11.4 looks like this: . βββ db.sqlite3 βββ jschemaforms β βββ admin.py β βββ apps.py β βββ forms.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ manage.py βββ myproject β βββ __init__.py β βββ settings.py β βββ templates β β βββ base.html β β βββ includes β βββ urls.py β βββ wsgi.py βββ README.md The docs for django-jsonschema-form specify a class: # Overriding widgets for all instances of JSONField on PageAdmin form class PageAdmin(admin.ModelAdmin): formfield_overrides = { JSONField: {'widget': JSONSchemaWidget(schema)} } Whereabouts in the directory tree is β¦