I have an pre-built HTML form and I need to reuse it with Django form class (django.forms), So how do I incorporate my HTML form with Django form class. for example
HTML:
<li id="foli11" class="">
<label class="desc" id="title11" for="Field11">
Username
<span id="req_0" class="req">*</span>
</label>
<div class="col">
<input id="Field11" name="Field11" type="text" class="field text medium" value="" maxlength="255" tabindex="11" />
</div>
</li>
How do I map this HTML in to Django form class, I know that it can be done by modifying Django form fields according to this HTML. But I guess it's a time consuming approach,so I would like to know that is there any easy and time saving solutions for this issue.
Thanks.
Extend the django forms.Form class and write to it your own form.as_my_ul similar to form.as_p:
Here is the implementation of as_p: http://code.djangoproject.com/browser/django/trunk/django/forms/forms.py#L227
def as_p(self):
"Returns this form rendered as HTML <p>s."
return self._html_output(
normal_row = u'<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
error_row = u'%s',
row_ender = '</p>',
help_text_html = u' %s',
errors_on_separate_row = True)
Related
I am newbie in Django and I would appreciate if someone can help me about this problem.
I have a database in backend with 100 rows of users information.
Name, surname, phone number.
The database is visible on Home page template and if you choose one of this names you can donate something to this person.
When you click on submit button will lead you to new ajax window where you input your data and then submit.
Then I got your message on email.
My questions is how to do at the same time to confirm (submit) and delete row from database (person from database) and then to refresh page ?
Meaning, when you submit form then function should delete person from Home page at once and have to refresh page so you can see another person ?
Here is the code.
I would appreciate any help.
Thanks to all.
views.py
def about(request):
context = {
'num_toys': '1',
}
return render(request, 'about.html') # , context=context
def couses(request):
db_queryset = Children.objects.all()
context = {'child': db_queryset}
return render(request, 'couses.html', context=context)
class ChildrenListView(ListView):
model = Children
context_object_name = 'child'
class ChildrenCreateView(CreateView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_changelist')
class ChildrenUpdateView(UpdateView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_changelist')
class ChildrenDetailView(DetailView):
model = Children
form_class = ChildrenForm
success_url = reverse_lazy('children_detail')
children_detail.html
<!-- Start contact form area -->
<div class="couses">
<section class="contact-form-area pb-60 pt-90">
<div class="couses">
<div class="container">
<div class="row">
<!-- Start section title -->
<div class="col-sm-12">
<div class="section-title text-center">
<h2>Donate <span> {{ children.toy }} </span> to <span>{{ children.name }}</span> who is <span>{{children.date }} old</span></h2>
<img src="static/children/img/title-bottom.png" alt="">
</div>
</div>
<!-- End section title -->
<div class="col-sm-12">
<div class="contact-form">
<form id="contact-form" method="POST" action="mail.php">
<div class="form-fields">
<label for="name">Name</label>
<input id="name" name="name" type="text" placeholder="Your Name" required>
</div>
<div class="form-fields">
<label for="email">Email</label>
<input id="email" name="email" type="text" placeholder="Your Email" required>
</div>
<div class="form-fields last">
<label for="phone">Phone</label>
<input id="phone" name="phone" type="text" placeholder="Your Phone" required>
</div>
<div class="message-fields">
<label for="mess">Message</label>
<textarea name="mess" id="mess" cols="30" rows="10" placeholder="Message"></textarea>
</div>
<div class="form-button">
<button type="submit">Send your message</button>
<button type="reset">Reset</button>
</div>
</form>
<p class="form-messege"></p>
</div>
</div>
</div>
</div>
</div>
</section>
sorry if I'm wrong but I understand that you want to do two actions.
In your code I can see that you have forms and class-based Views. Maybe you need to override the function form_valid to do the operations you need when you submit.
Check this website http://ccbv.co.uk there you will find the details of the views.
On click of submit hit the url & process your message on email part first and then you can delete the person from database by filtering out object of that particular person with whatever primary key you have for that table by writing a query in your view. and then render the remaining data of that table to your template on which you are Redirecting from your on submit click.
From above conversation what i understood that you don't want delete that person from database boolean field would be great option rather you want to save the message that has been sent from email by this way you can do both at the same time. you have the message saved in your database and from empty message data can render those user on template.
how to retrieve a form search parameters in a django generic listView. My url is:
url(r'postsearch$', views.PostsList.as_view(), name='postsearch'),
My generic listview is:
class PostsList(generic.ListView):
model = Post
template_name = 'posts/post_list.html'
def get_queryset(self):
localisation = #how to get location
discipline = #how to get discipline
return Post.objects.filter(.......)
and my form is:
<form class="form-inline text-center" action="{% url 'posts:postsearch' %}" id="form-searchLessons" method="get">
<div class="form-group">
<input type="text" class="form-control" id="typeCours" list="matieres" placeholder="Matieres: e.g. Math, Physique,.." name="discipline">
<datalist id="matieres">
<option value="value1">
<option value="value2">
</datalist>
</div>
<div class="form-group">
<input type="text" class="form-control" id="Localisation" placeholder="Lieu: Bousaada, Douaouda,.."
name="localisation" onFocus="geolocate()">
</div>
<button type="submit" class="btn btn-default" id="btn-getLessons">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span> Trouver !
</button>
</form>
I want to get the Posts by applying a filter according to the lacalisation and matieres introduced in the search fields (in the form)
You can add the search terms to your url regular expression.
url(r'postsearch/(?P<localisation>\w+)/(?P<descipline>\w+)/$', views.PostsList.as_view(), name='postsearch'),
(Note, mind the trailing slash)
In your get_queryset method you can use those given url parameters
def get_queryset(self):
localisation = self.kwargs['localisation'] or None
discipline = self.kwargs['discipline'] or None
filters = {}
if localisation:
filters.update(localisation: localisation)
if discipline:
filters.update(discipline: discipline)
return Post.objects.filter(**filters)
Eventually you should relocate getting the parameters outside your get_queryset, but that is up to you.
I'm not sure about the security risks doing it this way. Anyone having more information about the security risks during this operation, please share.
I build a library that can help you to solve this problem, you just have to put in the searchable_fields the attributes you want to filter and it will take care of the rest.
https://github.com/SchroterQuentin/django-search-listview
I'm finding it overly difficult to customize ClearableFileInput as set as the default widget in a modelForm that includes an ImageField in the model.
Particularly I don't want the Delete Checkbox that is part of the widget. I've tried customizing/overriding the rendering in a number of ways to get rid of the checkbox including setting the widget to FileInput and overriding the render method where subclassing the widget in a widgets.py file.
The simplest I can explain the problem is like this:
forms.py
class SpecImageForm(ModelForm):
orig_image = forms.ImageField(required=False, widget=forms.FileInput)
class Meta:
model = SpecImage
fields = ['orig_image',]
# The intention is to have more than one SpecImageForm once this is working but for now the
# max_num is set to 1
SpecImageFormSet = inlineformset_factory(Spec, SpecImage, form=SpecImageForm, extra=1, max_num=1)
Despite explicitly setting the FileInput against the widget it renders like this in my template - still including the checkbox which I don't think should be present using FileInput.
<fieldset>
<legend>Images</legend>
<input id="id_specimage_set-TOTAL_FORMS" name="specimage_set-TOTAL_FORMS" type="hidden" value="1" />
<input id="id_specimage_set-INITIAL_FORMS" name="specimage_set-INITIAL_FORMS" type="hidden" value="0" />
<input id="id_specimage_set-MAX_NUM_FORMS" name="specimage_set-MAX_NUM_FORMS" type="hidden" value="1" />
<ul>
<li>
<label for="id_specimage_set-0-orig_image">Orig image:</label>
<input id="id_specimage_set-0-orig_image" name="specimage_set-0-orig_image" type="file" />
</li>
<li>
<label for="id_specimage_set-0-DELETE">Delete:</label>
<input id="id_specimage_set-0-DELETE" name="specimage_set-0-DELETE" type="checkbox" />
<input id="id_specimage_set-0-id" name="specimage_set-0-id" type="hidden" />
<input id="id_specimage_set-0-car" name="specimage_set-0-car" type="hidden" />
</li>
</ul>
</fieldset>
The relevant part of the template is this:
<fieldset>
<legend>Images</legend>
{{ image_form.management_form }}
{% for form in image_form %}
<ul>
{{ form.as_ul }}
</ul>
{% endfor %}
</fieldset>
The only thing slightly different that I'm doing is using an inlineformset_factory.
I've also tried to override the rendering of a widget using widgets.py but similarly seem unable to rid myself of the defualt settings - principally based on this thread.
Any ideas or solution to rid myself of the checkbox would be gratefully received!
I think this is to do with the inlineformset_factory applying a default can_delete parameter set to true, which was present regardless of how I'd prepared the form to use with it. Simply passing can_delete=False got rid of the Delete checkbox.
SpecImageFormSet = inlineformset_factory(Spec, SpecImage, form=SpecImageForm, extra=1, max_num=1, can_delete=False)
In addition when I rendered the form on it's own (without using inlineformset_factory) there was no sign of a 'Delete checkbox'. Then I found this SO post that explained why.
Getting there.
I have a form that is supposed to create a new 'Quote' record in Django. A 'Quote' requires a BookID for a foreign key.
This is my form
<form method="POST" action="{% url 'quotes:createQuote' %}">
{% csrf_token %}
<section>
<label for="q_text">Quote Text</label>
<input type="text" name="text" id="q_text" placeholder="Enter a Quote" style="padding-left:3px"> <br>
<label for="q_book">Book ID</label>
<input type="text" name="bookID" id="q_book" placeholder="Enter Book ID" style="padding-left:3px"> <br>
<label for="q_disp">Display Quote Now?</label>
<input type="radio" name="display" id="q_disp" value="True"> True
<input type="radio" name="display" value ="False">False <br>
<button value="submit">Submit</button>
</section>
</form>
And this is the method that it is targeting
def createQuote(request):
#b = get_object_or_404(Book, pk=request.bookID)
return HttpResponseRedirect(reverse('quotes:index'))
Somewhere in that request argument I assume there is some sort of field that contains the bookID the user will pass in on the form. How do I get at that information?
Bonus points for anyone who can tell me some way I can visualise data like I might with console.log(some.collection) in Javascript
if request.method == "POST":
book_id = request.POST['book_id']
Assuming you're sure it's in there. Otherwise you'll need to verify/provide a default value like you would for a normal python dictionary.
As for visualising the data, do you mean printing it to the console? In which case if you're running the django runserver you can just do print some_data. If you want it formatted a little nicer, you can use pretty print:
import pprint
pp = pprint.PrettyPrinter()
pp.pprint(some_data)
This is standard checkbox from model forms:
In my HTML I have: {{form}}
In website source:
<div class="id_accept-control-group control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="accept" id="id_accept" /> <span>Accept</span>
</label>
</div>
</div>
How to add custom attribute: disabled="disabled" checked="checked" (to input)?
Check out this question to point you in the right direction Django: How do I add arbitrary html attributes to input fields on a form?
Also take a look at the model forms django doc https://docs.djangoproject.com/en/dev/topics/forms/modelforms/