Django - render custom form fields in custom HTML template - django

I'm kinda new into Django and I'm facing some troubles using some custom forms.
I'm using a purchased Bootstrap theme which apart from the standard classes that comes with Bootstrap has its own classes and of course, some custom CSS. I find it very difficult how Django deals with custom forms and all the sources/information/examples found online makes no sense to me.
So, my elements from my HTML template use the following classes:
<form action="#" method="post" class="card shadow-soft border p-4 mb-4">
<div class="form-group">
<label for="video">Video url</label>
<input type="text" value="https://video.com/" class="form-control shadow-soft" id="video"
placeholder="Video url" required>
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
In forms.py I have added the following:
class UpdateURLForm(forms.Form):
VideoURL = forms.CharField(
widget=forms.TextInput(
attrs={
'class': 'form-group'
}
)
)
class Meta:
model = Listing
fields = ('VideoURL')
In views.py I have imported the form and added to the view:
from .forms import UpdateURLForm
def updateInfo(request):
if request.method == 'POST':
form = UpdateURLForm(request.POST)
if form.is_valid():
pass
else:
form = UpdateURLForm()
return render(request, 'myapp/editinfo.html', {'form': form})
Now, in my HTML template, I want to render the form field which has to inherit the custom CSS styles but somehow, I'm missing something because the field is being displayed as I was using Crispy forms.
<form action="#" method='post' class="card shadow-soft border p-4 mb-4">{% csrf_token %}
<div class="form-group">
<label for="video">Video URL</label>
<input type="text" value="{{form}}" class="form-control shadow-soft" id="video"
placeholder="{{object.VideoURL}}" required> # the placeholder comes from my class based view
</div>
<div class="row">
<div class="col">
<button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right"
type="submit">Update</button>
</div>
</div>
</form>
What should I do if I need more fields from a custom form to be rendered using my custom CSS classes?
Any suggestion would be much appreciated. Thanks!

You can use Widget Tweaks to achieve what you want. This will allow you to use your own styles:
You can get Django Widget Tweaks by using pip:
$ pip install django-widget-tweaks
To enable widget_tweaks in your project you need to add it to INSTALLED_APPS in your projects settings.py file:
INSTALLED_APPS = [
...
'widget_tweaks',
...
]
Considering your code sample, when you render the form field in the HTML template, do something like:
first you need to load in the top of the HTML file (similar how you load static):
{% load widget_tweaks %}
Then you can add your custom class like this:
<div class="form-group">
<label for="video">Video URL</label>
{{form.VideoURL|add_class:"form-control shadow-soft"}}
</div>

Related

How do i push uploaded image file in my template input for update in django 2.0

