How to add values to a queryset used for a choice field in a template? - django-forms

I have a queryset which lists all users in an admin group. I am using this queryset for a dropdown field in a django template. This works but only lists actual users. But I want to add an additional option of 'all' to the dropdown. How to best do this? I can't append the queryset.
forms.py
indexer_name = forms.ModelChoiceField(
queryset=User.objects.filter(groups__name='indexers'),
initial='all',
required=True
)
template form:
<form action="{% url 'indexer_epg_search'%}" method="post">
{% csrf_token %}
<div class="row g-2 my-3">
<div class="col-md">
<div class="form-floating">
{{ form_indexer.indexer_name|add_class:"form-select"|attr:"placeholder:by Indexer" }}
<label for="id_indexer_name">by Indexer</label>
</div>
</div>

Related

How to filter foreign keys in Django Model form?

I want to have a form with two dropdowns (ForeignKey) in which when the user select "Branch" in the first dropdown, the second one only shows the "Staff" in that branch and then after filling a textbox for description the form would be saved.
Here is my codes:
models.py
class BranchCodes(models.Model):
br_code = models.IntegerField(max_length=4)
br_name = models.CharField(max_length=50)
class Staff(models.Model):
staf_br = models.ForeignKey(BranchCodes, on_delete=models.CASCADE)
staf_name = models.CharField(max_length=200)
class Problems(models.Model):
branch_code = models.ForeignKey(BranchCodes, on_delete=models.CASCADE)
Staff = models.ForeignKey(Staff, on_delete=models.CASCADE)
problem = models.CharField(max_length=200)
views.py
class Problems_form_View(FormView):
template_name = 'problem_page.html'
form_class = ProblemsModelForm
success_url = '/Problems'
def form_valid(self, form):
form.save()
return su
per().form_valid(form)
forms.py
class ProblemsModelForm(forms.ModelForm):
class Meta:
model = Problems
fields = '__all__'
page.html
<form id="main-contact-form" class="contact-form row" action="{% url'problem-form' %}" name="contact-form" method="post"
enctype="multipart/form-data" \>
{% csrf_token %}
<div class="form-group col-md-6">
{{ form.branch_code.label_tag }}
{{ form.branch_code }}
</div>
<div class="form-group col-md-6">
{{ form.staff.label_tag }}
{{ form.staff}}
</div>
<div class="form-group col-md-12">
{{ form.problem.label_tag }}
{{ form.problem }}
</div>
<div>
<button type="submit" " class=" btn btn-primary pull-left">send</button>
</div>
</form>
I searched on the net and I found that some used ajax for doing so and others in the forms.py with queryset tried to handle it. I'm totally confused and since I'm new in coding, I couldn't resolve the problem.

How to change css_class for all <div> rows in Crispy form

I am using Crispy forms to render my Django form. It works smoothly but I struggle with updating the css_class for my rows. Any suggestions how to solve this? The form is retrieved from the forms.models, so ideally I do not have to update my layout for every row individually.
The documentation https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#overriding-layout-objects-templates did not provide an answer to my question (or I did not understand it)
Current output in html
<div id="div_id_voornaam" class="form-group row"> </div>
Ideally: change css class for every row:
<div id="div_id_voornaam" class="row mb-3"> </div>
Forms setting
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
Template setting
<div class="card-body">
<form method="post">
{% load crispy_forms_tags %}
{% csrf_token %}
{% crispy form %}
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</form>
You need to use wrapper_css atribute. Like this:
...self.helper.layout = Layout(Field('voornaam', wrapper_class="row mb-3"))
You can check crispy documentation here: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html

i cant add image to my new blog post in django

kindly help me, i am using class based views now am about to create new post using Createview i added all the fields including an image which stands for the thumbnail so if i go to http://127.0.0.1:8000/pages/blog/new/ i get a form and if i fill in the fields and submit i get return back to the form saying the image fields is required meanwhile i already inserted an image , this is the error in picture
and this is my code below
views.py
class BlogCreateView(LoginRequiredMixin, CreateView):
model = Blog
fields = ['title', 'categories', 'overview', 'thumbnail', 'summary']
blog_form.html
<div class="content-section text-center">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group ">
<legend class="border-bottom mb-4 h2">Blog Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
You need to add "enctype="multipart/form-data" to your form, so:
<form method="post" enctype="multipart/form-data">
See detailed explanation is this elaborate answer:
What does enctype='multipart/form-data' mean?

Django form ajax submit concurrently

I have some field created by Django form and there are some other data I want to post to other form using jQuery(Ajax).
Is there any way to post them to different tables with two different ways at the same time?
form.py
class MyForm(forms.ModelForm):
class Meta:
model = models.Planning
fields = ['title','description','open','owner','upload_time']
template
<form id="myform" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.management_form }}
<div id="select_country">
<p style="display: inline;">country</p>
<select id="city">
<option selected disabled hidden>please choose</option>
{% for x in areas %}
<option value="{{x.area_country}}">{{x.area_country}}</option>
{% endfor %}
</select>
<select id="areas" name="my_areas"></select>
<br>
<div class="my_detail">
</div>
<br>
</div>
<div id="content_loi" class="col-lg-4">
<div class="col-lg-12" id="list"></div>
<div class="col-lg-12"">
<label>title:{{form.title}}</label>
<p><b>description:</b>{{form.description}}</p>
<button type="submit" class="btn btn-default" style="margin:0 auto;">submit</button>
</div>
</div>
</form>
I want to store the chosen areas and foreign key to another table with ajax
view
def make_list(request):
template = get_template('index.html')
areas = models.Area.objects.values('area_country').distinct()
max_my_id = models.RoutePlanning.objects.all().aggregate(Max('my_id'))
my_id = int(max_my_id['my_id__max']) + 1
#city = request.POST.get('my_areas')
if request.method == 'POST':
form = forms.MyForm(request.POST,initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
if form.is_valid():
form.save()
return HttpResponseRedirect('/make_player')
else:
loi_form = forms.MyForm(initial={'owner':username,'route_id':my_id,'route_upload_time':datetime.now()})
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)

