So my views look like this:
class PostCreateView(CreateView):
model = Post
fields = ['title','content','image', 'status']
The image field currently looks like this:
Is there a way to have like a button to clear the image from the field? The only way to remove the image is to do it from django admin page.
your html file add a button with an id:
<button id="clear">Clear image </button>
Then in your html, add
{% load static %}
<script>
document.getElementById("clear").addEventListener("click", function () {
document.getElementById("image").value = "";
}, false);
</script>
Note that you need to use your chrome developor tool to find out what is the id of your file input field, in the above example, I used "image", but it most likely be different. You need to change get.ElementById("image") with the id of your file input field.
Related
I have an option list in html.
<select>
<option value="Please select" disabled selected>- Please Select -</option>
<option value="Iphone">Iphone</option>
<option value="Samsung">Samsung</option>
</select>
When the user select one of the option, the particular table with data will appear.
In views.py:
dev_model = Device.objects.filter(name='name').all()
I want to get the data from html, then filter the option with my database in field 'name'.
If they are same, the data will be retrieved and display in html.
You may want to use a Django Form to accomplish this.
In a file called forms.py (in the same directory as your models.py) you will have something like:
from django import forms
class MyForm(forms.Form):
NAME_CHOICES = (('Iphone', 'Iphone'),
'Samsung', 'Samsung'))
name = forms.ChoiceField(choices=NAME_CHOICES)
Then, in your view, pass the form through context and render it in your django template. I would suggest ModelForm instead of Form a lot of the time, but I don't have any specifics about your application/use case.
When the form is POSTed back to your view, you should be able to get the data by using
form=MyForm(request.POST)
if form.is_valid():
name = form['name'].value()
The link to the documentation should be a good point to get you started
To display the data as soon as the user selects the correct field, you can do this with one of two approaches:
Use ajax if you want the filtering to happen on the server side
Use DataTables to pass all the data to the browser and have the user filter their display at their convenience.
You question is too broad to provide a specific answer while lacking the necessary details behind your attempt I have provided a starting point for your forms and links to the necessary documentation. I hope this helps
You can keep mapping of device to a particular value like this:-
DEVICE_TO_MAPPING = {
0:'Samsung',
1:'Iphone',
}
And then use this mapping to send in context as variable like "devicemapping" to render in html in template, you can do it like.
<form name="device-form" method='POST' action='.'>
<select>
<option value="{{device_value}}" disabled selected>- Please Select -</option>
{% for device_value, device_name in devicemapping.items %}
<option name='{{device_value' value="{{device_value}}">{{ device_name }}</option>
{% endfor %}
</select>
</form>
In your views.py you can filter the data using Mapping.
device_value = request.POST.get('device_value')
device_name = DEVICE_TO_MAPPING.get(device_value)
dev_model = Device.objects.filter(name=device_name)
I have a form which allows you to upload an image, but I want to know if it is possible to customise the markup that Django generates.
In the model it is created as an ImageField:
logo = models.ImageField(blank=True, null=True)
In the template I am creating an 'upload' form field using
{{ form.logo }}
This is the markup that gets generated:
Currently: dog.jpg
<input id="logo-clear_id" name="logo-clear" type="checkbox">
<label for="logo-clear_id">Clear</label>
<br>Change: <input id="id_logo" name="logo" type="file">
I want to know if I can change that markup by drilling down further, so that I can for example nest the checkbox to clear the image within its label. I also would like to use my own markup to separate the option to clear the form field from the option to upload a new one. However, I can't find any documentation on how to do this. I've tried outputting
{{ logo.logo-clear }}
directly but this throws an error.
The solution was to create a custom version of the widget being used in my forms.py: https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/#ClearableFileInput
from django.forms.widgets import ClearableFileInput
class CustomImageFieldWidget(ClearableFileInput):
template_with_clear = '<label for="%(clear_checkbox_id)s">%(clear)s %(clear_checkbox_label)s</label>'
class OrganisationProfileForm(OrganisationCreateForm):
class Meta(OrganisationCreateForm.Meta):
widgets = {
'logo': CustomImageFieldWidget,
}
I have something like the following:
class Destination(models.Model):
name = models.CharField
picture = models.ImageField
def __unicode__(self):
return u"%s" % self.name
class Vacation(models.Model):
destination = models.ForeignKey(Destination)
When creating the model in my Django Admin interface, I'd like my Destinations to be displayed as radio buttons with the Destination name and Destination picture.
I'm using a custom add_form template so displaying radio buttons with destination name is no problem, but including the picture is difficult.
I would like to leave __unicode__(self) as-is, I only need the picture returned with the object in this admin view. Also I don't want to inline the object.
Any advice on how to do this (including how to incorporate it into the template) would be great!
EDIT: This SO post comes very close to what I need, but I would like to access the individual choice data instead of parsing it from a modified label.
This is not an admin-specific answer, but I think it should work in admin if you can use a custom template for the form.
You could make a modified widget (probably as a subclass of an existing Django widget), that send extra fields from the model to a custom widget template.
You could also render the form manually in the template where it's displayed, and make an inclusion tag that fetches any extra information using the id of your destination object, which is passed as the value of the option.
For example:
your_template.html
{% load destinations %}
{% for opt in form.destination %}
{{ opt.tag }}
{% destination opt.data.value %}
{% endfor %}
destinations.py (in your_app/templatetags)
from django import template
from your_app.models import Destination
register = template.Library()
#register.inclusion_tag('your_app/destination-option.html')
def destination(id):
destination=Destination.objects.filter(id=int(id)).first()
return {'destination':destination}
destination-option.html
<!-- any formatting you prefer -->
{{destination.title}}
<img src="{{destination.picture.image_url}}">
I have the following form:
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
widgets = {
'tipo' : forms.RadioSelect(),
}
But I want to use images as the values of my radio buttons, the image will vary according to the option, like this:
<input type="radio" id="id_tipo_0" value="UP" name="tipo" /><img src="/images/thumb_up.gif"/>
<input type="radio" id="id_tipo_1" value="DOWN" name="tipo" /><img src="/images/thumb_DOWN.gif"/>
I have no clues on how to achieve this.
There is a nice solution for this issue!
A ModelChoiceField has the method label_from_instance(self, obj). This method is called for every option in the ModelChoiceField.
You can overwrite ModelChoiceField.label_from_instance with:
def label_from_instance(obj):
"""
Shows an image with the label
"""
image = conditional_escape(obj.thumbnail_image.url)
title = conditional_escape(obj.title)
label = """<img src="%s" />%s""" % (image, title)
return mark_safe(label)
Note: you need to use mark_safe, otherwise the renderer will escape the img tag. Do apply the conditional_escape to the user input values (title and url).
If you want to use a regular ChoiceField you can just add HTML to the choices parameter and add mark_safe.
You can override RadioSelect (and RadioFieldRenderer) class.
OR! you can use jquery ( or something similar) to insert your img dynamically.
$(document).ready(function(){
$("#id_tipo_0").after('<img src="/images/thumb_up.gif"/>')
$("#id_tipo_1").after('<img src="/images/thumb_down.gif"/>')
});
If you want to use Django form rendering function, you'll have to use javascript to modifiy the DOM, and this will be a mess because the names of the option are rendered just after the input tag, not enclosed in any tag...
If your form does not have any other tags, go ahead, just write your input just as in your example, carefully using the Django names and values for the radio input, add a submit button, a CSRF token and that's all, you'll be able to validate your form in the view like if it was rendered via {{form.as_p}}
I have typical profile/account settings form. So as expected you would be having a "name" field and a "domain" field(which will be used as like a website url: maddy.mywebsite.com). This domain field needs to be editable only once. Once set to one thing, will not be made editable later(since this is like a site url).
At the model level, I am comparing created_on and modified_on of that object(userprofile) and validating "domain" value saving. But at the form level, how do I customize the rendering of that field alone based on the condition I have taken ?
Note 1: I don't want to move the "domain" field to the signup page.
Note 2: I am trying to use normal forms(django.forms) and not a ModelForm.
You may try using two htmls, One for create profile and one for editing profile. Render the complete form in create profile and for editing profile if you use same django you may disable the #id_name and #id_domain filed by using either css or javascript. An implementation using js:
<script type="text/javascript">
var domain = document.getElementById("id_domain");
var name = document.getElementById("id_name");
domain.value = "{{ domain }}";
name.value = "{{ name }}";
domain.readOnly = true;
</script>
This looks tricky, you can read some of the following for some ideas:
In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
http://lazypython.blogspot.com/2008/12/building-read-only-field-in-django.html
None of those are particularly simple though, so I'd suggest (as did #dcrodjer):
Creating two forms, one for creating, one for editing. On the editing form, remove the Domain field so it's not required/won't be saved:
# forms.py
class AddForm(ModelForm):
class Meta:
model = UserProfile
fields = ('name','domain',)
class EditForm(ModelForm):
class Meta:
model = UserProfile
fields = ('name',)
In your view, creating the appropriate form, and in your template, rendering different HTML depending on which form you've been given:
{% if form.domain %}
{{form.domain.label_tag}}: {{form.domain}} {{form.domain.errors}}
{% else %}
Domain: <input type="text" disabled="disabled" value="{{userprofile.domain}}"/>
{% endif %}