I want to open a particular record in html template in update mode for which i want every value which was inserted before for this record be in those field, i got every required value in field for text field but in file field which contains image ,it shows no file selected where as i want the image file name(url) in there.
I havent used django form rather i used normal bootstrap forms.
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
image = models.ImageField(upload_to='images/') # i m facing problem for this field
icon = models.ImageField(upload_to='images/') # i m facing problem for this field as well
url = models.TextField()
votes_total = models.IntegerField(default=1)
hunter = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def short_pub_date(self):
return self.pub_date.strftime('%b %e %Y')
#
views.py
def myproducts_update(request,product_id):
product = get_object_or_404(Product,pk=product_id)
print(product.image) # this prints the name of the file (images/37003.jpeg)
return render(request,'products/myproducts_update.html',{'product':product})
templates(myproducts_update.html)
{% extends 'base.html' %}
{% block content %}
{% if error %}
{{error}}
{% endif %}
<br>
<br>
<div class="container">
<div class="jumbotron">
<h2>Update Product</h2>
<form action="{% url 'create' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="email" value={{product.title}} placeholder="please enter title" name="title" required>
</div>
<div class="form-group">
<label for="body">Description:</label>
<input type="text" class="form-control" id="body" value={{product.body}} placeholder="Description" name="body" required>
</div>
<div class="form-group">
<label for="url">URL:</label>
<input type="text" class="form-control" id="url" value={{product.url}} placeholder="please enter url" name="url" required>
</div>
<br>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="icon">
<strong>Icon:</strong></label>
<input type="file" id="icon" name="icon" value={{product.icon}} required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="url">
<strong>Image:</strong></label>
<input type="file" id="image" placeholder="please enter url" name="image" value={{product.image}} required>
</div>
</div>
</div>
<br>
<input type="submit" value="Update Product" class="btn btn-primary">
</form>
</div>
</div>
{% endblock %}
Link which contains image of form where i have problem
I am having trouble in getting the url of the image in the templates,guys please help me
Thanks in advance!
Try something like this in your <form>:
<div class="margintop50px">
<img {% if object.image %} src="{{ object.image.url }}" {% else %} alt="You have no image." {% endif %}>
<input type="file" name="image" accept="image/*">
</div>
UPDATE:
I just checked your views.py. Sorry for not noticing sooner, but your myproducts_update() function never .save()'s anything, so nothing will show because of that. Try changing that function to something like the following. It assumes the product has already been created somewhere else because I don't know of any other views you made to get this far (maybe you originally added all pics/text from the admin panel? And personally, I would change the names of your function(s) because your form goes to 'create', but the function you showed states that this is about updating it, and that's generally not a clear path to follow when designing it because createing something is different from 'update'ing it. So if the following still doesn't work, I'll need to see your 'create' view, and the urlpatterns for all these functions).
Either way, there are better ways to improve the following (such as what I talked about above), but this is all I can give you without knowing that stuff:
views.py
def myproducts_update(request,product_id):
product = get_object_or_404(Product,pk=product_id)
if request.method == 'POST':
product.body = request.POST.get('body', False)
product.title = request.POST.get('title', False)
product.url = request.POST.get('url', False)
product.icon = request.FILES.get('icon', False)
product.image = request.FILES.get('image', False)
product.save()
return render(request,'products/myproducts_update.html',{'product':product})
And then use the example template above to get it to show on that page.

Using Bootstrap Model with Django classed based views to implement login function

I have created loginview using class-based view concept as following:
class LoginView(NextUrlMixin,RequestformattachMixin,FormView):
form_class = login_page
template_name = 'login.html'
success_url = '/'
def form_valid(self, form):
next_url=self.get_next_url()
return redirect(next_url)
def form_invalid(self, form):
return super().form_invalid(form)
forms.py:
class login_page(forms.Form):
Email = forms.EmailField(required=True,widget=forms.EmailInput(
attrs={"class": "form-control", "placeholder": "Email
address", "id": "exampleInputEmail2"}))
Password = forms.CharField(required=True,widget=forms.PasswordInput(attrs={"class": "form-control",'id':'exampleInputPassword2',
"placeholder": "Password"}))
I have modified on my login.html page to use bootstrap modal as the following:
{% block content %}
<div id="loginModal" class="modal fade">
<div class="loginModal-content">
<div class="loginModal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Login</h4> </div><div class="loginModal-body">
<div class="row">
<div class="col-md-12"> via <div class="social-buttons">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-twitter"></i> Twitter
</div>or
<form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Email address</label>
{# <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>#}
{# {{ form.Email }}#}
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Password</label>
{# <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password" required>#}
{# {{ form.Password }}#}
<div class="help-block text-right">
Forgot the password ?
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> keep me logged-in
</label>
{{ form }}
</div>
</form>
</div>
<div class="bottom text-center"> New here ?
<b>Join Us</b> </div></div></div>
<div class="loginModal-footer">
</div>
</div>
</div>
{% endblock %}
As I am a newbie in Django, could you please help me how to use the bootstrap modal with my Django CBV
or even how to start as when I started using the Modal it is failed to appear, should I use ajax or what are other technologies should I use. please help from where could i start
Ok, the best way to render fields in django is django-widget-tweaks, this very simple and render all the error and fields with adding classes to that field.
Follow the installation of it - https://github.com/jazzband/django-widget-tweaks
here is simple and full guide of using django-widget-tweaks
I always suggest to use it, hope it will help you.
The plugin I wrote could be your starting point django-bootstrap-modal-forms. If you check the examples project you will also find a fully functional Login and Signup form in modals. You will be able to bind any form to the modal and all of the validation stuff will work out of the box.
You will create a trigger element opening the modal
Your selected form will be appended to the opened modal
On submit the form will be POSTed via AJAX request to form's URL
Unsuccessful POST request will return errors, which will be shown under form fields in modal
Successful POST request will redirects to selected success URL

Custom Django forms within template and hidden inputs

Very, very quick question. I'm rendering my own custom forms within my html template...how would I go about submitting the hidden input when the user submits that form?
template.html
<form class="contact-form" name="contact-form" method="post" action=".">
{% csrf_token %}
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="four">Your Text</label>
<textarea class="form-control" type="text" name="{{ comment_form.content.name }}" {% if comment_form.content.value %}value="{{ comment_form.content.value }}"{% endif %} placeholder="" required="required" id="four"></textarea>
</div>
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary pull-right">Submit Comment</button>
</div>
</form>
form.py
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
content_type = forms.CharField(widget=forms.HiddenInput)
object_id = forms.IntegerField(widget=forms.HiddenInput)
#parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Comment
fields = ('content',)
You can add this part to you forms.py file (in CommentForm class) :
hidden_field=forms.CharField(widget=forms.HiddenInput())
I hope it will work.let me know

Rendering fields manually and custom css class

I am trying to manually render the form fields.
I would like to add a bootstrap and custom css class to rendered html.
How can I do this ?
forms.py
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = ['name','postal_code']
widgets = {
'postal_code': forms.RadioSelect(),
}
file.html
<form action="." method="post" class="order-form">
<div class="fieldWrapper">
{{ form.postal_code }}
</div>
<p><input type="submit" value="Send"></p>
{% csrf_token %}
</form>
{% endblock %}
rendered html
<div class="fieldWrapper">
<ul id="id_postal_code">
<li><label for="id_postal_code_0"><input type="radio" name="postal_code" value="Yes" required id="id_postal_code_0" />Yes</label></li>
<li><label for="id_postal_code_1"><input type="radio" name="postal_code" value="No" required id="id_postal_code_1" />No</label></li>
</ul>
</div>
How to solve a problem ?
I would appreciate your help.
You can add css classes to form fields in the following way:
'postal_code': forms.RadioSelect(attrs={"class": "form-control"}),
Another option is to not render the form this way at all, and just write your own html.

how to render a djangoform into bootstrap modal window

I am strating to learn Django and I want to display some forms in bootstrap modal view.
I have a template with a HTML table, this table have a column with a drop down button with several options.
the table is rendered with django-tables2 and the forms are rendered with django-crispy-forms
My form definition for the modal form:
class RecepcionForm(forms.ModelForm):
fecha_recepcion = forms.DateField(widget=DateInput())
def __init__(self,*args,**kwargs):
super(RecepcionForm,self).__init__(*args,**kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Field('id_proveedor',
'anio',
'mes',
'usuario',
readonly = True
),
Fieldset('',
'fecha_recepcion',
'num_archivos',
Submit('save','Grabar'),
HTML('<a class="btn btn-danger" href={% url "monitor" %}>Cancelar</a>')
)
)
class Meta:
model = DetalleRecepcion
My view for the modal form:
#login_required(login_url='/login/')
def RecepModalView(request):
idp = request.GET.get('i')
anio = request.GET.get('a')
mes = request.GET.get('m')
if request.method == 'POST':
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
form = RecepcionForm(request.POST, instance=r)
if form.is_valid():
form.save()
return HttpResponseRedirect('/monitor/')
else:
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
r.usuario = request.user
form = RecepcionForm(instance=r)
return render_to_response('recepmodal.html',
{'form':form},
context_instance=RequestContext(request))
My template for the modal form
{% load crispy_forms_tags %}
<div class="modal fade" id="recmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Register </h4>
</div>
<div class="modal-body">
<form action="" method=post">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
{% crispy form %}
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
I don't know how to open and pass arguments to the modal form.
I try using the django tag include
Example snippet:
<body>
<table>
.
.
.
</table>
{% include 'recmodal.html' %}
</body>
but I get this error
Exception Value: Failed lookup for key [form] in
In simple word how can I pass values and open a bootstrap modal form in django using django-crispy-forms.
Any advice
Thansk in advance
I know it's too late to answer, but I render my forms in a modal using this into a "modal-body" tag:
<form method="post">
{% csrf_token %}
{% form.as_p %}
</form>
I hope this work for all people like me that we came here finding an answer.
Regards.