I want to add filer_image field to my Gift class instance object. It works as apphook in django-cms. The main problem is that after making migrations and open the view where the form is I don't have loaded js.
I already added all tags:
{% load staticfiles i18n cms_tags sekizai_tags menu_tags thumbnail filer_tags filer_image_tags %}
The model is:
class Gift(models.Model):
filer_image = FilerImageField(related_name="book_covers")
The form:
class GiftForm(ModelForm):
class Meta:
model = Gift
fields = '__all__'
widgets = {
'name': forms.TextInput(attrs={'class': 'basic-input full-width'}),
}
The rendered output:
The thumbnail and input view
Please tell me what am I doing wrong with these. It seems to me like some js files are not loaded. After click it opens FileImageFiler gallery, but I also cannot select any image.
Ok, i find the soliton. Basically I added {{ form.media }} after {{ csrf_token } and I have extended the form class with:
class Media:
extend = False
css = {
'all': [
'filer/css/admin_filer.css',
]
}
js = (
'admin/js/core.js',
'admin/js/vendor/jquery/jquery.js',
'admin/js/jquery.init.js',
'admin/js/admin/RelatedObjectLookups.js',
'admin/js/actions.js',
'admin/js/admin/urlify.js',
'admin/js/prepopulate.js',
'filer/js/libs/dropzone.min.js',
'filer/js/addons/dropzone.init.js',
'filer/js/addons/popup_handling.js',
'filer/js/addons/widget.js',
'admin/js/related-widget-wrapper.js',
)
That is all!
Related
based on multiple choice field i want to show result in template but I have no idea how to do as you can see in this model i give lunch choice to students base on lunch choice i want to show result but it is not working for ex if he select sandwich the result after submit will you sandwich will be ready and same for others
from multiselectfield import MultiSelectField
class student(models.Model):
lunch_choice = [
('Sandwich', 'Sandwich'),
('Salad', 'Salad'),
('omlete', 'omlete'),
]
name = models.CharField(max_length=70, blank=False)
classs = models.CharField(max_length70, blank=True)
lunch = MultiSelectField(choices=lunch_choice, blank=True)
def __str__(self):
return self.name
i tried in my HTML and it didn't work
{% if student.classs %}
{% if student.lunch == 'Sandwich' %}
<p> your sandwich will be ready</p>
{% endif %}
{%endif%}
and in form.py using widget
widgets = {
'lunch':forms.CheckboxSelectMultiple(attrs={'id':'lunch'}),
}
my views.py
def preview(request):
student = student.objects.all()
return render(request, 'preview.html',{'student':student})
OP can create a model for lunches (it would enable to create new lunches, edit and delete). Then, in the Student model create a lunch with a ManyToManyField, like
lunch = models.ManyToManyField(Lunch, blank=True)
Note the usage of blank=True to not require the field in the forms.
Then, when one generates a form based on that model, it'll create an experience just like the one in Django Admin where one can select multiple ones.
One can then show it to the user in a template.
If one doesn't like the experience of the form and want to make it more user friendly, there are some articles out there explaining that
Django Forms for Many-to-Many Fields
How To Add Tags To Your Blog (A Django ManyToManyField Example)
acc to me there is no such way by which u can show the result base on selected option because i also tried to use that and look for answers on internet but didn't find anything and creator of that repo is also not responding although I would recommend you to use models many to many field It will allow user to select more than one option like multiselectfield like this
first, create models
class Lunch(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
then add this in student models
lunch = models.ManyToManyField(Lunch, blank=True, related_name="lunch")
then add your option in lunch model
and it in your template to show result base on selected option
{% if student.classs %}
{% for Lunch in student.lunch.all %}
{% if Lunch.title == 'Sandwich' %}
<p> your sandwich will be ready</p>
{% endif %}
{% endfor %}
{%endif%}
it will work
This happens because the string is being compared to type: type(aaa[0].lunch) <class 'multiselectfield.db.fields.MSFList'>. Printed the data type 'type(aaa[0].lunch)' of the first value from the database in the view. Used stringformat:'s' to convert data to string in template. Here you can read about the conversion:
conversion
transformation type:
replace 'samplesite' with the name of your application.
urls.py
urlpatterns = [
path("Test/", Test, name = 'Test'),
]
views.py
def Test(request):
aaa = student.objects.all()
print('type(aaa[0].lunch)', type(aaa[0].lunch))
context = {'fff': aaa}
return render(request, 'samplesite/lunch.html', context)
lunch.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
{% for aa in fff %}
{% if aa.lunch|stringformat:'s' == 'Sandwich' %}
<p>{{aa.lunch}}</p>
<p>{{aa.name}}</p>
{% endif %}
{% endfor %}
</body>
</html>
settings in settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
django version 4.1
I have an HTML page with a link to redirect to another HTML template which has a form. I have used the class based view in rendering it. But it simply does not load.
My views.py look something like :
def startup(request):
return render(request, 'main/startup.html')
class AddStartup(CreateView):
model = Startup
template_name = 'startup_form.html'
fields = ['startup_name', 'startup_product', 'startup_date', 'startup_sector', 'startup_team_size',
'startup_desc', 'startup_team_condition', 'startup_team']
urls.py
# I have posted only the relevant code
url(r'startup/$', views.startup, name = 'startup'),
url(r'startup/add-startup/$', views.AddStartup.as_view(), name = 'add-startup'),
My HTML page which has a link to navigate to the field is below
{% extends "main/base.html" %}
{%block content%}
pass<br>
<a
href = "{%url "main:add-startup"%}" target="_parent" method = "post">
Add Startup
</a>
{%endblock%}
I am a bit confused in Class based views so that is why I choose to mix them. Help would be appriciated
I have a model like this:
class Assignment(models.Model):
content = models.FileField(upload_to='xxx')
other_val = models.CharField(...) # not important
And a form wrapping this model (ModelForm):
class AssignmentForm(ModelForm):
class Meta:
model = Assignment
fields = ['content', 'other_val']
My view looks like this (for simplicity I skip the request.POST/request.FILES. part):
#login_required(login_url='/login/')
def create_assignment(request):
form = AssignmentForm()
# render form
#login_required(login_url='/login/')
def update_assignment(request, assignment_id):
assignment = Assignment.objects.get(id=assignment_id)
form = AssignmentForm(instance=assignment)
Creating an assignment works just fine - It forces me to upload a file, which is what I want. But when I want to update the content of the assignment (the file), it first shows a link of a previously uploaded file (excellent!) then the upload button, like this:
Currently: AssignmentTask_grading_script/grading_script_firing.py
Change: [Choose File] no file chosen
But then I assume if I don't want to replace this file, I should simply click the submit button. Unfortunately, when I click the submit button, the form complains that I should upload a file. Is there a way to silent the complaint if a file is already in database?
As following the previous comments, maybe like this;
1. forms.py
class AssignmentForm(forms.ModelForm):
# as following #Rohan, to make it optional.
content = forms.FileField(required=False)
class Meta:
model = Assignment
fields = ['content', 'other_val']
2. yourtemplate.html
<form method="post" enctype="multipart/form-data" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<script>
{% if not form.content.value %}
$('#id_content').attr({'required': 'required'});
{% endif %}
</script>
The field of content is under required only if havn't value before...
I'm trying to use django-jfu to multiupload images, but I have a problem. I want to handle a foreign key dynamically (via url or something), but I can't think of anything.
I have the following models:
class Event(models.Model):
name = models.CharField(max_length=128)
class Picture(models.Model):
event = models.ForeignKey(Event)
image = models.ImageField(upload_to='media')
According to django-jfu, you have to specify a "upload" view to call from the template via template tag. This is my upload view:
#require_POST
def upload(request):
event = Event.objects.get(id=26)
file = upload_receive(request)
instance = Picture(image = file, event = event)
print instance
instance.save()
basename = os.path.basename(instance.image.path)
file_dict = {
'name' : basename,
'size' : file.size,
'url': settings.MEDIA_URL + basename,
'thumbnailUrl': settings.MEDIA_URL + basename,
'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
'deleteType': 'POST',
}
return UploadResponse(request, file_dict)
Right now, as a test, it only saves pictures to event with id=26, but how can I handle it dynamically? This is the view and template where I'm calling the template tag:
view
def add_pictures_to_event(request, event_id):
return render(request, 'add_pictures_to_event.html')
template
{% extends 'base.html' %}
{% load staticfiles %}
{% load jfutags %}
{% block body %}
<div class="container">
<h2>Photo upload</h2>
{% jfu %}
</div>
{% endblock %}
As you can see, the view add_pictures_to_event, gets the request and the id of the event, but I cant seem to pass it to the upload view.
Any help would be appreciated.
I had the same question. I looked at different django versions of jQuery File Upload but stuck with Alem's jfu but with the changes from Thomas Willson to make it work in 1.9. My solution might not be the best but I could not find an other way.
I assume you already created an event and then add images to it.
media_upload_form.html is in my projects static directory. I used the UPLOAD_FORM_EXTRA block to add a hidden formfield with the current event_id:
{% block UPLOAD_FORM_EXTRA %}
<input type="hidden" name="currentevent" value="{{instance.pk}}">
{% endblock %}
I assume you have the view from the docs. I changed in the beginning of the uploadview:
file = upload_receive( request )
event_instance = get_object_or_404(Event, id=request.POST['currentevent'])
instance = Picture( file = file, event=event_instance)
instance.save()
It is probably against all django rules but it works. If anyone has a better solution I like to know too. FormSets maybe?
I have following field:
photo = models.ImageField(null=True,blank=True,upload_to="product_images")
I have defined the following layout in forms.py for this field:
self.fields['photo'].label = "Asset Image"
self.helper.layout = Layout(
'photo',
HTML("""{% if form.photo.value %}
<img height="80"
width="160"
class="pull-left"
src="{{ MEDIA_URL }}{{ form.photo.value }}">
{% endif %}""", ),
Now I can upload images associated with this particular field just fine. However when I try to update the image I see the following in my template:
Is there any way I can change the layout so that only the browse button and existing image are shown when the image field is not empty? In other words, remove the text Currently: product_images/km_2.jpeg Clear Change:
I'm pretty sure ImageField uses ClearableFileInput in order to render the HTML.
So to get rid of the "Currently: ... Clear" stuff you need to subclass the ClearableFileInput and modify the template_with_clear and/or template_with_initial members.
from django.forms import ClearableFileInput
class MyClearableFileInput(ClearableFileInput):
template_with_initial = '%(input_text)s: %(input)s'
Subsequently you use MyClearableFileInput, e.g.:
class MyForm(ModelForm):
class Meta:
model = MyModel
widgets = {
"file": MyClearableFileInput(),
}
I tested this with a FileField, but I'm pretty sure it will also work with an ImageField.