I would like to write a one-template view, which depending on the url path will show different field of the model. So for instance if path is
http://127.0.0.1:8000/trip/2/1/
I will get second trip from my db (that works), and 1 should give (as html is written) a description field. I don't know how to process this to context_processor in my view. Do you have any ideas?
views.py
class TripDescriptionCreate(LoginRequiredMixin, UpdateView):
model = Trip
template_name = 'tripplanner/trip_arguments.html'
fields = ["description", "city", "country", "climate", "currency", "food", "cost", "comment", "accomodation",
"car", "flight", "visa", "insurance", "remarks"]
context_object_name = 'trips'
success_url = '/'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
trip_arguments.html
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">{{ trips.tripName }}</legend>
{% if field_id == 1 %}
{{ form.description|as_crispy_field }}
{% elif field_id == 2 %}
{{ form.city|as_crispy_field }}
{% endif %}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
urls.py
path('trip/<int:pk>/<int:field_id>', TripDescriptionCreate.as_view(), name='trip-fullfill'),
So I came up with this idea. In my html I added these lines:
{% url 'trip-fullfill-description' pk=trip.pk as description_url %}
{% url 'trip-fullfill-city' pk=trip.pk as city_url %}
{% if request.get_full_path == description_url %}
{{ form.description|as_crispy_field }}
{% elif request.get_full_path == city_url %}
{{ form.city|as_crispy_field }}
Related
I am developing a domestic worker booking app in django
When I try to pass the formset, I am not geting the label of that field. I am only getting the field in html.
{% for formset in formsets %}
<form method="post">
{% for form in formset %}
{% for field in form %}
<div>
<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endfor %}
This the html code
def staffApply(request,pk):
if request.method == 'POST':
selected_domestic_works = request.POST.getlist('domestic_works')
formsets = []
if 'cook' in selected_domestic_works:
formsets.append(CookingForm(request.POST,prefix='cook'))
if 'driver' in selected_domestic_works:
formsets.append(DriverForm(request.POST,prefix='driver'))
print(formsets)
return render(request, 'staffApply2.html', {'formsets': formsets})
return render(request,'staffapply.html',{'uid':pk})
enter code here
This is my views.py
class CookingForm(ModelForm):
food_cooked=(('veg','veg'),
('non-veg','non-veg'),
('both','both')
)
class Meta:
model = Cook
fields = '__all__'
exclude=['user']
widgets={
'food_cooked':forms.widgets.RadioSelect(),
'type_of_cuisine':forms.widgets.CheckboxSelectMultiple()
}
This is my forms.py
I am getting the fields to type. But I am not getting hte label for those fields. Please help me fix this.
class Cook(models.Model):
food_cooked=(('veg','veg'),
('non-veg','non-veg'),
('both','both')
)
type_of_cuisine=(('NorthIndian','NorthIndian'),
('SouthIndian','SouthIndian'),
('Chettinadu','Chettinadu'),
('Chinese','Chinese'),
)
user=models.ForeignKey(User,on_delete=models.CASCADE)
food_cooked=models.CharField(choices=food_cooked,max_length=30)
type_of_cuisine=models.CharField(choices=type_of_cuisine,max_length=30)
experience=models.IntegerField()
wages_expected=models.IntegerField()
dishwashing_flag=models.BooleanField()
wages_for_dishwashing=models.IntegerField(null=True)
desc=models.TextField(max_length=200)
This is my models.py
You have one extra loop, with the wrong naming so you cannot access {{ field.label }} on your loops its like you are trying something like {{ form.field.attribute.label }}, the correct way would be the following:
{% for form in formsets %}
<form method="post">
{% for field in form %}
<div>
<label for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endfor %}
That being said, you can also use Django form rendering options, instead of doing it manually.
{% for form in formsets %}
<form method="post">
{{form.as_p}}
<input type="submit" value="Submit">
</form>
{% endfor %}
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page.
The value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py
The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none
The Html template
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}
{% block extrahead %}
{{ media }}
{% endblock %}
{% block content %}
<form class="change_superprofile_parent_form" met`your text`hod="POST" class="change_superprofile_parent_form">{% csrf_token %}
{% for superprofile in superprofiles %}
<input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Django admin.py
def change_superprofile_parent(self, request, queryset):
"""
Action to change the superprofile of the selected
"""
queryset = queryset.values_list("id", flat=True)
if request.method == 'POST':
selected_value = request.POST.getlist('superprofile_selected')
eligible_superprofiles = SuperProfile.objects.filter(status='Active')
return render(
request, 'admin/auth/user/change_superprofile_parent.html', context={
'superprofiles': eligible_superprofiles,
}
)
I have created a custom html template with basic checkboxes to select a value and return the value to the Django admin page.
I have done a 100 times before, but now the value of the selected superprofile does not get captured by the variable "selected_value" in the admin.py
The if statement "if request.method == 'POST':" is getting triggered but i keep getting the value of "selected_value" as none
Driving me crazy, I cannot find anything wrong in the code
The Html template
{% extends "admin/base_site.html" %}
{% load i18n admin_urls static admin_modify %}
{% block extrahead %}
{{ media }}
{% endblock %}
{% block content %}
<form class="change_superprofile_parent_form" method="POST" class="change_superprofile_parent_form">{% csrf_token %}
{% for superprofile in superprofiles %}
<input type="checkbox" name="superprofile_selected" {{ superprofile.checked }} value="{{ superprofile }}"> {{ superprofile }}<br>
{% endfor %}
<input type="submit" value="Submit">
</form>
{% endblock %}
Django admin.py
def change_superprofile_parent(self, request, queryset):
"""
Action to change the superprofile of the selected
"""
queryset = queryset.values_list("id", flat=True)
if request.method == 'POST':
selected_value = request.POST.getlist('superprofile_selected')
eligible_superprofiles = SuperProfile.objects.filter(status='Active')
return render(
request, 'admin/auth/user/change_superprofile_parent.html', context={
'superprofiles': eligible_superprofiles,
}
)
I have a Django form in which I use crispy-forms along with bootstrap5. Everything was alright until I wanted to changed the Layout of my form. As my form is constructed dynamically, I just wanted to define the value of a set element item which is under the form (field_name, layout_index). The goal was to define it as a FieldWithButton, as I couldn't find another way to do that.
To do that, I modified my helper in the __init__ method of my form :
self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")), id=f'div_id_{item[0]}', css_class='mb-3 row')
This is rendered nearly correctly in my form, I have the FieldWithButton with Div etc. However, the div which contains my FieldWithButton doesn't take the field_class of my helper that I defined, and instead creates a <divclass='col-10'>...</divclass='col-10'>.
There's juste a space which disappeared and messed everything up. How can I either remove the class='col-10' part of my div and put it as its class or differently define my Field as a FieldWithButton ?
Here's my whole form class if needed :
class ScriptInputForm(forms.Form):
def __init__(self, *args, **kwargs):
variables = kwargs.pop('variables') # All variables to render
variables_names = [*variables] # under the form {'name':['type', 'description']}
super().__init__(*args, **kwargs)
for var in variables_names: # Dynamic creation of the fields
values = variables[var]
field = self.fields[var] = forms.CharField()
field.widget.attrs['placeholder'] = values[1].title()
self.helper = FormHelper(self)
num = 1 # Rough part where I define the tuples ('name', 'index') of all lists in my variables
lists = []
for k,v in variables.items():
if v[0]=='list':
lists.append((k,num))
num+=1
for item in lists: # Part where the problem is coming from
self.helper[item[1]] = Div(FieldWithButtons(item[0], StrictButton("Add item")))
self.helper.add_input(Submit('submit', 'Submit'),)
self.helper.label_class = 'col-2'
self.helper.field_class = 'col-10'
self.helper.form_action = reverse_lazy('scripts:data_input')
And the rendered HTML :
<div>
<div class="mb-3 row">
<label for="id_liste" class="col-form-label col-2">Liste</label>
<divclass="col-10"> <!-- With <div class="col-10"> everything's ok -->
<div class="input-group">
<input type="text" name="liste" placeholder="Your List" class="textinput textInput form-control" id="id_liste">
<button class="btn" type="button">Add item</button>
</div>
</divclass="col-10">
</div>
</div>
Seems like it was an error in crispy-bootstrap5.
The FieldWithButtons display is defined in field_with_buttons.html whose code is the following :
<div{% if div.css_id %} id="{{ div.css_id }}"{% endif %} class="mb-3{% if 'form-horizontal' in form_class %} row{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}{% if div.css_class %} {{ div.css_class }}{% endif %}" {{ div.flat_attrs }}>
{% if field.label and form_show_labels %}
<label for="{{ field.id_for_label }}" class="{% if 'form-horizontal' in form_class %}col-form-label {% else %}form-label {% endif %}{{ label_class }}{% if field.field.required %} requiredField{% endif %}">
{{ field.label }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</label>
{% endif %}
<div{% if field_class %}class="{{ field_class }}"{% endif %}> <!-- Here -->
<div class="input-group{% if input_size %} {{ input_size }}{% endif %}">
{% if field.errors %}
{% crispy_field field 'class' 'form-control is-invalid' %}
{% else %}
{% crispy_field field 'class' 'form-control' %}
{% endif %}
{{ buttons|safe }}
</div>
{% for error in field.errors %}
<p id="error_{{ forloop.counter }}_{{ field.auto_id }}" class="text-danger mb-0"><small><strong>{{ error }}</strong></small></p>
{% endfor %}
{% include 'bootstrap5/layout/help_text.html' %}
</div>
</div>
Just had to add a space at the start of the second div to fix the issue.
I have two views in my app
Views.py
def selectwarehouse(request):
z = Warehouse.objects.all()
return render(request, 'packsapp/employee/selectwarehouse.html', {'z': z})
def warehouse_details(request):
queryset = AllotmentDocket.objects.filter(send_from_warehouse = #dynamic(from the selectwarehouse.html))
return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query': queryset})
selectwarehouse.html
{% block content %}
<label>Select Warehouse<label>
<select id="the-id">
{% for i in z %}
<option value="{{ i }}">{{ i }}</option>
{% endfor %}
<form method="post" novalidate>
{% csrf_token %}
Proceed
Nevermind
</form>
</select>
{% endblock %}
URLS.py
path('select-warehouse/', selectwarehouse, name='select_warehouse'),
path('warehouse-details/', warehouse_details, name='warehouse_details'),
I want that when a person selects the "Warehouse" from the dropdown and clicks on Proceed, it should pass that value to def warehouse_details and pass the value to Allotment queryset. How Can I do that ?
MAKE Proceed as a hidden input
Template
{% block content %}
<label>Select Warehouse<label>
<select id="the-id">
{% for i in z %}
<option value="{{ i }}">{{ i }}</option>
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="object_id" value="{{ i.id }}">
<input class="btn btn-outline-secondary" name="Proceed" type="submit"
value="Proceed">
<a href="{% url 'employee:products_table' %}" class="btn btn-outline-
secondary" role="button">Nevermind</a>
</form>
{% endfor %}
</select>
{% endblock %}
views.py
def selectwarehouse(request):
z = Warehouse.objects.all()
return render(request, 'packsapp/employee/selectwarehouse.html', {'z': z})
def warehouse_details(request):
queryset = AllotmentDocket.objects.get(id=request.POST.get('object_id'))
//Now to access the element in queryset write (queryset.'attribute name')
return render(request, 'packsapp/employee/allotwarehousedetails.html', {'query':
queryset}
Check if this works
Try printing the queryset and see what is the output.