Django Formset display currently images in BlogUpdate - django

i want to display currently images in BlogUpdate with custum label
how can i show blog related image in BlogUpdate
display currently images path with url
but not display currently images in img tag
i want to display currently images in blog_update.html
{{ img.media_files }}
display currently images path
<img src="{{ img.media_files.url }}">
but not display currently images in img tag
forms.py
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ['title', 'text', ]
class BlogImagesForm(forms.ModelForm):
class Meta:
model = BlogImages
fields = ['media_files', ]
media_files = forms.ImageField(
widget=forms.ClearableFileInput(attrs={'multiple': False,}))
BlogImagesFormSet = inlineformset_factory(
Blog, BlogImages, form=BlogImagesForm,
extra=6, max_num=6, can_delete=False, can_order=False
)
views.py
class BlogUpdate(LoginRequiredMixin, UpdateView):
model = Blog
form_class = BlogForm
template_name = 'blog/blog_update.html'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data['images'] = BlogImagesFormSet(
self.request.POST or None,
self.request.FILES or None,
instance=self.object
)
else:
data['images'] = BlogImagesFormSet(instance=self.object)
return data
def form_valid(self, form):
context = self.get_context_data()
images = context['images']
with transaction.atomic():
form.instance.owner = self.request.user
self.object = form.save()
if images.is_valid():
images.instance = self.object
images.save()
return super(BlogUpdate, self).form_valid(form)
blog_update.html
<form method="POST" enctype="multipart/form-data">
<div class="girdbox">
{% for img in images.forms %}
<label for="{{ img.media_files.auto_id }}" class="blurfix">
<img src="{{ img.media_files.url }}">
<div style="padding-bottom: 50%;"></div>
</label>
{% endfor %}
</div>
{% csrf_token %}
{{ form|crispy }}
{{ images|crispy }}
<button type="submit" class="btn btn-sm btn-primary w-100">
Blog-update
</button>
</form>

problem solved
not worked
<img src="{{ img.media_files.url }}">
code updated to instance and worked
<img src="{{ img.instance.media_files.url }}">
full code
<div class="girdbox">
{% for img in images.forms %}
{% if img.instance.media_files %}
<label for="{{ img.media_files.auto_id }}" class="blurfix">
<img src="{{ img.instance.media_files.url }}">
<div style="padding-bottom: 50%;"></div>
</label>
{% else %}
<label for="{{ img.media_files.auto_id }}" class="blurfix">
<img src="/media/post.jpg" id="{{ img.media_files.auto_id }}Show">
<div style="padding-bottom: 50%;"></div>
</label>
{% endif %}
{% endfor %}
</div>

Related

using formsets with images does not show the error when the image has not loaded

I have a function with a formset that needs a product that I take from the id that I pass in the function and of the formset creates 3 boxes to insert the images which I then save, the problem is that if these images are not compiled, the redirect is done anyway while in reality the error should come out. Where is the problem?
view
def product_gallery_create_view(request, id):
ProductGalleryFormset = modelformset_factory(ProductGallery, fields = ('image',), extra = 3)
product = Product.objects.get(id = id)
if request.method == "POST":
formset = ProductGalleryFormset(request.POST, request.FILES)
if formset.is_valid():
for form in formset:
instance = form.save(commit = False)
instance.product = product
instance.save()
return redirect('home')
else:
formset = ProductGalleryFormset()
context = {'formset':formset}
return render(request, 'crud/product_gallery_create.html', context)
model
class ProductGallery(models.Model):
product = models.ForeignKey(Product, on_delete = models.CASCADE, related_name = 'product_gallery')
image = models.ImageField(upload_to ='galleria/', null = False, blank = False)
html
<div class="container mt-3">
<h4>galleria prodotto</h4>
<hr>
{% if formset.errors %}
<div class="alert alert-danger">
{{ formset.errors }}
</div>
{% endif %}
<form method="post" enctype='multipart/form-data' class="notifica" autocomplete="off" novalidate>
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<div class="d-flex align-item-center justify-content-between">
<div><small>img</small> {{ form.image }}</div>
</div>
<hr class="mt-4 mb-4">
{% endfor %}
<input type="submit" value="crea galleria" class="btn btn-info w-100">
</form>
</div>

Django reference multiple image in template

