Good day,
I'm trying "create" a DatePicker for one of my Inputfields in Django but it's not working!
In my models.py:
class Customer(models.Model):
...
name = models.CharField()
date = models.DateField()
In my views.py:
def Page(request):
CustomerFormSet = modelformset_factory(Customer, fields='__all__')
formset = CustomerFormSet (queryset=Customer.objects.none())
...
context = {'formset': formset}
return render(request, 'app/base.html', context)
In my template:
{% extends 'app/base.html' %}
{% load widget_tweaks %}
<form actions="" method="POST">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form.id }}
...
{% render_field form.name class="form-control" %}
...
{% render_field form.date class="form-control" %}
...
Now my first Inputfield works fine! It returns a fitting Field in Bootstraps "Form-Group"-Layout. But my InputField for Dates remains a simple TextInput with no calendar apearing to choose from.
My Question is: am I doing something wrong or is it still impossible to obtain such a function in this way?
Thanks and a nice evening to all of you.
If you ara using ModelForm try:
from django import forms
class DateInput(forms.DateInput):
input_type = 'date'
class DataTreinoForm(forms.ModelForm):
class Meta:
model = models.YOURMODEL
fields = _all_
widgets = {
'dateField': DateInput
}
The default format is mm/dd/yyyy. I don't know how to change it in this way.
I just solved this too. Add type="date" to the render_field.
{% render_field form.date type="date" class="form-control" %}
You can add any input tag attributes here which is convenient because
Modify form appearance on the template instead of forms.py, which is conceptually consistent
When you save templates, it doesnt reload the app, so faster testing with html
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 am looking to create a dropdown in a template where the values of the dropdown come from a field (reference) within my Orders model in models.py. I understand creating a dropdown where the values are set statically, but since I am looking to populate with values stored in the DB, I'm unsure of where to start.
I've created the model and attempted playing around with views.py, forms.py and templates. I am able to get each of the order numbers to display but not in a dropdown and I am struggling with how to write my template.
models.py
from django.db import models
class Orders(models.Model):
reference = models.CharField(max_length=50, blank=False)
ultimate_consignee = models.CharField(max_length=500)
ship_to = models.CharField(max_length=500)
def _str_(self):
return self.reference
forms.py
from django import forms
from .models import *
def references():
list_of_references = []
querySet = Orders.objects.all()
for orders in querySet:
list_of_references.append(orders.reference)
return list_of_references
class DropDownMenuReferences(forms.Form):
reference = forms.ChoiceField(choices=[(x) for x in references()])
views.py
def reference_view(request):
if request.method == "POST":
form = references(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = references()
return render(request, 'proforma_select.html', {'form': form})
proforma_select.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label"> {{ field.label }}</label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button">Add Order</button>
</form>
</div>
{% endblock %}
All I get when I render the template is each of the reference #s listed out but NOT within a dropdown. This leads me to believe my problem is mainly with the template, but I'm unsure as I am new to using Django.
Are you using Materialize CSS? If yes, then Django forms renders dropdowns differently from how Materialize expects them. So you will want to override the form widget. You can do something like so:
forms.py:
class DropDownMenuReferences(forms.Form):
reference = forms.ChoiceField(choices=[(x) for x in references()],
widget=forms.Select(choices=[(x) for x in references()], attrs={'class':
'browser-default'}))
This overrides the parameters passed into html. You can also pass any name tags in the attrs too.
The issue:
https://github.com/Dogfalo/materialize/issues/4904
I have a trouble. I have form:
from django import forms
class CartAddProductForm(forms.Form):
quantity = forms.IntegerField(min_value=1, initial=1)
update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
How I can customize(css) this field in template?
I try do it by widget, but just broken form, lol.
Help me pls, I feel me retarded.
django-widget-tweaks lets u to customize your form in your template
Example :
{% for field in form %}
{% render_field field class="form-control" value="" %}
{% endfor %}
I would like to display something like this in my template:
Name: John
Age: 18
City: New York
Using, for example, this code:
views.py
def person_details(request,pk):
person = get_object_or_404(Person, id=pk)
return render(request, 'template.html', {'person': person, 'person_fields': person._meta.get_fields()})
template.html
{% for field in person_fields %}
<div class="col-4 form-group">
<p><strong>{{ field.verbose_name }}:</strong> {{ person[ field.name ] }}</p>
</div>
{% endfor %}
Is this possible in python? I ask because I have a model that have about 20 fields and hard coding the fields in template would be a little hard.
You can use Django's to-python queryset serializer.
Just put the following code in your view:
from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )
And then in the template:
{% for instance in data %}
{% for field, value in instance.fields.items %}
{{ field }}: {{ value }}
{% endfor %}
{% endfor %}
Its great advantage is the fact that it handles relation fields.
For the subset of fields try:
data = serializers.serialize('python', SomeModel.objects.all(), fields=('name','size'))
Django templates are deliberately restricted, such that writing business logic is hard (or close to impossible). One typically performs such logic in the model or view layer.
def person_details(request, pk):
person = get_object_or_404(Person, id=pk)
person_data = {
f.verbose_name: getattr(person, f.name, None)
for f in person._meta.get_fields()
}
return render(request, 'template.html', {'person': person, 'person_data': person_data })
and then render it with:
{% for ky, val in person_data.items %}
<div class="col-4 form-group">
<p><strong>{{ ky }}:</strong> {{ val }}</p>
</div>
{% endfor %}
It is however advisable not to do this serialization yourself, but to use other serialization methods like these listed in this answer.
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