Integrating normal HTML form with Django form - python-3.x

What I am trying to do is have a form that has this HTML:
<form method="post" action="">
{% csrf_token %}
<label>Pick a class:</label>
<select id="schedClass" name="schedClass" >
<option>Select one</option>
{% for i in classes %}
<option value="{{ i.id }}">{{ i.name }}</option>
{% endfor %}
</select>
</select>
{{ form }}
<input type="submit" value="reload">
</form>
The problem is that for some reason when I submit, the select schedClass doesn't appear in the link. I think it comes from the fact that it's integrated with a django form, but I have no idea.
For clarification, what I am trying to do is have a form that creates an instance of a specific model, and one of the categories is schedClass which is a ManyToManyField, but I can't use a ModelForm since I need the items in the selections to be only ones that are also linked to the user with another ManyToMany.
Is there anything to do?

Related

Showing model data as dropdown list in html Template in Django?

I am trying to access model's data for implementation as dropdown menu but I got stuck in this problem. Can anyone help me??
Here is what i have....
views.py
def educationdata(request):
obj = DegreeDetails.objects.all()
context={
'Data':obj
}
return render(request,'Education.html', context)
This the view I have created for the model DegreeDetails
Model.py
class DegreeDetails (models.Model):
degree = models.CharField(max_length=10)
discipline = models.CharField(max_length= 15)
def __str__(self):
return '%s %s'%(self.degree, self.discipline)
This is the model i am using and this model is used as a ForeignKey in another model as follows, hence i want to show it as dropdown field
degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE)
Template.Html
<div class="col-lg-8 col-md-8">
<label>Degree Details</label>
<input type="text" name="degree_details" id="inputdegree_details" class="form-control" placeholder="Select from Dropdown" value="{{education_form.initial.degree_details}}">
<select class="form-control">
{% for data in Data %}
<option>{{data}}</option>
{% endfor %}
</select>
Look forward to your responses, Thank you
You should use django forms. It is well explained in the docs.
It is better to use Django Forms or modelforms.
Official Document https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/
for fixing the current code that you have written.
you need to set id as a value for each option in the dropdown.
<div class="col-lg-8 col-md-8">
<label>Degree Details</label>
<input type="text" name="degree_details" id="inputdegree_details" class="form-control" placeholder="Select from Dropdown" value="{{education_form.initial.degree_details}}">
<select class="form-control">
{% for data in Data %}
<option value="{{data.id}}">{{data}}</option>
{% endfor %}
</select>

Django Form issue

I am using Django to select language. One option works fine, but the other won't work
Option (1) Works fine .
<select name="language"
onchange="this.form.submit()" >
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% for lang in LANGUAGES %}
<option value="{{ lang.0 }}" {% if lang.0 == LANGUAGE_CODE %} selected="selected"{% endif %} >{{ lang.1 }} ({{ lang.0 }})</option>
{% endfor %}
</select>
Option 1 : Not working using (form Submit Button )
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="LanForm">
{% csrf_token %}
<input class="lang" id="language" name="language" type="hidden" value="ar">
<input class="lang" id="setl" name="setl" type="submit" value="Go">
</form>
The select option works fine and change the language and redirect properly . But if I use the "Go" button , nothing is changing . I am wondering what is issue.
Firstly you do not set more than one node with the same id.
Secondly, you have kept the name of both submit and hidden inputs same i.e, 'language'.
Use the below snippet and test again
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="language">
{% csrf_token %}
<input class="lang" id="language" name="language" type="hidden" value="ar">
<input class="lang" type="submit" value="Go">
</form>
I managed to fix this issue by modfing the form as follows,
<form action="{% url 'set_language' %}" method="post" id="LanForm" name="LanForm">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />
<input name="language" type="hidden" value="ar" />
<input class="lang" name="language2" type="button" value="Go" onclick=" document.getElementById('LanForm').submit();" >
</form>
No ids no names in the input field

How can I read user inputs from a dynamically created form in flask?

