Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retriev the specific filed name from a list of data?
"education": [ { "school": { "id": "133332226690099", "name": "Govt. High School" }, "type": "High School", "id": "184985051845318" } ], using mongo db and json. i need retriv the data from a large list -
How to call external python script in django from a dropdown button on click event in the html
I need to run the jenkins job from frontend through python. So have made a header html which have dropdown button.From many posts i came to know that I can do that through AJAX.can someone please tell me how to do that with example snippets of view.py and how to redirect it to HTML when firing the on click event. I am very new to Django,so please bare if I am doing wrong. home.html <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <h4>Application B <span class="badge badge-secondary"></span></h4> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <h3>ACTIONS ALLOWED</h3><br> <div> <div class="dropdown"> <button class="btn btn-success btn-md" type="button" onclick="" data-toggle="dropdown">List of scripts available <span class="caret"></span></button> <ul class="dropdown-menu"> <li><a href="#">Healthcheck</a></li> <li><a href="#">Regresseion Testing</a></li> <li><a href="#">Functional Testin</a></li> <li><a href="#">Unit Testing</a></li> <li class="divider"></li> </ul> <button class="btn btn-warning btn-md">Cick to see the results</button><br> </div> </div> </div> </div> <script> $(document).ready(function(){ $('.btn-success').tooltip({title: "Execute", animation: true}); $('.btn-warning').tooltip({title: "Results!@", animation: false}); }); </script> </div> from django.shortcuts import render,redirect from django.http import HttpResponse,HttpResponseRedirect import datetime from jenkin_test import jobrun from django.core.urlresolvers import reverse def index(request): today=datetime.datetime.now().date() print jobrun() return render(request,'webapp/home.html',{"today":today}) urls.py from … -
Accessing database Model from HTML Template in DJango
In the below code Instead of {{ i.user }} I want to access a value from another table with {{ i.user }} as matching value. How to done it within HTML {% for i in obj reversed %} <div class="container"> <blockquote> <header> {{ i.topic }} {{ i.user }} </header> <p> {{ i.desc }} </p> <footer> {{ i.time }} </footer> </blockquote> {% endfor %} </div> Here are My Models from django.db import models class Accounts(models.Model): name=models.CharField(max_length=30) phone=models.CharField(max_length=20,unique=True) mail=models.EmailField() password=models.CharField(max_length=20) def __str__(self): return self.name class BlogPost(models.Model): user=models.CharField(max_length=30) topic=models.CharField(max_length=100) desc=models.CharField(max_length=1000) likes=models.IntegerField(null=True,default=0) time=models.DateTimeField(null=True) def __str__(self): return self.user And I want to get value from Accounts using Blogspot.user i.e {{ i.user }} in template Thanks in Advance... -
Using existing table for AUTH_USER_MODEL is it possible for a Django model field name to refer to database field name that is different
As the title suggests, I am playing with using an existing table for the AUTH_USER_MODEL using AbstractUser. Have to --fake the migration. Any additional columns I have to add to the DB manually and then to the model as some errors come up. Not ideal. Anyway, when I got to ./manage.py createsuperuser I get errors related to fields not existing that it requires: is_superuser, is_staff, etc. The thing is there are fields in the table for this already, just have a slightly different name. I could just change the name. But it got me wondering if there is something built in to Django to cast an ORM field name to a table field name. Something like: class Meta: db_table = 'Users' Where Django assumes the name, unless it is otherwise specified. My quick glimpse through the documentation didn't immediately yield anything. https://docs.djangoproject.com/en/1.11/ref/models/options/ from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. # Extend the User model class User(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=255, blank=False, null=False, unique=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) cono = models.IntegerField(blank=False, null=False) … -
Update bokeh graph that is rendered through Django via bokeh widgets
Currently, I have created a plot in Django using data from the database lets say name of the plot is p1. It is being rendered to a html file lets say abc.html Now I have added a widget to the plot and now it is being rendered as script , (div1 , div2) = components((p1 , options)) 'options' is the name of widget. Now the problem is how can I access the change value of the widget and update the plot accordingly from my view.py of Django? -
I wanna set type's number to id of select tag
I wanna set type's number to id of select tag. My ideal html in browser is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> <option value="0">---</option> <option value="1">a</option> <option value="2">b</option> </select> <select name="type" id="type1"> <option value="1">a1</option> <option value="2">a2</option> </select> <select name="type" id="type2"> <option value="5">b1</option> <option value="6">b2</option> </select> Now actual html in browse is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> <option>---</option> <option>a</option> <option>b</option> </select> <select name="type" id="type"> <option value="0">---</option> <option value="1">a1</option> <option value="2">a2</option> </select> <select name="type" id="type"> <option value="5">---</option> <option value="6">b1</option> <option value="7">b2</option> </select> id="type" of does not have each number but I do not know how to add these number by using Django's template. I wrote in index.html <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> What should I write it?How can I fix this? -
getting multi-tiered JS object into Python via Django
I am building a Django app. I need to build a JS object that is pretty simple, looks like this: data = {0: {t1: v("#t1"), p1: v("#p1")}, 1: {t2: v("#t2"), p2: v("#p2")}, 2: {t3: v("#t3"), p3: v("#p3")}, 3: {t4: v("#t4"), p4: v("#p4")}, 4: {t5: v("#t5"), p5: v("#p5")}, 5: {t6: v("#t6"), p6: v("#p6")}, 6: {t7: v("#t6"), p7: v("#p6")}, 7: {t8: v("#t8"), p8: v("#p8")}, numTickers: 8 }; FYI, v() is just a function that would be a macro in other languages...all it does is reduce typing to get values from tags. It works, so that is not the issue: on the console, I have the right JS object with proper key/value pairs nested right. Before AJAX I do a: var xmitData = JSON.stringify(data); Since that gets me closest. My AJAX call looks (right now) like this: $.ajax({ type : 'POST', headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: xmitData, url: 'ajax/data', dataType : 'json', success : function(data) { However, what I get in Python after Django handles this is a querydict that looks munged: <QueryDict: {'{"0":{"t1":"1","p1":"100"},"1":{"t2":"","p2":""},"2":{"t3":"","p3":""},"3":{"t4":"","p4":""},"4":{"t5":"","p5":""},"5":{"t6":"","p6":""},"6":{"t7":"","p7":""},"7":{"t8":"","p8":""},"numTickers":8}': ['']}> To me, this says that JS/JQuery used ALL of the multi-level key/value pairs as a big key, with the value [''] (note the single quotes). I have … -
Django CSS not working on live site
This site is live and hosted with Digital Ocean. I finally got it to work properly, however the css won't work for the site? Here's what I have setup, there are no errors, just the css won't work. I have this in my settings.py: STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATIC_DIR = os.path.join(BASE_DIR,'static') STATICFILES_DIRS = [ STATIC_DIR, ] Here are my project urls.py: from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from blog import views from users import views from feed import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomeView.as_view(),name='index'), url(r'^user/',include('users.urls',namespace='users')), url(r'^feed/',include('feed.urls',namespace='feed')), url(r'^blog/',include('blog.urls',namespace='blog')), url(r'^accounts/', include('allauth.urls')), ] File structure: - django_project - /allauth/ - /blog/ - /django_project/ - /feed/ - manage.py - /media/ - req.txt - /static/ - /css/ - /templates/ - /users/ - gunicorn.socket I have run python manage.py collectstatic -
Login and Logout view not working in django auth system
I am using the Django auth system for my app. I have made a CustomUser table using AbstractUser functionality to add some more fields. //models.py from django.contrib.auth.models import AbstractUser from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) state= models.CharField(max_length=20) class UserSession(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL) session=models.ForeignKey(Session) //views.py from .models import UserSession from django.contrib.auth.signals import user_logged_in def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/Student_home.html') # Redirect to a success page. else: return HttpResponse("disabled account") # Return a 'disabled account' error message else: return HttpResponse("invalid login")# Return an 'invalid login' error message. def logout(request): logout(request) return HttpResponseRedirect('/Student_home.html')# Redirect to a success page. def user_logged_in_handler(sender,request,user, **kwargs): UserSession.objects.get_or_create( user= user, session_id= request.session.session_key ) user_logged_in.connect(user_logged_in_handler, sender=CustomUser) def delete_user_sessions(CustomUser): user_sessions=UserSession.objects.filter(user=CustomUser) for user_session in user_sessions: user_session.session.delete() //forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) password = forms.CharField(label="Password", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'password'})) //project/urls.py(the outer one) from django.contrib.auth import views from swaracharya.forms import LoginForm url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/login'}), //login.html <div class="container"> <section id="content"> <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} … -
Python-Django project ideas
I learned python and Django , watching videos and reading some books. I also developed small applications on Django, like login page application. I want to implement any project on Django, which i can put on my resume. So that it will be helpful for me to find internship. Can somebody please help me out with any good project idea. TIA. -
Getting back a nonexistant url in test
So I have a django web app called notes where I have a viewset. The viewset is composed of CRUD commands. When I created a test to the api it keeps redirecting to a nonexistent url instead of the Json String. Here is my code: For tests.py: def test_list(self): e = Employee.objects.get(first_name="Dylan") organ = Organization.objects.get(name='test') cl = APIClient() # cl = APIClient() c = Customer.objects.get(first_name="John") cl.credentials(HTTP_AUTHORIZATION='Token ' + organ.token.key) response = cl.post('/api/notes/list', {'customer_id': c.uuid}, follow=True) #cl.login(username = "Dylan", password="Snyder") pprint("list: %s" % response.data) for api.py: def list(self, request): c = Customer.objects.get(pk=request.POST['customer_id']) n = Note.objects.get(customer=c, retired=False) notes = NoteListSerializer(n) return HttpResponse(notes) The results I get: .'list: {\'detail\': \'Method "GET" not allowed.\'}' in the command prompt I use. I never made a directory or have anything that contains /details/ in it -
Bootstrap is not hit to HTML
Bootstrap is not hit to HTML. I use Flat UI's Bootstrap. I wrote in index.html like {% load staticfiles %} <html lang="ja"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static './bootflat.github.io/bootflat/css/bootflat.min.css' %}"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <style> body { padding-top: 70px; } .my-form { width: 640px; margin: 0 auto; } @media screen and (max-width: 768px) { .my-form { width: 100%; } } .errorlist li { list-style-type: none; } .errorlist { color: red; margin-left: 0; padding-left: 0; } </style> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <p class="navbar-text">Hello</p> {% if user.is_authenticated %} <p class="navbar-text">{{ user.get_username }}</p> {% endif %} </div> </nav> <div class="container"> {% block content %} {% endblock %} </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> I designate folder path which has Flat UI like <link rel="stylesheet" href="{% static './bootflat.github.io/bootflat/css/bootflat.min.css' %}"> but the design is not changed.I accessed http://localhost:8000/static/bootflat.github.io/bootflat/css/bootflat.min.css,but Page not found (404) Request Method: GET Request URL error happens.So I think path is wrong. Directory structure is index.html is in accounts.accounts folder structure is What is wrong in my code?How should I fix this? -
OSX/Apache ModuleNotFoundError: No module named 'encodings'
I have a local Django application that I've been developing for a while. Today, after about a month off from working on it I went back to it, but it wouldn't load. Checking the apache error log, I see the following over and over: Current thread 0x00007fffc0be23c0 (most recent call first): [Tue Sep 26 19:18:09.154141 2017] [core:notice] [pid 1590] AH00052: child pid 1651 exit signal Abort trap (6) Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' The last time I was working on the project, I made some changes to my project code, but didn't touch and of my apache or mod_wsgi configuration. My PYTHONPATH is not set (nor was it set a month ago when everything was working. Here's my mod_wsgi configs (again haven't changed): WSGIDaemonProcess secureDash python-path=/Users/user/projects/secureDash_project python-home=/Users/user/.venvs/securedash_py3.6 WSGIProcessGroup secureDash WSGIScriptAlias / /Users/user/projects/secureDash_project/config/wsgi.py I've spent a lot of time googling this issue, but none of the common fixes seem to apply. Looking for some guidance on where else to look. -
why does django not combine makemigrations and migrate commands?
I can think of three reasons why: providing users with the flexibility on "when" to commit model changes debugging modularity perhaps resource consumption in larger databases However, it does seem that migrate always follows shortly after migration (tutorials/youtube videos). so is there a philosophy behind this that I'm missing? -
Failure during running rc.exe for Twisted on Windows 10
When I run pip install channels or pip install twisted Twisted fails with Failed building wheel for twisted Twisted is a required dependency for Django Channels. Here is the error: LINK : fatal error LNK1327: failure during running rc.exe error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1327 I tried various installs of Visual Studio and Build Tools, but could not make any progress. How do I get twisted to build on Windows 10? -
operational error with Digital ocean and django
Getting this error after using DO's one-click install for Django and uploading all my stuff. I set up my settings and urls files. Not really sure what the issue is, I've never seen it before. The error: OperationalError at /accounts/login/ SSL error: unknown protocol expected authentication request from server, but received S Traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapper return bound_func(*args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in dispatch return super(LoginView, self).dispatch(request, *args, **kwargs) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in dispatch **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in get request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in get return self.render_to_response(self.get_context_data()) ... ▶ Local vars /home/django/django_project/allauth/account/views.py in get_context_data site = get_current_site(self.request) … -
django apache ImportError: No module named
So this is driving me crazy I have python3 and modwsgi and apache and a virtual host, that work great, as I have several other wsgi scripts that work fine on the server. I also have a django app that works great when I run the dev server. I have checked that "ldd mod_wsgi.so" is linked correctly against python3.5 Whenever I try to access my site, I get an error and the apache log states: ImportError: No module named 'protectionprofiles' protection profiles is mysite name the following is my virtual host config <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName <my ip> WSGIScriptAlias /certs /var/www/scripts/CavsCertSearch/CavsCertSearch/certstrip.wsgi WSGIScriptAlias /testcerts /var/www/scripts/CavsCertSearchTest/CavsCertSearch/certstriptest.wsgi WSGIScriptAlias /protectionprofiles /var/www/protectionprofiles/protectionprofiles/wsgi.py <Directory /var/www/protectionprofiles/protectionprofiles> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> my site app is the protection profiles alias. I have no idea what the issue is I have tried following dozens of different apache tutorials and none of them seem to work. Any help is greatly appreciated. -
Django form field validation and auth password validation
I'm using Django 1.10.6 and working on a registration form. On a forms.py I want to use the min_length argument for the password form field to help prevent unnecessary server requests, because Django adds that attribute to the CSS and most browsers will check that before allowing a form to be submitted. However, Django doesn't seem to like when I use form field validation along with AUTH_PASSWORD_VALIDATORS in certain cases. When I open up inspector on the registration page and delete the CSS for the min_length attribute of the password input (thus preventing being prompted by my browser to enter more characters) and submit the request with less than 8 characters, the form field validation fails and Django deletes/empties (sorry, not sure of the correct term) the cleaned data so the password is None, which then causes the rest of the AUTH_PASSWORD_VALIDATORS to throw errors. This is the error which results object of type 'NoneType' has no len() Here's my registration class on forms.py class RegisterForm(forms.Form): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username'})) email = forms.CharField(label="Email", max_length=254, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'email'})) #when I remove the min_length here it works, however I would like to have the benefit of the … -
Django | update requirements.txt automatically afrer installing new package
I am new to Django. Every time I install new library using pip, I have to run pip freeze -l > requirements.txt and sometimes I forget this ( and error happens at my production environment). What's the best way to run this command automatically when I install new packages...? I am using: Django==1.11.5 Python 3.6.1 -
Django Template: key, value not possible in for loop
Error I get: Need 2 values to unpack in for loop; got 1. Here is my view: class Index(View): def get(self, request, slug): test = { 1: { 'id': 1, 'slug': 'test-slug-1', 'name': 'Test Name 1' }, 2: { 'id': 2, 'slug': 'test-slug-2', 'name': 'Test Name 2' } } context = { 'test': test } return render(request, 'wiki/category/index.html', context) Here is my template: {% block content %} <div> {{ test }} <ul> {% for key, value in test %} <li> <a href="#">{{ key }}: {{ value }}</a> </li> {% endfor %} </ul> </div> {% endblock %} I also tried the template like: {% block content %} <div> {{ test }} <ul> {% for value in test %} <li> <a href="#">{{ value }}: {{ value.name }}</a> </li> {% endfor %} </ul> </div> {% endblock %} No error then, but {{ value }} shows key (what is fine), but {{ value.name }} shows nothing. Whilte {{ test }} shows my dict. -
Social authentification django
I am building a website using django, and I did a social auto using 'allauth', but the thing is, I can only login from my own facebook account where I have added the app in developers.facebook.com, well I want other users , to be able to login with their own facebook accounts. Is there's another way than 'allauth', or should I make changes to it ? I am a beginner in django. -
How to select results from django model group by an attribute
I need some help with a problem that i can't figure out with Django (unless by doing crappy nested for). I have these three models : class Article(models.Model): label = models.CharField(max_length=100) unity = models.ForeignKey('Unity') category = models.ForeignKey('Category') user = models.ForeignKey(User) class Store(models.Model): label = models.CharField(max_length=100) address = models.TextField() products = models.ManyToManyField(Article, through='Offer') user = models.ForeignKey(User) class Offer(models.Model): quantity = models.FloatField() price = models.FloatField() infos = models.TextField(blank=True) article = models.ForeignKey('Article') store = models.ForeignKey('Store') user = models.ForeignKey(User) I'd like to print a table in my template that would looks like : Article | Quantity | Infos | Store_1 | Store_2 | Store_n ------- | -------- | ----- | ------- | ------- | ------- Ham | 4 | Bla | 4.2 $ | 5.0 $ | Ham | 6 | Bla | 6.0 $ | 7.5 $ | Instead, i only managed to have print this : Article | Quantity | Infos | Store_1 | Store_2 | Store_n ------- | -------- | ----- | ------- | ------- | ------- Ham | 4 | Bla | 4.2 $ | | Ham | 6 | Bla | 6.0 $ | | Ham | 4 | Bla | | 5.0 $ | Ham | 6 | … -
How to deploy a Django website that developed on Pycharm IDE (windows 10) to AWS EC2 or Elastic Bean?
I recently build a Django website in local with Pycharm IDE. I am using window 10. The website is almost done. Now I need to research how to deploy it on the AWS EC2 or Elastic Bean. The reason of choosing AWS is I want to learn how to use AWS. Any clues, tips or document will be appreciated. -
django-graphene mutation runs multiple queries
I'm using these versions. django==1.11.5 graphene-django==1.2.1 Amazon Redshift I have a simple Django model that looks like this. Base class BaseModel(models.Model): created_dt = models.DateTimeField(auto_now_add=True) created_user = models.CharField(max_length=25, default='myuser') updated_dt = models.DateTimeField(auto_now=True) updated_user = models.CharField(max_length=25, default='myuser') class Meta: abstract = True Model class MappingsMaster(BaseModel): """Master mappings model.""" master_id = models.CharField( max_length=36, help_text='''The UUID of the record.''', primary_key=True, default=uuid.uuid4) account_nm = models.CharField( max_length=255, null=True, blank=True, help_text='''The account's name.''') class Meta: managed = False db_table = 'mappings_dev' app_label = 'mappings' GraphQL model class MappingsGraphQL(ObjectType): master_id = String() account_nm = String() My schema looks like this. I've taken most of this from the Graphene tutorial. class MappingsNode(DjangoObjectType): """ Search account. accounts (or groups) of a search advertisement source system. """ class Meta: model = MappingsMaster interfaces = (relay.Node,) class CreateMapping(ClientIDMutation): class Input: account_nm = String() ok = Boolean() mapping = Field(MappingsNode) @classmethod def mutate_and_get_payload(cls, args, instance, info): ok = True mapping = MappingsMaster(account_nm=args.get('account_nm')) mapping.save() return CreateMapping(mapping=mapping, ok=ok) class Mutations(AbstractType): """Mutations for the mappings class.""" create_mapping = CreateMapping.Field() class Query(AbstractType): """The account query class for GraphQL.""" mapping = Field(MappingsGraphQL) Query mutation createMapping { createMapping(input: {accountNm: "testing account derp"}) { mapping { masterId accountNm } ok } __debug { sql { rawSql } } } Output … -
How do you add a Django form to a wagtail block
I want to add a form to a wagtail block. The form is a simple drop down selection with a submit button. class ExampleForm(forms.Form): example = forms.ModelChoiceField(queryset=Example.objects.all()) Then the wagtail block is a simple table that is generated with get_context() # this is basically the view rendering def get_context(self, request, **kwargs): context = super().get_context(request, **kwargs) # do some queries and populate tables in template. context['example_data'] = SomeObject.objects.all() # here is where I want to add the form. this_form = SomeForm() context['this_form'] = this_form return context But how do you habdle form submissions and everything? It seems that wagtail takes away the idea of a view so I don't know if its possible to do this. Any help would be greatly appreciated.