Show multiselectfield value in Bootstrap 4 multiselect dropdown in Django template - python

I am following this answer for the multi-selecting dropdown. I am using django-multiselectfield to collect data in the DB model. I want to show value in bootstrap multi-selecting dropdown but getting the below result
I am seeking this result
These are my code snippet
model.py
from django.db import models
from multiselectfield import MultiSelectField
class Country(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Person(models.Model):
obj=Country.objects.all()
TEAM=tuple((ob,ob) for ob in obj)
name = models.CharField(max_length=124)
southasia=MultiSelectField(max_length=200, choices=TEAM)
def __str__(self):
return self.name
views.py
from django.http import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from .forms import PersonCreationForm
from .models import Person
def person_create_view(request):
form = PersonCreationForm()
if request.method == 'POST':
form = PersonCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('person_add')
return render(request, 'miracle/index.html', {'form': form})
forms.py
from django import forms
from .models import Person
class PersonCreationForm(forms.ModelForm):
class Meta:
model = Person
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
template
{% load crispy_forms_tags %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<title>Dependent Dropdown in Django</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
</head>
<body>
<h2>Person Form</h2>
<form method="post">
{% csrf_token %}
{{ form.name|as_crispy_field }}
<select class="selectpicker" multiple data-live-search="true">
{{ form.southasia|as_crispy_field }}
</select>
<input type="submit" value="Submit">
</form>
<script>
$('select').selectpicker();
</script>
</body>
</html>
How can do show all values in dropdown multiselect instead of normal checkbox select?

django multiselect will give you check box view. If you want drop-down multiple list one of the work around is you can create another model for the choices and use manytomany relation . Django rendering should automatically detect it as droplist view and gives you opttion to select multiple choices.
Like this.
Class model1(model.models)
Choices = models.charfield(choice=choice)
Class person(models.model)
Choice = manytomany (model1).

Related

not able to upload and display django form

1.views.py
from django.shortcuts import render
from . models import User
from .forms import Userform
def Home(request):
if request.method == "POST":
form = Userform(request.POST or None,request.FILES or None)
if form.is_valid():
form.save()
else:
form = Userform()
return render(request,"home.html",{"form":form})
def read(request):
read = User.objects.all()
return render(request,"read.html",{"read":read})
2.models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=12)
rollno = models.IntegerField()
# files = models.FileField()
3.form.py
from django import forms
from .models import User
class Userform(forms.ModelForm):
class Meta:
model = User
fields = ('name','rollno')
urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("",views.Home,name="Home"),
path("read/",views.read, name="read"),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4.home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="read/" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{%block containt%}
{%for i in read%}
{{i.name}}
{{i.rollno}}
{%endfor%}
{%endblock%}
</body>
</html>
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
Problem is in the action of your form, you have entered the wrong URL in the action
You have to put home URL instead of read/, because you are handling your form submission in your home function so replace your form action by this
<form method="POST" action="{% url 'Home' %}" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>

Review a form before submitting in django

I am building a registration form. I want the users to review their filled-up forms to confirm their submissions. But in my code the form is submitted twice (overwritten not duplicated). Once when they hit the submit button after filling their form and overwritten after hitting the submit button on the review page. As a result if they close the browser in the review page their page is still submitted, which I don't want to allow.
views.py
from django.shortcuts import render, redirect
from .models import *
from .forms import *
# Create your views here.
def index(request):
form = RegisterForm()
print('hi')
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
z = form.cleaned_data
if (Register.objects.filter(email=z['email']).exists()):
print('already exist')
return redirect('/')
else:
print('xx')
return redirect('preview', pk=z.get('id'))
context = {'form':form}
return render(request, 'event/index.html', context)
def preview(request, pk):
prev = Register.objects.get(id=pk)
if request.method == 'POST':
prev.save()
print('overwrite')
return redirect('/')
print('yy')
context = { 'prev':prev,'id':pk}
return render(request, 'event/preview.html', context)
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Registration</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
<div class="mobile-screen">
<div class="header">
</div>
<div class="logo"></div>
<form id="login-form" method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.email}}
<input class="btn btn-sm btn-primary" type="submit" value="Register" name="Register">
</form>
</div>
</body>
</html>
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Register(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(max_length=254,null=True)
def __str__(self):
return self.name

Django_tables2 with delete buttom

How is going? I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table.
Now I'm try to add a delete button in each row of my table but, beside I have tried a lot of solutions, I didn't find one that works correctly.
Below my code:
urls
from django.urls import path
from app import views
app_name = 'main'
urlpatterns = [
path('', views.homepage, name='homepage'),
path('delete_item/<int:pk>', views.delete_item, name="delete_item"),
]
forms
from django import forms
from .models import Income
class IncomeModelForm(forms.ModelForm):
class Meta:
model = Income
fields = "__all__"
tables
import django_tables2 as tables
from django_tables2.utils import A
from .models import Income
class PersonTable(tables.Table):
delete = tables.LinkColumn('main:delete_item', args=[A('delete-id')], attrs={'a': {'class': 'btn'}})
class Meta:
model = Income
template_name = "django_tables2/bootstrap.html"
views
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView
from .models import Income
from .tables import PersonTable
from .forms import IncomeModelForm
def homepage(request):
table = PersonTable(Income.objects.all())
if request.method == 'POST':
form = IncomeModelForm(request.POST)
if form.is_valid():
print("Il form รจ valido")
new_input = form.save()
else :
form = IncomeModelForm()
context= {"form": form,
"table":table }
return render(request, "app/base.html", context)
def delete_item(request, pk):
Income.objects.filter(id=pk).delete()
items = Income.objects.all()
context = {
'items': items
}
return render(request, 'app/base.html', context)
html
{% load static %}
{% load render_table from django_tables2 %}
<!doctype html>
<html lang="it">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello, world!</title>
</head>
<div class="container">
<form class="" action="" method="post">
{% csrf_token %}
{{form|crispy}}
<input type="submit" class="btn btn-danger" value="INVIA">
</form>
</div>
<br>
<br>
<div class="container">
{% render_table table %}
</form>
</div>
</body>
</html>
My table disply the column "Delete" but no buttoms, only a "-". Why? Where is my error?
Please add this
text='static text', argument like delete = tables.LinkColumn('main:delete_item',text='Delete', args=[A('delete-id')], attrs={'a': {'class': 'btn'}})
.
Hope it will work

How do you get a string from Django PostgreSQL ArrayField?

I'm trying to get a string out of an ArrayField in my database but it only prints by characters, not the full string. For example, the ArrayField is named words and in the database it shows as {word1, word2, word3} so in the HTML I put {{ object.words.0 }} and { is rendered on the screen.
How can I get it to render word1?
I have added django.contrib.postgres to INSTALLED_APPS.
This is what it looks like in my model:
from django.db import models
from django.contrib.postgres.fields import ArrayField
class WordArr(models.Model):
words = ArrayField(models.CharField(max_length=200, null=True))
I fixed the issue and it was with my database. The ArrayField in my model was previously a CharField that I changed. I thought the migrations were correct however the database was still reading it as a CharField, so the output was the first character of a string. I migrated to a new database and everything worked fine. My code is below for further reference:
models.py
from django.db import models
from django.contrib.postgres.fields import ArrayField
# Create your models here.
class Word(models.Model):
first = models.CharField(max_length=50)
last = models.CharField(max_length=50)
words = ArrayField(models.CharField(max_length=50, null=True))
def __str__(self):
return self.first
views.py
from django.shortcuts import render
from django.views.generic.detail import DetailView
from django.views.generic import CreateView
from .models import Word
# Create your views here.
class ArrayCreateView(CreateView):
model = Word
fields = ['first', 'last']
success_url = '/'
def form_valid(self, form):
w = form.save(commit=False)
random_words = ["word1", "word2", "word3"]
w.words = random_words
return super().form_valid(form)
class ArrayDetailView(DetailView):
model = Word
word_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Create Array</h1>
<div>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
word_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>{{ object.words.0 }}</h1>
</body>
</html>
settings.py
INSTALLED_APPS = [
...
'django.contrib.postgres',
'arr',
]
urls.py
from django.contrib import admin
from django.urls import path
from arr.views import ArrayCreateView, ArrayDetailView
urlpatterns = [
path('admin/', admin.site.urls),
path('create/new/', ArrayCreateView.as_view(), name='create'),
path('detail/<int:pk>/', ArrayDetailView.as_view(), name='detail')
]

Empty Template while drawing graphs using Django-graphos

I am new to Django. I want to draw a google graph using django graphos. I have written small code for that and i am getting empty template..any lead would be appritiated..
view.py
from graphos.renderers import gchart
from django.shortcuts import render
from django.shortcuts import render_to_response
from graphos.sources.model import ModelDataSource
from models import MyCityViews
def get_context_data(self):
queryset = MyCityViews.objects.all()
data_source = ModelDataSource(queryset,fields=['city', 'views'])
line_chart = gchart.LineChart(data_source)
context = {"chart": line_chart}
return render_to_response('gchart.html', {'chart': line_chart})
models.py
from django.db import models
# Create your models here.
class MyCityViews(models.Model):
city = models.CharField(max_length = 30, blank = True , null = True)
views = models.IntegerField()
class Meta:
ordering = ['city']
verbose_name = 'city'
verbose_name_plural = 'city'
def __unicode__(self):
return self.city
gchart.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Graphos</title>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "css/bootstrap.css" %}">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback({{line_chart.as_html}});
</script>
</head>
<body>
{{line_chart.as_html}}
<div id="container"></div>
</body>
</html>
Where i am doing wrong...
Did not pass view object to div block thats why i was not getting HTML view.
<body>
<div id="container">
{{line_chart.as_html}}
</div>
</body>

Categories

Resources