i use the
{{ form.Product_PId }}
to make this field
is there anyway to pass this value
{{ Product.PId }}
where the PId is a primary key from another database
and be like this
<input id="id_Product_ID" min="0" name="Product_ID" type="number" value="{{Product.PId}}" required="">
so that the end result would be like
<input id="id_Product_ID" min="0" name="Product_ID" type="number" value="1" required="">
**to sum up the question
is there a way to pass {{ Product.PId }} into {{ form.Product_PId }}
so that the {{ Product.PId }} value could turn into usable number taken from another database**
reference
forms.py
class PlaceOrder(forms.ModelForm):
class Meta:
model = Order
fields = ["Product_ID","HowMany","DateSubmit",]
HTML
{% for Product in Display_Product %}
<form method="post" action="" id="CartInput"> {% csrf_token %}
<div>
{{ form.Product_ID }}
{{ form.HowMany }}
{{ form.DateSubmit }}
</div>
<div>
<input name="Cart{{ Product.PId }}" type="submit" value="Add to Cart">
</div>
</form>
{% endfor %}
views.py
class Catalogue(generic.ListView, ModelFormMixin):
template_name = 'Shop/Catalogue.html'
model = models.Order
form_class = forms.PlaceOrder
def get(self, request, *args, **kwargs):
Display_Product = Product.objects.all()
now = datetime.datetime.now()
*** tried this one but failed, it just pass in the string {{Product.PId}} and not turn into number ***
form = PlaceOrder(initial= {'Product_ID': "{{Product.PId}}"})
context = {
'form': form,
'date': now,
'Display_Product': Display_Product
}
return render(request, 'Shop/Catalogue.html', context)
thanks and sorry for the long question
Using the {{ }} syntax to reference an object is only used in templates.
On your view you should just use Object.id when passing your initial values.
...
# Get the object that you need
product = Product.objects.first()
# Define your initial values
form = PlaceOrder(initial= {'Product_ID': product.id })
this is what i was looking for , found out that i can use different form method and combine them
i will put it out here hope someone might find it useful
<form method="post" action="" id="CartInput"> {% csrf_token %}
<div>
<input name="Product_ID" type="hidden" value="{{ Product.PId }}" >
<input name="HowMany" type="number" value="1" >
{{ form.DateSubmit }}
</div>
<div>
<input name="Cart{{ Product.PId }}" type="submit" value="Add to Cart">
</div>
</form>
Related
I am new to django. I want to use this django form to get number_of_days for all {{ name }} values
<div>
<form action="change_number_of_days" method="post">
{% csrf_token %}
{% for name in filenames %}
<input type="number" name="number_of_days" id="number_of_days" value=200>
<label for="number_of_days"> {{ name }} </label>
<input type="hidden" value="{{ name }}" name="name_of_file"><br><br>
{% endfor %}
<button type="submit"> Gem </button>
</form>
</div>
Currently Im only getting the values of the LAST loop(Pizzaria, 200), but I want to get all looped inputs as a POST request
This is my VIEW.py
def change_number_of_days(request):
if request.method == 'POST':
days = request.POST['number_of_days']
print(cleaning_days)
filename = request.POST['name_of_file']
print(filename)
return render(request, 'price_calculation_complete.html')
return HttpResponse("error")
You have explicitly mentioned that - That's why it shows only 200
<input type="number" name="number_of_days" id="number_of_days" value=200>
You have to set the first <input> tag's value to {{ name }}.
<div>
<form action="change_number_of_days" method="post">
{% csrf_token %}
{% for name in filenames %}
<input type="number" name="number_of_days" id="number_of_days" value="{{ name }}">
<label for="number_of_days"> {{ name }} </label>
<input type="hidden" value="200" name="name_of_file"><br><br>
{% endfor %}
<button type="submit"> Gem </button>
</form>
</div>
I figured it out. To anyone interested:
days_list = request.POST.getlist('number_of_cleaning_days')
I had to use .getlist instead of just POST
I need to render checkbox form fields in the following format in html template:
<input id="tag" type="checkbox" name="check" value="1">
<label for="tag">Tag 1</label>
Currently, in my template I tried:
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
<input id="{{ field.id_for_label }}" type="checkbox" name="check">
<label for="{{ field.id_for_label }}">{{ field.value }}</label>
{% endfor %}
This will not render {{ field.value }} (I get empty instead of Tag 1) and also is non sticky.
I also tried:
{% for field in filter.form.tags %}
{{ field.label_tag }}
{{ field }}
{% endfor %}
Which gives me nested of <label><input></input></label>, but displays everything that I need.
Is it possible to render a form such that I get the format that I'm after? (It should also preserve checked e.g. make ticks sticky).
Edit:
class TaskFilter(django_filters.FilterSet):
"""Filter for books by author"""
tags = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Task.tags.most_common())
title = django_filters.CharFilter(field_name='title', lookup_expr='icontains')
class Meta:
model = Task
fields = ['tags', 'title']
views.py
def task_list_filter(request):
if request.method == 'GET':
form = AdditionalForm(request.GET)
# process the form
results = Task.objects.all().order_by('-created')
f = TaskFilter(request.GET, queryset=results)
# Output final query set
results = f.qs[0:100] # only get first 100 objects
# Create pagination
# Get the view
return render(request, 'base/task_list_filter.html', {'filter': f,
'task_list': results,
'form': form })
To make sure the checkbox is in the correct state you can use the example you yourself provided with a few changes:
{% for field in filter.form.tags %}
<input type="checkbox" id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
{% if field.value %}checked{% endif %}>
<label for="{{ field.id_for_label }}">{{ field.value }}</label>
{% endfor %}
And remember that you can use the {{ field.label_tag }} to generate the entire label HTML tag.
In HTML
{% for field in filter.form.tags %}
{{ field.tag }} <!-- Generates the checkbox for the field -->
{{ field.choice_label }} <!-- Generates the named label of the field -->
{% endfor %}
I learned that from this guy who has lots of helpful information specific to using Django.
I'm using the Django-Filter library !important. For tags, I'm using Django-taggit.
I built the following filter.py:
class TaskFilter(django_filters.FilterSet):
tags = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckboxSelectMultiple, queryset=Task.tags.most_common())
class Meta:
model = Task
fields = ['tags']
However, when I pass this filter to the template, it doesn't render the tags properly. In particular {{ field.value }} is empty. Let's look at the following cases:
CASE 1.
# template.html
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
<label for="{{ field.id_for_label }}"></label>
{{ field.value }}
{% endfor %}
# out
<label for="id_tags_0"></label>
<label for="id_tags_1"></label>
<label for="id_tags_2"></label>
CASE 2.
# template.html
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
<label for="{{ field.id_for_label }}"></label>
{{ field }}
{% endfor %}
# out
<label for="id_tags_0"></label>
<label for="id_tags_0"><input type="checkbox" name="tags" value="4" id="id_tags_0">Tag 1</label>
<label for="id_tags_1"></label>
<label for="id_tags_1"><input type="checkbox" name="tags" value="1" id="id_tags_1">Tag 2</label>
<label for="id_tags_2"></label>
<label for="id_tags_2"><input type="checkbox" name="tags" value="2" id="id_tags_2">Tag 3</label>
CASE 3.
# template.html
{{ filter.form.tags.errors }}
{% for field in filter.form.tags %}
{{ field }}
{{ field.label_tag }}
{% endfor %}
#out
<label for="id_tags_0"><input type="checkbox" name="tags" value="4" id="id_tags_0">Tag 1</label>
<label for="id_tags_1"><input type="checkbox" name="tags" value="1" id="id_tags_1">Tag 2</label>
<label for="id_tags_2"><input type="checkbox" name="tags" value="2" id="id_tags_2">Tag 3</label>
I'm trying to understand why this happens. Why can't I get the values as stated in the docs
STEPS TO REPRODUCE
pip install django-filter + add 'django_filters' to APPS
pip install django-taggit + add 'taggit' to APPS
# models.py
class Task(models.Model):
title = models.CharField(max_length=100, blank=False)
tags = TaggableManager()
# Use the API to create an object.
t = Task.objects.create(title="Title")
t.tags.add("Tag 1","Tag 2")
# views.py
def view(request):
f = TaskFilter(request.GET, queryset=Task.objects.all())
return render(request, 'template.html', {'filter': f}
When you iterate over filter.form.tags you're not iterating over a set of form fields, but instead over a set of individual choices for the tags field. This is why field.value doesn't work.
This should work instead:
{{ filter.form.tags.errors }}
{% for choice in filter.form.tags %}
<label for="{{ choice.id_for_label }}"></label>
{{ choice.tag }}
{% endfor %}
Where tag is an attribute that exists on each choice, which will render the checkbox input for that choice.
This is documented in the documentation for RadioSelect:
To get more granular, you can use each radio button’s tag, choice_label and id_for_label attributes.
Further down, the documentation for CheckBoxSelectMultiple says that the same logic applies for it too.
I am trying to submit form with array fields and process on Django view. Also, I want to compare the submitted form data with correct answer table data.
question.html:
<form method="post" class="form-inline">
{% csrf_token %}
{% for question in questions %}
<h3>{{ question.title }}</h3>
<div class="radio">
<label class="radio-inline">
<input type="radio" name="ans{{ question.id }}" value="{{ question.option.0 }}">
{{ question.option.0 }}
</label>
</div>
<div class="radio">
<label class="radio-inline">
<input type="radio" name="ans{{ question.id }}" value="{{ question.option.1 }}">
{{ question.option.1 }}
</label>
</div>
<div class="radio">
<label class="radio-inline">
<input type="radio" name="ans{{ question.id }}" value="{{ question.option.2 }}">
{{ question.option.2 }}
</label>
</div>
{% endfor %}
<button type="submit" class="btn btn-success" name="ans_submit">Submit</button>
</form>
view.py:
if request.method == 'POST':
if(request.POST.get('ans_submit')):
temp_context["submitted_answers"] = request.POST.get("ans", "") # Receive as an array?
Expecting to get expert advice.
Thanks
Actually what is posted to you is ans0, ans1, ..., ansN.
So what you want to do is something like this:
answer_fields = [field for field in request.POST if field.startswith('ans')]
for field in answer_fields:
# Do something with `field`...
print(request.GET[field])
Additionally, you might want to check that the latter part is numeric, like so:
[field for field in request.POST
if field.startswith('ans') and field[3:].isnumeric()]
I am trying to render the images of the choices next to their respective choice. Attempting to do so will not save the form as valid so I have become lost at what to do. I've tried both methods below and I have no idea why one works and the other doesn't, could I get some tips?
#Form:
class ServerGroupForm(forms.Form):
OPTIONS = (
("pic1", "https://i.imgur.com/tMahp6U.png"),
("pic2", "https://i.imgur.com/b76nwsj.gif"),
("pic3", "https://i.imgur.com/qzEcfyX.png Lover"),
("pic4", "https://i.imgur.com/kdc7UF7.png"),
("pic5", "https://i.imgur.com/ynWJ13W.gif"),
("pic6!", "https://i.imgur.com/goHFWsp.png"),
("pic7", "https://i.imgur.com/b76nwsj.gif"),
("pic8", "https://i.imgur.com/KPgKm79.png"),
("pic9", "https://i.imgur.com/7KtEV1i.png"),
("pic10", "https://i.imgur.com/7KtEV1i.png"),
("pic11", "https://i.imgur.com/FXfo773.png")
)
servergroups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS)
#View:
def sendmessage(msg):
#Other code sends msg to user, not includes so this isn't long
def select_server_group(request):
form = ServerGroupForm(request.POST)
if form.is_valid():
servergroups = form.cleaned_data['servergroups']
sendmessage(msg=servergroups)
return redirect('/')
return render_to_response('webts3/selcectsgroup.html', {'form':form },
context_instance=RequestContext(request))
#HTML: Works but no icons
<section class="login">
<div class="titulo">Create a channel</div>
<form method="post" action="." enctype="multipart/form-data">{% csrf_token %}
<table border="0">
{{ form.as_table }}
</table>
<input type="submit" class="btn btn-block btn-danger" value="Submit" style="margin-top: 10px;">
</form>
</section>
#HTML: Icons but not working
<form method='post' action="." enctype="multipart/form-data">{% csrf_token %}>
<table>
{% for x,y in form.fields.servergroups.choices %}
<tr>
<td><input type="checkbox" name="{{ x }}" value="{{ x }}"><img src={{ y }}</img></td>
</tr>
{% endfor %}
</table>
<input type='submit' value='submit'>
</form>
The name attribute of the field should not be {{ x }}. It should be "servergroups".
Note you'd also need to have some logic that determines if the field is already selected, for when for example the form is being redisplayed after validation errors.