KeyError: 'image' - python

When I trying to save detail, I have this error: KeyError: 'image'. I can't understand, why? Error in views.py. I want to upload multiple photos at once
views.py:
#user_passes_test(lambda u: u.is_superuser)
def new_detail(request):
ImageFormSet = modelformset_factory(DetailImage,
form=ImageForm, extra=10)
if request.method == 'POST':
form = DetailForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES,
queryset=DetailImage.objects.none())
if form.is_valid() and formset.is_valid():
detail_form = form.save()
detail_form.save()
for form in formset.cleaned_data:
images = form['image'] # HERE IS THE PROBLEM
photo = DetailImage(detail=detail_form, image=images)
photo.save()
return redirect('/new_detail/')
else:
form = DetailForm(request.POST)
formset = ImageFormSet(queryset=DetailImage.objects.none())
return render(request, 'shop/new_detail.html',
{'form': form,'formset': formset})
forms.py
...
class ImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = DetailImage
fields = ('image',)
models.py
...
class DetailImage(models.Model):
detail = models.ForeignKey(Detail, related_name='images',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='details', null = True, blank = True)

KeyError: 'image' in your case means that there is no 'image' key in one of the forms in your formset cleaned data. You should perform a check. Something like this:
for form in formset.cleaned_data:
if 'image' in form:
image = form['image']
photo = DetailImage(detail=detail_form, image=image)
photo.save()

Related

Adding edit photo page to django image gallery app using Python

I have an image gallery app in Django that has an upload image page and sends that photo to a gallery page. Also, there's an edit photo page where I want to display the uploaded image and edit it, then submit the edited photo to the gallery page. How can I have the currently uploaded image show up on both the upload image and edit pages?
views.py #uploads form for add image page(named addartifact)
def addartifact(request):
if request.method == 'GET':
form = EditorForm()
return render(request=request,template_name='addartifact.html', context={'form': form})
if request.method == 'POST':
form = EditorForm(request.POST)
if form.is_valid():
imgtitle = form.cleaned_data['imgtitle']
imgdesc = form.cleaned_data['imgdesc']
image = form.cleaned_data['image']
artifact = Artifact.objects.create(imgtitle=imgtitle, imgdesc=imgdesc, image=image)
return HttpResponseRedirect(reverse('landingpage'))
views.py #uploads image to page
def image_upload_view(request):
"""Process images uploaded by users"""
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
# Get the current instance object to display in the template
img_obj = form.instance
return render(request, 'addartifact.html', {'form': form, 'img_obj': img_obj})
else:
form = ImageForm()
return render(request, 'addartifact.html', {'form': form})
forms.py
class ImageForm(forms.ModelForm):
"""Form for the image model"""
class Meta:
model = Artifact
fields = ('artifact_id', 'imgtitle', 'imgdesc', 'image')
class EditorForm(forms.Form):
imgtitle = forms.CharField(max_length=13, required=True, label=False, widget=forms.TextInput(attrs={'style': 'text-transform:lowercase;', 'placeholder': 'enter title'}))
imgdesc = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'add description'}), label=False, required=True)
image = forms.URLField(required=True, label=False, widget=forms.TextInput(attrs={'placeholder': 'add image'}))
models.py
class Artifact(models.Model):
artifact_id = models.AutoField(primary_key=True)
imgtitle = models.CharField(max_length=11)
imgdesc = models.CharField(max_length=24)
image=models.ImageField(upload_to='images/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']

DJANGO FORMS.py 'RawQuerySet' object has no attribute 'all'