I want to create a dynamic input form and read the user inputs back when a button ("Submit") is pressed, what is the best way (a good way) to do this?
I have tried creating a dynamic form with a FieldList but I was unable to get the values from the user.
This is (hopefully all of) the relevant code:
forms.py
class EntryForm(Form):
field = StringField()
class DynamicForm(FlaskForm):
parameter = FieldList(FormField(EntryForm), min_entries=1)
submit = SubmitField('Submit')
routes.py
#app.route("/new", method=['GET', 'POST'])
def new_form():
form = DynamicForm()
if form.validate_on_submit():
values = form.parameter #This does not work as intended.
do_stuff(values)
return redirect(url_for('index'))
parameter = utils.get_parameter()
return render_template('dynamic_form.html', form=form, parameter=parameter)
where utils.get_parameter() returns an unknown list of parameters. Or to be precise the function expects a parameter and returns a list based on this paramater, but I have omitted this here.
dynamic_form.html
{% extends "layout.html" %}
{% macro render_field(item) %}
<div class="form-group">
<label class="form-control-label">{{ item.label }}</label>
<input type="text" name="{{ item.name }}" class="form-control" value="{{ item.value }}"/>
</div>
{% endmacro %}
{% block content %}
<div class="content-section">
<form method="POST" action="">
{{ form.hidden_tag() }}
<fieldset class ="form-group">
<legend class="border-bottom mb-4">Parameter</legend>
{% for item in form.parameter %}
{{ render_field(item) }}}
{% endfor %}
</fieldset>
<div class="form-group">
{{ form.submit(class="btn btn-outline-info") }}
</div>
</form>
</div>
{% endblock content %}
I assume it is because the validate_on_submit() is called after the form is constructed (again) and thus it does not contain the form fields, and especially not the user inputs. Is there a way to prevent this "data loss" or is this a completely wrong approach?
Also, please let me know if information is missing.
You don't want to validate the form when the page first loads. Try this first:
if request.method == "POST" and form.validate_on_submit():
values = form.parameter
do_stuff(values)
return redirect(url_for('index'))
Next, notice that you are redirecting them to your view for def index():. Is that what you want?

Django - Form is not saving to Db

I'm using for authentication extended AbstractUser and ModelForm. When I write on HTML page only {{ form }} everything works fine, the form is submitting, but in the following case I've added some stylings, but now nothing works. Please, help me find the reason.
HTML:
<form method='POST'>
{% csrf_token %}
<div class="sign-up-user">
<div class="sign-up-user-container">
<div class="sign-up-user-left">
<label for="">{{form.username.label}}</label>
{{form.username}}<br>
<label for="">{{form.password.label}}</label>
{{form.password}}<br>
<label for="">{{form.branch.label}}</label><br>
{{form.branch}}<br>
<label for="">{{form.license_number.label}}</label>
{{form.license_number}}<br>
<label for="">{{form.fin_number.label}}</label>
{{form.fin_number}}<br>
<label for="">{{form.voen_number.label}}</label>
{{form.voen_number}}<br>
</div>
</div>
<input type="submit" value="Register User" class="sign-up-btn">
</div>
</form>
Include two lines to your HTML to understand whats going wrong:
{{ form.errors }}
{{ form.non_field_errors }}
This will display any errors that are associated with the form. If they dont then in your views do the following:
form = YourForm()
if form.is_valid():
// Do things
else:
print (form.errors)
print(form.non_field_errors)
This will display some other errors that you are missing.

request.POST does not return multiple fields values in Django

I started using Django to create a simple webapp.
I am using multipleselect to have a dropdown that allows multiple selection.
I tried almost all solutions found here but none of them seem to work for me.
I am using python 3.5
HTML:
<form action="datareturn.html" method="post">
{% csrf_token %}
<select id="probs_location" multiple="multiple" name="probs_locations[]">
{% for probs_location in probs_locations %}
<option value="{{ probs_location }}">{{ probs_location }}</option>
{% endfor %}
</select>
...........#Other input fields
</form>
<script>
$('#probs_location').multiselect({
enableClickableOptGroups: true
});
</script>
PYTHON-DJANGO:
def datareturn(request):
if request.method=='POST':
print(request.POST)
print(request.POST.getlist('probs_locations[]'))
return HttpResponse("Success")
request.POST returns all other fields except for multiple select
fields.
request.POST.getlist('probs_locations[]') returns a empty list.
You have an error in select tag, multiple is an argument you simply pass like below:
<select id="probs_location" name="probs_locations[]" multiple>
That's probably why it's not recognized. Besides probs_locations[] looks like a terrible name, probs_locations_list would be a lot better.

Resources