Django ask for fill a form not required - html

I've a strange bug with my forms.
In a page I must hande 2 separate forms,
the 1st one have no problem at all and I can add the record in DB ,
the 2nd one raise me an error asking to fill a required data of 1st form.
The POST dictionary looks ok
Here the log:
<QueryDict: {'csrfmiddlewaretoken': ['lvt5Ph2SA1xxFK4LMotdHOWk2JuZzYDo0OKWc77rKICYKYmemy3gl0dBphnRNcFb'], 'pk_atto': ['1.1'], 'pk_persona': ['1'], 'capacita': ['11'], 'Aggiungi_persona': ['persona'], 'tipo': ['fondo']}>
<ul class="errorlist"><li>pk_particella<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
the views:
if request.method == 'POST':
if("Aggiungi_particella" in request.POST):
save_atto = AttiPartenzeParticelleForm(request.POST)
else:
save_atto = AttiPartenzePersoneForm(request.POST)
print(request.POST)
print(save_atto.errors)
if save_atto.is_valid():
save_atto.save()
return redirect('/aggiungi_atto_partenza' + '/' + str(save_atto['pk_atto'].value()))
the forms:
class AttiPartenzeParticelleForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_particella = forms.ModelChoiceField(queryset=Particelle.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
class AttiPartenzePersoneForm(ModelForm):
pk_atto = forms.ModelChoiceField(queryset=Atti.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
pk_persona = forms.ModelChoiceField(queryset=Persone.objects.all(),
widget=forms.Select
(attrs={'class': 'form-control'}))
capacita = forms.CharField(max_length=30,
widget=forms.NumberInput
(attrs={'class': 'form-control'}))
tipo = forms.CharField(max_length=30, initial="fondo", widget=forms.TextInput (attrs={'class': 'form-control'}))
class Meta:
model = Acquisizioni_Cessioni_particella
fields = '__all__'
and the HTML
<div id="particella" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="particella_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ form.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ form.pk_particella|as_crispy_field }}
</div>
<div class="col-2">
{{ form.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button form="particella_f" class="btn btn-outline-primary btn-lg mt-5" type="submit" name="Aggiungi_particella" value="particella">
AGGIUNGI PARTICELLA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
<div id="persona" class="content-section d-flex justify-content-center mt-5">
<form action="" method="POST" id="persona_f">
{% csrf_token %}
<fieldset class="form-group">
<div style="visibility:hidden">
{{ persona.pk_atto|as_crispy_field }}
</div>
<div class="row">
<div class="col-8">
{{ persona.pk_persona|as_crispy_field }}
</div>
<div class="col-2">
{{ persona.capacita|as_crispy_field }}
</div>
<div class="col-4 d-flex justify-content-center">
<button class="btn btn-outline-primary btn-lg mt-5" form="persona_f" type="submit" name="Aggiungi_persona" value="persona">
AGGIUNGI PERSONA
</button>
</div>
<div style="visibility:hidden">
{{ form.tipo|as_crispy_field }}
</div>
</div>
</fieldset>
</form>
</div>
soneone have any idea?
thx

Related

Dropdown are not working in Django , HTML

I am trying to display data from database throw drop-down list and Use filter query to filter data and display
if i tried to select value of html and select but slot is not create. Debugging form and i see error. If i select anything but drop-down do't selected here is error
Here is my code: slot/views.py
def slot_create(request):
form = SlotForm(request.POST)
print(form)
station = Station.objects.filter(user_id=request.user)
print(station)
if form.is_valid():
slot = form.save(commit=False)
slot.user = request.user
slot.save()
messages.success(request, 'Your Slot is add successfully')
return redirect('view_slot')
return render(request, 'add_slot.html', {
'form': form,
'station': station
})
here is my add_slot.html
<form method="post" novalidate>
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.slot_name|as_crispy_field }}
</div>
<div class="form-group col-md-12 mb-0">
{{ form.per_unit_price|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.current_status|as_crispy_field }}
</div>
{% comment %} <div class="form-group col-md-6 mb-0">
{{ form.station|as_crispy_field }}
</div> {% endcomment %}
<div class="form-group col-md-6 mb-0">
<label for="station" class="block font-semibold text-sm mb-1"> Choose Station </label>
<select name="station_name" id = "station">
{% for station in station %}
<option value="{{station}}"> {{station}} </option>
{% endfor %}
</select>
</div>
<button type="submit" class="w-full rounded-full bg-red-gradient p-3 text-white font-bold hover:ring">
Add Slot
</button>
</div>
</form>

How to Create search function in Flask using Sqlite3

This is my form for search function
<form class="form-inline ml-auto" action="{{ url_for('search') }}" method="POST">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
Now I wan to display it if its match so this is my html
{% for articles in data %}
<div class="card m-3">
<input type="hidden" value="{{ data[0] }}" id="id" name="id">
<h5 class="card-header">{{ data[0] }}</h5>
<div class="card-body">
<h5 class="card-title">{{ data[2] }} - {{ data[3] }}</h5>
<p class="card-text">{{ data[4] }}</p>
</div>
<div class="row m-3 ml-auto">
<div class="btn-group mr-2">
Update Article
</div>
<div class="btn-group">
Delete Article
</div>
</div>
</div>
{% endfor %}
And also this is my query filter
#app.route('/search',methods = ['POST', 'GET'])
def search_route():
if request.method == 'POST':
q= request.args.get('search')
with sqlite3.connect("blogdb.db") as con:
cur = con.cursor()
cur.execute('SELECT * FROM articles WHERE title = ?', (q))
art = cur.fetchall()
cur.close()
print(art[0])
con.commit()
return render_template('search.html', data = art[0])
So far what I got is that it doesnt return anything I also tried to print(art[0]) so that I can see what did i get but i aint getting anything.

Can I match the height of a formset input with a button?

I'm currently making a todo list using Django model formsets. I came across a problem when trying to list each form in the formset with a delete button next to it. Here's a picture of what it looks like now:
When looked at closely, the spacing and height for each form are slightly different than the spacing and height for each delete button. The buttons are slightly larger and more spaced out than the forms. Here's my views.py:
def dashboard(request):
user = request.user
todo_list = Todo.objects.filter(user=user).all()
UpdateFormSet = modelformset_factory(Todo, fields=('item',))
if request.method == 'POST':
formset = UpdateFormSet(request.POST, queryset=todo_list)
if 'delete' in request.POST:
items_to_delete = request.POST.getlist('delete')
deleted_items = Todo.objects.filter(pk__in=items_to_delete).delete()
if 'update' in request.POST:
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances:
instance.user = user
instance.save()
return redirect('dashboard')
formset = UpdateFormSet(queryset=todo_list)
if not formset:
formset = UpdateFormSet()
context = {
'current_user': request.user,
'formset':formset,
'items':todo_list,
}
return render(request, 'users/dashboard.html', context)
Template:
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 pt-3">ToDo Items</legend>
{{ formset.management_form }}
<div class="row">
<div class="col-6">
{% for form in formset reversed %}
{{ form.id }}
<div class="py-3">
{{ form.item }}
</div>
{% endfor %}
</div>
<div class="col-6">
<div class="input-group">
<div class="input-group-append">
<button type="submit" class="btn btn-sm btn-success my-3" name="update"><i class="fas fa-plus"></i>
</button>
</div>
</div>
{% for item in items reversed %}
<div class="input-group">
<div class="input-group-append">
<button type="submit" class="btn btn-sm btn-danger my-3" name="delete" value="{{ item.pk }}">
<i class="far fa-trash-alt"></i>
</button>
</div>
</div>
{% endfor %}
</div>
</div>
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit" name="update">Save</button>
</div>
</form>
I can't seem to align each form with its delete button. I'm guessing the two for loops are interfering with that. Any help would be much appreciated!

submit button in django refreshes the page without saving

I am trying to save data in ORM via a form but when I click on the submit button all it does is refresh the page with the same data.
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy form %}
{% load widget_tweaks %}
{% block content %}
<h2 class="mb-3">Add a Warehouse</h2>
<div class="row">
<form method="post" class="col-md-12 proct-form" novalidate>
{% csrf_token %}
<div class="form-group col-md-4 mb-0">
{{ form.owner|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_name|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_email|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_contact|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_city|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_pincode|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_state|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_pan|as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.warehouse_gst|as_crispy_field }}
</div>
<div class="form-group col-md-12 mb-0">
<button type="submit" class="btn btn-success">Save</button>
Nevermind
</div>
</form>
</div>
{% endblock %}
Views.py
#method_decorator([login_required, employee_required], name='dispatch')
class WarehouseFormView(CreateView):
model = Warehouse
fields = "__all__"
template_name = 'packsapp/employee/warehouseForm.html'
def form_valid (self, form):
product = form.save(commit=False)
product.save()
messages.success(self.request, 'The Warehouse was created with success!')
return redirect('employee:warehouse_table')
Is there a problem with my views.py or do I need to change my templates?
All the other forms in the app are created the same way and they work fine

django ModelForm DateField initial value not working

I want to set initial data in my ModelForm for a datefield but it is not working. Below is my code.
def get_date():
return timezone.localtime(timezone.now()).date()
ModelForm:
class TransferPacketForm(forms.ModelForm):
party = forms.ModelChoiceField(
required=True, queryset=Party.objects.all(),
widget=forms.Select(
attrs={
'class': 'form-control'
}
)
)
transferred_on = forms.DateField(
required=True, initial=get_date, input_formats=['%d-%m-%Y'],
validators=[validators.get('min_value')(date(2000, 01, 01))],
widget=forms.DateInput(
format='%d-%m-%Y',
attrs={
'autofocus': 'true', 'class': 'form-control'
}
)
)
transferred_roi = forms.DecimalField(
required=True, max_digits=3, decimal_places=2,
min_value=1.00, max_value=5.00,
widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
transferred_amount = forms.IntegerField(
required=True, min_value=1, widget=forms.TextInput(
attrs={
'class': 'form-control'
}
)
)
class Meta:
model = Packet
fields = (
'transferred_on', 'transferred_amount',
'transferred_remark', 'transferred_roi',
'party'
)
widgets = {
'transferred_remark': forms.Textarea(
attrs={
'class': 'form-control'
}
)
}
View:
class TransferPacketView(LoginRequiredMixin, UpdateView):
model = Packet
form_class = TransferPacketForm
http_method_names = ['get', 'post']
template_name = 'update_templates/transfer_packet.html'
def get_success_url(self):
return reverse(
'girvi:transferred_packet',
kwargs={
'pk': self.get_object()
}
)
def get(self, request, *args, **kwargs):
return super(TransferPacketView, self).get(request, *args, **kwargs)
def form_valid(self, form):
pkt_obj = self.get_object()
pkt_obj.is_transferred = True
pkt_obj.save()
return redirect(
self.get_success_url()
)
Form:
<tr><th><label for="id_transferred_on">Transferred on:</label></th><td><input autofocus="true" class="form-control" id="id_transferred_on" name="transferred_on" type="text" value="15-02-2015" /></td></tr>
<tr><th><label for="id_transferred_amount">Transferred amount:</label></th><td><input class="form-control" id="id_transferred_amount" name="transferred_amount" type="text" /></td></tr>
<tr><th><label for="id_transferred_remark">Transferred remark:</label></th><td><textarea class="form-control" cols="40" id="id_transferred_remark" maxlength="150" name="transferred_remark" rows="10">
</textarea></td></tr>
<tr><th><label for="id_transferred_roi">Transferred roi:</label></th><td><input class="form-control" id="id_transferred_roi" name="transferred_roi" type="text" /></td></tr>
<tr><th><label for="id_party">Party:</label></th><td><select class="form-control" id="id_party" name="party">
<option value="" selected="selected">---------</option>
<option value="2">ram pal</option>
<option value="1">shyam pal</option>
</select></td></tr>
But html form is rendered without any initial data.
Html form field:
<div class="form-group form-group-sm clearfix">
<label class="control-label col-xs-2 col-xs-offset-6" for="id_transferred_on">Dated</label>
<div class="col-xs-4 pull-right">
<div id="datepicker" class="input-group date">
<input id="id_transferred_on" class="form-control" type="text" name="transferred_on" autofocus="true">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
Can someone tell me what is wrong??? Why value is not set to initial data.
Template:
<form id="transferPacketForm" class="form form-horizontal width-500 center-block theme-font" role="form" action="." method="post">{% csrf_token %}
<!-- DIV -->
{% if form.errors %}
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
{% for field in form %}
{% if field.errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>{{ field.label }}: {{ field.errors|striptags }}</span><br>
{% endif %}
{% endfor %}
{% for error in form.non_field_errors %}
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>Error: {{ error|striptags }}</span>
{% endfor %}
</div>
{% endif %}
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm clearfix">
<label for="id_{{ form.transferred_on.name }}" class="control-label col-xs-2 col-xs-offset-6">Dated</label>
<div class="col-xs-4 pull-right">
<div class="input-group date" id='datepicker'>
{{ form.transferred_on }}
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.party.name }}" class="control-label col-xs-4">{{ form.party.label }}</label>
<div class="col-xs-8">
{{ form.party }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_amount.name }}" class="control-label col-xs-4">Amount</label>
<div class="col-xs-8">
{{ form.transferred_amount }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_roi.name }}" class="control-label col-xs-4">Interest</label>
<div class="col-xs-8">
{{ form.transferred_roi }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="form-group form-group-sm">
<label for="id_{{ form.transferred_remark.name }}" class="control-label col-xs-4">Remark</label>
<div class="col-xs-8">
{{ form.transferred_remark }}
</div>
</div>
<!-- /DIV -->
<!-- DIV -->
<div class="btn-toolbar" align="middle">
<button type="submit" class="btn btn-primary btn-color btn-bg-color">Submit</button>
<button type="button" class="btn btn-danger btn-color btn-bg-color" onclick="window.close()">Close</button>
</div>
<!-- /DIV -->
</form>
It will only render initial value if you have no model instance passed to the form. Try this:
p = Packet.objects.filter(transferred_on__isnull=True)[0]
# or simply
p = Packet()
f = TransferPacketForm(instance=p)
print(f['transferred_on'])
which will not have initial value for that field, but if you do:
f = TransferPacketForm()
print(f['transferred_on'])
it will. Check it out.
Edit
It doesn't apply when you pass initial dictionary to the form, it will actually check if the model's field is empty and use the value from the dictionary. So workaround for you is not to use field's initial, but forms' initial instead, namely through view's get_initial() it is.