Issues with uploading images to a carousel [duplicate]

This question already has an answer here:
Django template/view issues with carousel
(1 answer)
Closed 7 years ago.
OK, so here's the deal:
This is currently what I'm working on:
See the two arrows at the top? That's where a carousel of pictures should be. However, there are no pictures in this carousel. That is, until I click the 'Upload' Button.
So, my goal is to make the pictures appear on the first page before I even click the 'upload' button.
How can I fix this problem? I'm kind of a noob at Django, and writing this code is like pulling teeth.
My code:
Index.html
{% extends 'webportal/defaults.html' %}
{% block body %}
{% include 'webportal/carousel.html' %}
<br/>
<div class="container">
<div class="row">
<div class="col-md-12">
<p> So far we have been able to establish what the user tables will be have created or are in process of
creating
the ability to create, update, destroy users.</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> For now this ability is limited to the main user table, however the models will be easily extended
to other
tables as they are needed</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> Also not a lot of thought has gone into styling yet, we know that the page is suppose to resemble
the parent
organizations page. Right now we have been more focused on getting each individual component
working. Later we
will merge them into a whole. </p>
</div>
</div>
</div>
{% include 'webportal/info_row.html' with one=one two=two three=three %}
{% endblock %}
Carousel.html:
{% load staticfiles %}
{% load filename %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
{% for document in documents %}
<div class="item {% if forloop.first %} active {% endif %}">
<div class="row">
<div class="col">
<li>{{document.docfile.name}}</li>
<img src = "{{STATIC_URL}}img/{{document|filename}}" >
<p align="center"><form style="text-align:center" action="{% url 'webportal:delete' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.Document.label_tag }} {{ form.Document.help_text }}</p>
<p>
{{ form.Document.errors }}
{{ form.Document.docfile }}
</p>
<p><input type="submit" value="Delete" /></p>
</form></p>
</div>
</div>
</div>
{% endfor %}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- /.carousel -->
</div>
</div>
<form action="{% url 'webportal:carousel' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</div>
Views.py:
from django.shortcuts import render
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login
from webportal.views.authentication import LoginForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from webportal.forms.forms import DocumentForm
from webportal.models import Document, DeleteForm
is_server = True
def delete(request, my_id):
Deleted=get_object_or_404(Document, docfile=my_id)
if request.method=='POST':
form=DeleteForm(request.POST, instance=Deleted)
if form.is_valid():
Deleted.delete()
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form=DeleteForm(instance=Deleted)
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
# Redirect to the document list after POST
def carousel(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
#documents=DocumentForm().
# Render list page with the documents and the form
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
Models.py:
class Document(models.Model):
docfile = models.ImageField(upload_to='webportal/static/img/')
class DeleteForm(ModelForm):
class Meta:
model=Document
fields=[]
Forms.py:
class DocumentForm(forms.Form):
docfile = forms.ImageField(label='Select a file', help_text='max. 42 megabytes')
URls.py:
from django.conf.urls import patterns, url
from webportal.views import views, register, authentication, welcome, search, profile, event, csv_export, role_creation, \
edit_event, reports, accounts
urlpatterns = patterns('',
url(r'^reports', reports.report_page),
url(r'^search/criteria', search.get_criteria),
url(r'^search', search.search_page),
url(r'^register', register.SignUpView.as_view(), name="register"),
url(r'^login', authentication.login_view, name="login"),
url(r'^carousel', views.carousel, name="carousel"),
url(r'^delete', views.delete, name="delete"),
url(r'^profile', profile.ProfileView.as_view(), name="profile"),
url(r'^welcome', welcome.WelcomeView.as_view(), name="welcome"),
url(r'^event/creation', event.Creation.as_view(), name="event_creation"),
# url(r'^role_creation', role_creation.Creation.as_view(), name="role_creation"),
url(r'^csv_export', csv_export.CSVExport.as_view(), name="csv_export"),
url(r'^csv_import', reports.upload_file, name="csv_import"),
url(r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/alzheimers/'}),
url(r'^edit_event', edit_event.EditView.as_view(), name='edit_event'),
url(r'^parse_ajax', profile.parse_ajax),
url(r'^event/role_ajax', role_creation.ajax),
url(r'^event/all', event.view_all),
url(r'^event/information', event.ajax),
url(r'^accounts/personal', accounts.personal),
url(r'^accounts/create', accounts.create),
url(r'^accounts/edit', accounts.edit),
url(r'^accounts/remove', accounts.remove),
url(r'^$', views.bootstrap),
)
If there is a way to do this, does it involve ajax? I asked this again because of a lack of an adequate answer.
You should pass the documents context variable to the template in the view which handles the /alzheimers/ page.
UPDATE: The view you should change is the views.boostrap(). So rendering of the template will be something like this:
def bootstrap(request):
...
return render_to_response('webportal/bootstrap.html',
{'documents': Document.objects.all()},
context_instance=RequestContext(request)
)

Resources