Hi my problem is the next, I'm trying to do a Forms with filter raw sql but I can't solved this problem
'RawQuerySet' object has no attribute 'all'
Forms.py
class pruebaForm (forms.Form):
userid = forms.ModelChoiceField(queryset = users.objects.raw('SELECT userid FROM groupsmembers WHERE groupid=User.groupid'))
softlimit = forms.IntegerField()
hardlimit = forms.IntegerField()
printerid = forms.ChoiceField()
class Meta:
model = userpquota
Views.py
#login_required
def asignarcuota_lista (request):
f = userpquotaFilter(request.GET, queryset=userpquota.objects.all())
if request.method == "POST":
form = pruebaForm(request.POST)
if form.is_valid():
asignarcuota = form.save(commit=False)
asignarcuota.save()
messages.success(request,'Se ha asignadoº correctamente')
return redirect('asignarcuota_lista',)
else:
form = pruebaForm()
return render (request, 'pykota/asignarcuota_lista.html', {'filter': f, 'form': form})

Post create with multiple images using FBV

Hi everyone I am new to Django and I am going bald pulling my hair. Can someone help me with this.
I'm trying to add multiple images to my post and I am having issues. I have 2 models. One post model and One image model. My post model already has 1 imagefield. Then I have another related model which allows multiple images. Below is how my models look like
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts')
title = models.CharField(max_length=250, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
message = models.TextField()
post_image = models.ImageField()
class Image (models.Model): #(Images)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/', blank=True, null=True)
image_title = models.CharField(max_length=100)
image_description = models.CharField(max_length=250)
def __str__(self):
return self.post.title + " Image"
Below is how my views look like. When the form loads. It has the multiple image fields. Its just not saving those images when my post is created. I get a post that completely ignores the formsets and multiple images. It only shows the Post model aspects and 1 image of the Post model. Even in the Admin there are no multiple images.
Can someone point me to what is the error in my code?
VIEWS.py 1st try
#login_required
def post_create(request):
ImageFormset = modelformset_factory(Image, fields=('image', 'image_title', 'image_description'), extra=7)
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
formset = ImageFormset(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save() ## It seems as if my code just plays till here and then disconnects
for f in formset:
try:
photo = Image(post=post, image=f.cleaned_data['image', 'image_title', 'image_description'])
photo.save()
return redirect('posts:single', username=request.user.username, slug=post.slug)
except Exception as e:
break
else: ## This part works too as it shows the correct empty form
form = PostForm()
formset = ImageFormset(queryset=Image.objects.none())
context = {'form': form, 'formset': formset}
return render(request, 'posts/post_form.html', context)
below is my forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'message', 'post_image' )
Changed the views like user3054319 suggested see below. It works fine but saves only 1 image in the image folder. Is everything correct my indents
VIEWS.py 2nd try
#login_required
def post_create(request):
ImageFormset = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7)
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
formset = ImageFormset(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
for f in formset:
try:
photo = Prep(post=post, image=f.cleaned_data['image'], image_title=f.cleaned_data['image_title'],
image_description=f.cleaned_data'image_description'])
photo.save()
return redirect('posts:single', username=request.user.username, slug=post.slug)
except Exception as e:
break
Then I tried removing the try and except statement and getting the redirect outside the loop It saves all 7 images but in the end gives a error (see error image attached below)
VIEWS.py 3rd try
#login_required
def post_create(request):
ImageFormset = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7)
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
formset = ImageFormset(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
for f in formset:
photo = Prep(post=post, image=f.cleaned_data['image'], image_title=f.cleaned_data['image_title'], image_description=f.cleaned_data['image_description'])
photo.save()
return redirect('posts:single', username=request.user.username, slug=post.slug)
error image below
If this can be achieved by CBV I can add a video of me dancing like I won a lottery. but I won't get too greedy even a solution to this can save some hair on my head
I went through your post create view and found that you are trying to access multiple keys of a dictionary with one call which is f.cleaned_data[‘image’, ‘image_title’] which is syntactically wrong
If you print(f.cleaned_data) it will give dictionary and you should know how to access dictionary.
You must use
photo = Image(post=post, image=f.cleaned_data['image'], image_title=f.cleaned_data['image_title'])
Below are the correct Views.py thanks to user3054319
def post_create(request):
ImageFormSet = modelformset_factory(Images, fields=('image','image_title', 'image_description'), extra=7)
if request.method == "POST":
form = PostCreateForm(request.POST or None)
formset = ImageFormSet(request.POST or None, request.FILES or None)
if form.is_valid() and formset.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
print(formset.cleaned_data)
for f in formset.cleaned_data:
try:
photo = Images(post=instance, image=f['image'], image_title=f['image_title'], image_description=f['image_description'])
photo.save()
except Exception as e:
break
return redirect('posts:single', username=instance.user.username, slug=instance.slug)
else:
form = PostCreateForm()
formset = ImageFormSet(queryset=Images.objects.none())
context = {
'form': form,
'formset': formset,
}
return render(request, 'blog/post_create.html', context)

How do I save m2m field session from a form to another?

I'm doing a multi step form where everything is saved at the end. In my models I have a m2m checkbox field and I'm using django Sessions to grab the forms datas to show it on the final step.
The issue is that the m2m field (checkboxes) is not saved when I submit the final form.
Here is my views file :
views.py
def step1(request):
initial={'name': request.session.get('name', None), 'checkbox': request.session.get('checkbox', (False,))} #cookies
form = FormOneForm(request.POST or None, initial=initial)
if request.method == 'POST':
if form.is_valid():
request.session['name'] = form.cleaned_data['name']
request.session['checkbox'] = form.cleaned_data.get('checkbox')
return HttpResponseRedirect(reverse('step2'))
return render(request, 'step1.html', {'form': form})
def step2(request):
form = FormTwoForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
formtwo = form.save(commit=False)
formone2 = FormOne.objects.create(checkbox=request.session.get('checkbox')) #error is here
formone = FormOne.objects.create(name=request.session['name'])
formtwo.owner = formone
formtwo.save()
formone2.save_m2m()
return HttpResponseRedirect(reverse('step3'))
return render(request, 'step2.html', {'form': form})
models.py
class Font(models.Model):
font_name = models.CharField(max_length=100)
font_family = models.CharField(max_length=100)
font_link = models.CharField(max_length=100)
...
class FormOne(models.Model):
name = models.CharField(max_length=40)
checkbox = models.ManyToManyField(Font, blank=True)
...
class FormTwo(models.Model):
owner = models.ForeignKey(FormOne)
name = models.CharField(max_length=40)
...
this code gives me this error :
'checkbox' is an invalid keyword argument for this function
How can I achieve what I am trying to realise ?
Try to save object first:
formone2 = FormOne.objects.create(name=request.session['name'])
formone2.checkbox.add(request.session.get('checkbox')
The problem is that you need to save object before use Many-to-many relations. See docs:
You can’t associate it with a Publication until it’s been saved

Query Error when Saving Image ModelForm in Django

I'm trying to make a simple image upload form, which works until I try to save the Model called User_Image using the posted data. The error I get is this: int() argument must be a string or a number, not 'QueryDict' and I receive it at the line marked *****. Thanks for the help.
models.py:
class User_Image(models.Model):
image = models.ImageField(upload_to="img")
user_profile = models.ForeignKey(UserProfile)
title = models.CharField(max_length=10)
forms.py:
class User_ImageForm(ModelForm):
class Meta:
model = User_Image
views.py:
def upload_image(request):
if request.method == 'POST':
HttpResponseRedirect("/accounts/profile")
form = User_ImageForm(request.POST, request.FILES)
if form.is_valid():
im = User_Image(request.POST, request.FILES)
******im = im.save()
HttpResponseRedirect("/accounts/profile")
else:
form = User_ImageForm()
return render_to_response('uploadimage.html', {'form':form}, context_instance=RequestContext(request))
Why are you saving it to the model class directly? Try:
form = User_ImageForm(request.POST, request.FILES)
if form.is_valid():
im = form.save()
HttpResponseRedirect("/accounts/profile")
You don't need to following lines.
im = User_Image(request.POST, request.FILES)
im = im.save()
Enough to save the form,
.....
if form.is_valid():
form.save()
HttpResponseRedirect("/accounts/profile")
.....

Categories

Resources