How to integrate HTML form into django view and model? - html

I have one html file which contain submission form.
I want to use this HTML form in django with model and view.
I dont want to use form class in html like
<form method="post" action="">
{% csrf_token %}
{{ form }}
<input type="submit" value="Register"/>
</form>
I want to use complete form code in HTML and use django model to store that data in database.
How can I do that?

Please update the question that you want to use jQuery.Django by defaults generate id for its form element.
As avinash already said you can always inspect the element and get the id and classses but some time we need custom class in that case you can use something like.
If you want to write your own custom fields.
class myForm(forms.ModelForm):
class Meta:
model = ModeName
widgets = {
'field_one': forms.TextInput(attrs={'id':'foo', 'name':'foo'})
'field_two': forms.TextInput(attrs={'id':'bar', 'name':'bar'})
}

Related

Flask WTForms SelectField add placeholder or disabled option

I am working on a webpage using flask and wtforms. When opening the webpage, my selectfield should not hold any value (i.e. be blank, have placeholder saying "please choose an option" or something in that direction).
My form is defined like this in forms.py:
class Form(FlaskForm):
selectfield = SelectField('Title', choices=[])
I leave choices as an empty list because they are created from a database through the function get_choices:
# create instance of form
form = Form()
# run function to get data from db
form.selectfield.choices = get_choices()
Here it starts to get gnarly: Since the placeholder value should be empty (i.e. "") or something like "please choose" I don't want to have it in my database. So I add the value manually:
# append
form.selectfield.choices.append('Please choose')
The html part, where I render the form looks like this:
<form method="POST" action= {{ url_for('index') }}>
{{ form.csrf_token }}
{{ form.selectfield(class_="form-control", **{"onchange":"this.form.submit()"}) }}
</form>
What have I tried:
adding 'placeholder = "please choose"' here:
{{ form.selectfield(placeholder="please choose", class_="form-control", **{"onchange":"this.form.submit()"}) }}
(as suggested by Crast here: WTForms Can I add a placeholder attribute when I init a field?)
adding default="Please choose" to my Form class as suggested by Liu Yue (How do you set a default value for a WTForms SelectField?):
class Form(FlaskForm):
selectfield = SelectField('Title', choices=[], default="Please choose")
This works partly, but the Please Choose value should not be selectable which it still is.
I feel like I might be completely on a wrong path here, and maybe oversee a very simple feature. I really can't believe that such a popular feature is not available using wtforms.
I am thankful for any advice and guidance.

Placing a <select> field using Django templates with custom bootstrap styles

I am having an issues connecting my html css javascript front-end with django. I have html templates that look and work exactly as I want them too. I can display data without issue with I make a call to a django field that is part of my current view using:
<a>{{ thing.attribute }}</a>
That works great.
My issue is when trying to connect a form to the django view I created for updating and creating records using a POST action. For example, when using an mdbootstrap themed template, I have implemented an html <select> object like this:
<select type="select" class="mdb-select" id="fieldOne">
<option value="0">Something</option>
<option value="1">Something</option>
<option value="2">Something</option>
</select>
This works and looks exactly like I want it too as it is correctly utilizing the proper css and javascript.
When I want to place a django form object in place of the same field, I have to call it like this:
<div class="mdb-select">{{ thing.attribute }}</div>
I have to call it as a <div> in django, and it's breaking my css and javascript, thus not displaying correctly and not usable. I can see the data being returned when I look at the rendered html in dev tools, so I know my django views and forms are working.
Is there any way to call a django object while still utilizing the <select> tags in my html template?
1) If you're using model forms, do one one this:
Use django widget_tweaks and then in your template do this:
{% load widget_tweaks %}
<label>{{my_form.field.label}}</label>
{% render_field my_form.field class="mdb-select" name="field" %}
OR
class NewSomethingForm(ModelForm):
class Meta:
model = Account
fields = ['name', 'last_name', 'description']
def __init__(self, *args, **kwargs):
self.fields['description'].widget = forms.Textarea(attrs={'class': 'md-textarea', 'style': 'height: 75px'})`enter code here`
2) If you're not using model forms, then in your template, try this:
<select type="select" class="mdb-select" id="fieldOne" name=field>
<option value="my_form.field_name.field.choices.0">my_form.field_name.field.choices.1</option>
<!–– follow same sequence -- >
</select>
Don't forget to give the dropdown element a name that matches the field on the form.
You can render a select field using Django ModelChoiceField. When you use this form in template using {{yourForm.select_field_name}} it will be rendered as with
id:id_select_field_name
name:select_field_name
The css classes you need to associate are included in attrs
from django import forms
class yourForm(forms.Form):
select_field_name=forms.ModelChoiceField(queryset=recieptDetail.objects.all(), widget = forms.Select(attrs = {'class':"class-name",'onchange' : "jsFunction();"}))