Hi I am letting the user upload multiple images per project but so far the images are not displayed. In projects.html all projects should be displayed and the title and the describtion work so far. But the main-image doesn´t show up. In single-project all images should be displayed.
What do I have to change in my models.py?
Thanks in forward
models.py
class Project(models.Model):
title = models.CharField(max_length=200)
describtion = models.TextField(null=True, blank=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class ProjectImage(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
featured_images = models.FileField()
forms.py
class ProjectForm(ModelForm):
featured_images = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True}))
class Meta:
model = Project
fields = ['title', 'describtion', 'featured_images']
views.py
def createProject(request):
form = ProjectForm()
if request.method == 'POST':
form = ProjectForm(request.POST)
images = request.FILES.getlist('image')
if form.is_valid():
project = form.save()
for i in images:
ProjectImage(project=project, image=i).save()
context = {'form':form}
return render(request, 'projects/project_form.html', context)
def projects(request):
projects = Project.objects.all()
context = {"projects":projects}
return render(request, 'projects/projects.html', context)
def project(request, pk):
projectObj = Project.objects.get(id=pk)
return render(request, 'projects/single-project.html', {'project':projectObj})
projects.html
{% for project in projects %}
<div class="column">
<div class="card project">
<a href="{% url 'project' project.id %}" class="project">
<img class="project__thumbnail" src="{{project.featured_images.url}}" alt="project thumbnail" />
<div class="card__body">
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
</div>
</a>
</div>
</div>
{% endfor %}
single-project.html
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
<h3 class="singleProject__subtitle">Infos zum Produkt</h3>
{{project.describtion}}
project_form.html
<form class="form" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#text">{{field.label}}</label>
{{field}}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" />
</form>
To access the images of a project, you need to use the related manager in your templates:
projects.html
{% for project in projects %}
<div class="column">
<div class="card project">
<a href="{% url 'project' project.id %}" class="project">
<img class="project__thumbnail" src="{{project.projectimage_set.all.0.featured_images.url}}" alt="project thumbnail" />
<div class="card__body">
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
</div>
</a>
</div>
</div>
{% endfor %}
I assumed that by "main-image" you mean the first image of the project.
single-project.html
<h3 class="project__title">{{project.title}}</h3>
<h3 class="project__title">{{project.price}} €</h3>
<h3 class="singleProject__subtitle">Infos zum Produkt</h3>
{{project.describtion}}
{% for projectimage in project.projectimage_set.all %}
<img src="{{projectimage.featured_images.url}}"/>
{% endfor %}
To avoid the N+1 query problem, you can also change the query in your view:
views.py
def projects(request):
projects = Project.objects.all().prefetch_related('projectimage_set')
context = {"projects":projects}
return render(request, 'projects/projects.html', context)

Django Nested inline formset-- nested form does not save to DB, no errors thrown

