I don't understand how widgets work.
I tried this minimum example :
in my forms.py
class PartialResetForm(forms.Form):
date = forms.DateField(
label="Starting date",
widget=AdminDateWidget()
)
in my admin/intermediary_reset_page.html
{% extends "admin/base_site.html" %}
<!--Loading necessary css and js -->
{{ form.media }}
{% block content %}
<form action="" method="post">{% csrf_token %}
<!-- The code of the form with all input fields will be automatically generated by Django -->
{{ form }}
<!-- Link the action name in hidden params -->
<input type="hidden" name="action" value="custom_action" />
<!-- Submit! Apply! -->
<input type="submit" name="apply" value="Submit" />
</form>
{% endblock %}
in my admin.py as the definition of an action
def custom_action(self, request, queryset):
form = PartialResetForm()
return render(request, "admin/intermediary_reset_page.html", {
"items": queryset, "form": form
})
For now I don't care about the queryset, it will be my next topic. With this simple example, I wanted to have a calendar in order to help pick a date, but only a TextInput appeared. I believe it is due to the fact that AdminDateWidget inheritates from TextInput.
My question is why isn't it appearing as a calendar ? I imported the media and declared my widget, I don't understand what else I'm supposed to do.
you should declare type
AdminDateWidget(attrs={'type': 'date'})
And it should be enough ;)
Related
Is there any way how to update booleanField in the list view? In list view I have listed all my orders and I need to mark which are done and which are not done. I know I can update it via UpdateView, but that is not user friendly because I have to leave the listview page.
models.py
class Order(models.Model):
...
order = models.CharField(max_length = 255)
completed = models.BooleanField(blank=True, default=False)
views.py
class OrderIndex(generic.ListView):
template_name = "mypage.html"
context_object_name = "orders"
def get_queryset(self):
return Order.objects.all().order_by("-id")
mypage.html
{% extends "base.html" %}
{% block content %}
{% for order in orders%}
User: {{ order.user}} | Completed: {{order.completed}} <input
type="checkbox">
{% endfor %}
<input type="submit">
{% endblock %}
I am quite new to the django framework and have no idea how to make it work.
like this should look you javascript
const updateField = (order_id) =>{
var form = new FormData();
form.append('order_id', order_id);
fetch('{% url "url_updateField" %}', {
method:'post',
body:form,
mode:'cors',
cache:'default',
credentials:'include',
}).then((response)=>{
console.log('field update as well')
})
})
just add a function to your button on envent onclick
{% extends "base.html" %}
{% block content %}
{% for order in orders%}
User: {{ order.user}} | Completed: {{order.completed}} <input
type="checkbox" onclick="updateField({{order.pk}})">
{% endfor %}
<input type="submit">
{% endblock %}
then in your view you should have the below view to process the request
def updateField(request):
print(request.body.get('order_id'))
#you should update you model field here
return JsonResponse({'ok':True}, status=200)
This will help you How to work with ajax request with django
Combine the UpdateView with the part of the listView's functionality by adding to the UpdateView the extra context of the entire list of objects:
class OrderUpdateView(generic.UpdateView):
model = Order
form_class = OrderForm
....
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['orders'] = Order.objects.all().order_by("-id")
return context
Consider a simple template where the entire list is displayed on top, and the bottom has a form allowing the user to update a particular item in the list.
This approach purposefully avoids using Ajax and javascript.
documentation
There is a way to do this without any special magic, just post to an update view from your listview with the entire form filled out correctly in hidden form fields nothing special needs to be done anywhere else.
<!-- todo_list.html -->
<form method="POST" action="update/{{object.id}}/">
{% csrf_token %}
<input type="hidden" name="completed" value="true" />
<input type="hidden" name="name" value="{{object.name}}" />
<input type="hidden" name="due_date" value="{{object.due_date|date:'Y-m-d'}}" />
<input type="hidden" name="details" value="{{object.details}}" />
<button type="submit" class="btn btn-primary">Not Done</button>
</form>
I would like to be able to use my external app data on django cms page.
I am able to use custom plugin data but not data from normal django app
I tried creating views to handle my data but how do I call this view from django cms pages?
here is exactly what I am asking for but his explanation is shallow and the link provided in the answer is no longer in use.
Here is my model:
class ExternalArticle(models.Model):
url = models.URLField()
source = models.CharField(
max_length=100,
help_text="Please supply the source of the article",
verbose_name="source of the article",
)
title = models.CharField(
max_length=250,
help_text="Please supply the title of the article",
verbose_name="title of the article",
)
class Meta:
ordering = ["-original_publication_date"]
def __str__(self):
return u"%s:%s" % (self.source[0:60], self.title[0:60])
My template has placeholders
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
<section class="section">
<div class="container">
<div class="row">
<!-- header-->
<div class="col-lg-12">
<div class="updates">
{% placeholder "header" %}
</div>
</div>
<!-- header end-->
</div> <!-- end row -->
but I don't mind displaying this data anywhere on the template if not possible inside a place holder
I have a custom page that I am using in Django cms.
I would like to display the above data is a section in the Django cms page
If this model was inheriting from CMSPlugin then that would be easy because I could use a custom plugin in my placeholder
I expect to display the data from my model in the template.
I was able to achieve this by doing the following:
#plugin_pool.register_plugin
class ArticlesPluginPublisher(CMSPluginBase):
model = ArticlesPluginModel
name = _("Articles")
render_template = "article_plugin/articles.html"
cache = False
def render(self, context, instance, placeholder):
context = super(ArticlesPluginPublisher, self).render(
context, instance, placeholder
)
context.update(
{
"articles": Article.objects.order_by(
"-original_publication_date"
)
}
)
return context
The plugin model(ArticlesPluginModel) is just for storing the configurations for the instance of the plugin. Not the actual articles.
Then the render will just add to the context the relevant articles from the external app(Article)
You must somehow connect the ExternalArticle with a page object. For example
by defining the ExternalArticle as a page extension
or with an AppHook
or - low-tech - with a PageField on the ExternalArticle model
{% load cms_tags %}
<h1>{{ instance.poll.question }}</h1>
<form action="{% url polls.views.vote poll.id %}" method="post"> {% csrf_token %}
{% for choice in instance.poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
I'm using Django and I just did a big form Using HTML5 and bootstrap. Can I still send the form via the post method to django if I'm not using it to generate the form? Should I definitely redo my form using Django?
NOTE: There may be a better way of doing this, if there is I'd really like to know, this is just how I have done it in the past.
You will still need a forms.py file in your app.
In forms.py:
from django import forms
class MyForm(forms.Form):
# FORM FIELDS HERE
Then put the form in the context dictionary for your view:
def myView(request):
if request.method == "POST":
# FORM PROCESSING HERE
else:
myform = MyForm() #create empty form
return render(request, "template.html", {"myform": myForm}
Now in your template you can add:
<form id="myForm" name="myFormName" method="post" action=".">
{% csrf_token %}
{% for field in myform %}
{{ field.as_hidden }}
{% endfor %}
</form>
This will add your django form to the page without displaying it. All of your form inputs are given the id id_fieldName where fieldName is the field name you defined in the forms.py file.
Now when the user clicks your "submit" button (which I am assuming is a bootstrap button given the rest of your form is). You can use Jquery to input the bootstrap field values into those of the hidden form.
Something like:
$("#mySubmitButton").click(function() {
$("#id_djangoFormField").val($("#myBootstrapFormField").val());
$("#myForm").submit();
}
);
This will submit the django form with the inputs from bootstrap. This can be processed in the view as normal using cleaned_data["fieldName"].
A bit late I post the solution I found for including a form in a modal in a class based detail view. Dunno if it's really orthodox but it works.
I don't use any Form Class or Model. (Django 3.9)
Within the template, I send a field value of my object in a hidden div. If this value is missing for a special action (because for the most of actions on the object, it's not required), a modal pops asking for updating the given field. This modal is triggered with JS that check the presence (or not) of the required value.
In the modal, I display a list of radio choices buttons in an ordinary form inviting the user to update the field. The form's action leads to a view that will update the given field.
modal.html
<form action="{% url 'update-sku-column' object.pk %}" method="post">
{% csrf_token %}
{% if csv_headers %}
<div class="m-3 ps-3">
{% for header in csv_headers %}
{% for csv_sample in csv_samples %}
{% if forloop.counter0 == forloop.parentloop.counter0 %}
<div class="form-check">
<input class="form-check-input" type="radio" name="chosen-field" value="{{ forloop.counter0 }}">
<label class="form-check-label" for="{{ forloop.counter0 }}">
<span class="ms-3">{{ header }} </span>: <span class="ms-1 text-secondary">{{ csv_sample }}</span>
</label>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
{% endif %}
<div class="modal-footer">
<button type="submit" class="btn btn-success">Enregistrer</button>
</div>
</form>
urls.py
[...]
path('flow/<int:pk>/update-sku-column',
set_sku_column, name='update-sku-column'),
[...]
views.py
#login_required
def set_sku_column(request, pk):
if request.method == 'POST':
column = request.POST['chosen-field']
flow = Flow.objects.get(pk=pk)
flow.fl_ref_index = column
flow.save()
return redirect('mappings-list', pk=pk)
[...]
Even if I can imagine it's not the best way, it works.
don't forget the {% csrf_token %}otherwise it won't
I have a form that in layman's terms, has a bunch of buttons (that act like checkboxes) with values. Users can select a handful of buttons.
The buttons push their values (via a JQuery function) into a hidden input which I'm using to gather the values.
I would like to make sure that the "values=" attribute of each hidden input isn't null or "" when the user presses the submit form.
Ex: Make sure that the input does NOT equal this:
<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden"> or
<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden" value="">
Here's the forms.py:
class getGames(forms.Form):
valuePlatform = forms.CharField(required=True, error_messages={'required': 'You need to tell us your platform(s)!'}, widget=forms.HiddenInput(attrs={'autocomplete': 'off'}))
Template:
<form method= "POST" autocomplete="off"> {% csrf_token %}
{{ form.non_field_errors }}
<div class="container">
{% if form.valuePlatform.errors %}
<ol>
{% for error in form.valuePlatform.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
</div>
{{ form.valuePlatform }}
</div>
</div>
</form>
Views.py:
from .forms import getGames
def find(request):
form = getGames()
context = {"form": form}
if form.is_valid():
print form.cleaned_data['valuePlatform']
Is this even possible, or would I have to pass the data to Django via a Ajax POST?
Changed views.py to this, after looking at # Alasdair's examples in the documentation:
from .forms import getGames
def find(request):
form = getGames(request.POST or None)
context = {"form": form}
if request.method == 'POST':
if form.is_valid():
print form.cleaned_data['valuePlatform']
So basically I want to make a simple form I can enter text and the after I hit submit, see the text.
Here is my forms.py:
class Search(forms.Form):
search = forms.CharField()
Here is my views.py:
def search(request):
context = RequestContext(request)
if request.method == 'POST':
search = Search(data=request.POST)
if search.is_valid():
ticker = search.save()
ticker.save()
success = True
else:
print search.errors
else:
search = Search()
return render_to_response('ui/search.html', {"search":search}, context)
Here is the html form that you use to type in (I'm using bootstrap for styling purposes):
<form class="navbar-form navbar-right" role="search" action="/search/" method="post" name="tick">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter stock symbol">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And finally, I want the text entered in the form to be displayed on "search.html" which looks like this currently:
{% extends 'ui/base.html' %}
{% block title %} search {% endblock %}
{% block body_block %}
<br>
<p>test</p>
{{ form.search.data }} <!--I'm pretty sure this is not correct -->
{% endblock %}
Anyone know how I can do this? Thanks.
Your form name is search.
To render the value with modern django, you need to call the value method of the field, therefore your template should look like the following:
{{ search.search.value }}
Your template is wrong, as you suspect.
It is looking for a context variable named "form", but you have given it a context dictionary with a key named "search".
Also, "data" is the argument that you use to build up your Search object (correctly), but when you want to extract the user's input from it, you should use the field names instead, and you need to call value() on them in order to get the bound value. So, to get the contents of the text field called search, you should use search.search.value.
Try changing the line
{{ form.search.data }}
to
{{ search.search.value }}