Create "static" HTML Pages For Each Product

I have 10k+ products that need their HTML Page and the stuff within is to be static (thus searchable). I am trying to find a way to do the following using django:
Loop over all the items.
Get the matching information.
Fill a model template.
Save such template with the information now static.
As much as I tried looking here on Stack Overflow and in the web, I did not find any instructions to do so.
Build a standard template that has variables for the products. Then on the backend you can search for the products you want and populate the template with their information. Something like this for a concept:
search.html
<form action="{% url 'your_url' %}" method="POST">
{% csrf_token %}
<input type=text name=input value="" />
<input type="submit" value="Submit">
product.html
<html>
<div>Hello {{name}}!</div>
</html>
models.py
class Names:
user_name = models.CharField(max_length=200)
def __str__(self):
return self.user_name
views.py
input = request.POST['input']
name = Names.objects.get(user_name=input)
return render_to_response('product.html', {'name': name})
This will allow your user to search something, pull up the record searched, and place it in the template.
You can use that system for any number of variables.

Django Wagtail ajax contact form

I have a contact form that appears at the bottom of every page in the footer. I simply included it in my base.html at the bottom. Now i want to figure out a way to submit it. All the examples wagtail provides is under the assumption i have an entire page dedicated to it and hence submits to itself.
This cannot work for me as its not a page.
I have written pseudo code of what I think it should look like .
def submitContact(request):
source_email = request.POST.get('email')
name = request.POST.get('name')
message = request.POST.get('message')
if (source_email is not None) and (name is not None) and (message is not None):
body = "sample"
send_mail(
name,
message,
source_email,
['test#foobar'],
fail_silently=False,
)
Then my form would be something like this
<form class="form-group" role="form" method="post" action="/submitContact">
......
</form>
Ideally if someone could point to Wagtail resources that show how to create endpoints in models that do not inherit from the Page model and are not snippets that maintain "request" content that would be useful. Ideally what I would prefer is to log this data into contact "table" then send the email after.
What should I add to my urls.py to reroute the request with the correct context for the function to retrieve the required variables and thus send the email
Additional info
I wrapped a snippet around the footer to provide some context to it using templatetags, just putting this out there incase it adds value
See below.
#register.inclusion_tag('home/menus/footer.html', takes_context=True)
def footers(context):
return {
'footers': Footers.objects.first(),
'request': context['request'],
}
You should use {% url %} template tag.
urls.py :
from django.conf.urls import url
from yourapp.views import submitContact
urlpatterns = [
url(r'^contact/$', submitContact, name='contact'),
]
Template :
<form class="form-group" role="form" method="post" action="{% url 'contact' %}">
......
</form>
Another improvement is to use Django Form.
Note : prefer lower_case_with_underscores naming style for functions. Use CamelCase for classes. See PEP8 for more information.
Instead of trying to build it yourself, why not take a look at the already existing Form Builder of Wagtail?
It enables you to create a FormPage on which you can display a custom form and even E-mail the results.
Check out the documentation here.

Preferred way to POST with params from a listing template in Django

I was looking for some input on the preferred way of making a post request from a list template in Django. The way I'm currently using doesn't quite seem right to me, even though it works.
Let's say I have a table of data from my model, SomeModel, which I'm outputting in a Django GCBV ListView.
class SomeModelList(ListView):
model = SomeModel
In my template I'm iterating over the list of models and outputting each row in a table with some of the data, and I want two buttons which make a POST to perform some operation on the current row's object.
I can write an entire form for each operation manually. Something like:
{% for object in object_list %}
{{ object.name }}</br>
<form method="POST" action="{{ url 'do_something' {{ object.pk }}"><input type="button" value="Do Something"/></form></br>
<form method="POST" action="{{ url 'do_something_else' {{ object.pk }}"><input type="button" value="Do Something Else"/></form></br>
{% endfor %}
It doesn't seem correct to be writing out these form tags like this.
Is this really the best way? Maybe I should have a single giant form around the whole list and use some properties of the button? Maybe I should be doing something with Django forms? Maybe something else entirely?
Thanks!