We have a few nested inline formsets in an application. Ideally, the goal is to allow for dynamic and unlimited population of these fields so that users can add an arbitrary number of notes. The form renders, the JS calls are populating; however, I am not seeing the update on the nested from manager.
This is my first Django project and I am not finding anything regarding what is causing the hang up. The Organization is saved in the DB, but the notes are not.
Thanks in advance for any help
Model.py:
class Organization(models.Model):
//irrelevant organization information//
class OrganizationNote(AbstractNotes):
note = models.TextField(blank=True)
org = models.ForeignKey(Organization, on_delete=models.CASCADE,blank=True, null=True)
modelforms.py:
class OrganizationForm(AbstractBigThree):
class Meta:
model = custModels.Organization
fields = '__all__'
orgNoteFormSet = inlineformset_factory(custModels.Organization, custModels.OrganizationNote,
form=OrganizationForm, extra=0)
ModelView.py
class OrganizationCreateView(CreateView, AbstractOrganizationView):
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
org_note_form = orgNoteFormSet()
return self.render_to_response(
self.get_context_data(form=form,
org_note_form=org_note_form))
def get_context_data(self, **kwargs):
data = super(OrganizationCreateView, self).get_context_data(**kwargs)
if self.request.POST:
data['notes'] = orgNoteFormSet(self.request.POST)
else:
data['notes'] = orgNoteFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
notes = context['notes']
with transaction.atomic():
self.object = form.save()
if notes.is_valid():
notes.instance = self.object
notes.save()
return super(OrganizationCreateView, self).form_valid(form)
def get_success_url(self):
return '/portal'
template:
{% extends 'base.html' %}
{% load i18n widget_tweaks %}
{% block __file__ %}
<!-- filename == organization_create_form.html -->
{% endblock %}
{% block container %}
<script type="text/javascript">
$(function() {
$(".inline.{{ org_note_form.prefix }}").formset({
prefix: "{{ org_note_form.prefix }}",
})
})
</script>
<div class="content">
<div class="thermometer">
<div style="float:left;padding:10px;">
Dashboard
</div>
<div style="float:left;padding:10px;">
>><a class="back-link" style="padding-left:10px;"href="">Organization List</a>
</div>
</div>
<div class="col-md-7 main">
<h1>Create Organization</h1>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
<div id = "form_set">
<legend>Notes</legend>
</div>
<input type="button" value="Add Note" id="add_more">
<div id="form_set">
{{ org_note_form.management_form }}
{{ org_note_form.non_form_errors}}
{% for form in org_note_form.forms %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>
{{ form }}
</table>
{% endfor %}
</div>
<div id="empty_form" style="display:none">
<table class='no_error'>
<fieldset>
{{ org_note_form.empty_form}}
<div class="inline {{ org_note_form.prefix }}">
{{ form.note.errors }}
{{ form.note.label_tag }}
{{ form.note }}
</div>
</fieldset>
</table>
</div>
<div>
<input style="margin-top: 30px;" type="submit" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div> {% endblock %}
{% block javascripts %}
<script type="text/javascript">
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
{% endblock %}
<script> $('#add_more').click(function() {
var form_idx = $('#id_organizationnote_set-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_organizationnote_set-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});</script>
the issue was solved by editing the prefix of the model manager. By default django names the prefix as table_set which was missing from above.
add another option to your code:
def form_invalid(self, form):
print(form.errors)
...
to see if you have any validation errors in your form, don't forget to check errors in your inline

How to insert multiple choices in to the database and display

My models is:
class LabRequest(models.Model):
ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)
lab_test = models.ManyToManyField(Lab)
My Form
class LabRequestModelForm(forms.ModelForm):
class Meta:
model = LabRequest
fields = ['ticket', 'lab_test']
widgets = {
'lab_test': forms.CheckboxSelectMultiple,
}
My view
def LabRequestToGenerateView(request):
if form.is_valid():
obj = form.save(commit=False)
obj.created_by = request.user.id
obj.save()
return render(request, 'dashboard/laboratory_request.html', {'form': form})
My Template
<form action="." method="POST">
{% csrf_token %}
{{ form.as_p }}
<div class="form-group float-right">
<button type="submit" name="submit" class="btn btn-success btn-sm" > <i
class="fa fa-save"></i>
Save</button>
</div>
</form>
{% for rl in rl %}
<label for=""> Ticket: {{ rl.ticket }} </label>
<p> Lab Tests: {{ rl.lab_test }}</p>
{% endfor %}
So, It's displaying as a checkbox that's good. but when i want to save some data it saves only ticket, not lab_test? So, how do I save both?
As you see it displays only ticket which is Ubed Gedi ALi and where I wanted to see lab_test it shows me appname.modelname.None

using ModelForm Wizards with User Image Upload - can't get user.PK

I've been trying to create a photo upload system that allows users to upload an image and then write in a title and comment for that image. I was originally using a ModelForm when I made the image upload functionality but switched to a Form Wizard for the upload & comment functionality based on previous stackoverflow answers. I'm really confused on getting my site's user id system to work with this approach (I keep getting the error user id cannot be null when I attempt to upload pictures) and can't find any good resources -- any suggestions on whether this approach is valid and how I can fix the user_id issue?
Views.py:
def showScrapbookPage(request,userID):
if request.method == 'POST':
image = ImageUploadForm(request.POST, request.FILES)
user = User.objects.get(pk=userID)
if image.is_valid():
image.save()
scrapbook_gen = Pictures.objects
url = Pictures.objects.filter(user=User.objects.get(pk=userID))
return render(request, 'scrapbook/scrapbook.html', {'scrapbook_gen':scrapbook_gen, 'url':url, 'form': ImageUploadForm(),'userID':userID})
class PhotoWizard(SessionWizardView):
file_storage = FileSystemStorage(location = os.path.join(settings.MEDIA_ROOT, ''))
def done(self, form_list, **kwargs):
do_something_with_the_form_data(form_list)
return HttpResponseRedirect('/page-to-redirect-to-when-done/')
Models.py:
class Pictures(models.Model):
user = models.ForeignKey(User)
picture = models.ImageField(upload_to = 'scrapbook_uploads', default = 'static/scrapbook/images/no_pic_uploaded.jpg');
date = models.DateTimeField('date published', auto_now=True)
caption = models.TextField(blank = True)
title = models.CharField(max_length = 100, blank = True) #New
def __unicode__(self):
return self.caption
Forms.py:
class ImageUploadForm(ModelForm):
class Meta:
model = Pictures
fields = ['picture']
user = ['userID']
class TitleCommentForm(ModelForm):
class Meta:
model = Pictures
field = ["caption", "title"]
urls:
url(r'^(?P<userID>[-\w]+)/scrapbook/',views.showScrapbookPage, name='showScrapbook'),
url(r'^contact/$', PhotoWizard.as_view([ImageUploadForm, TitleCommentForm])),
Relevant section in template:
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
<!--Grid -->
<div id='frame'>
<table id = "frame-table">
<tr>
<td id = "left">
<span class="glyphicon glyphicon-chevron-left" alt = "left"></span>
</td>
<td id = "right">
<span class = "glyphicon glyphicon-chevron-right" alt = "right"/>
</td>
</tr>
</table>
<img id = "main" src="" alt=""/>
</div>
<div id = "wrapper" class="showpiece">
<ul id = "portfolio">
{% for x in url %}
{{ x.picture }}
<li><img src = '{{ MEDIA_URL }}{{ x.picture }}' ></li>
{% endfor %}
</ul>
</div>
Thanks!
Completely remove your added UserID stuff and use user = request.userinstead in your views.