My Views
def apost(request):
if request.method =='POST':
form = APostForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
form.slug = slugify(form.title)
form.save()
return redirect('apost')
else:
form = APostForm()
template_name = 'dadmin/form.html'
items = Post.objects.all()
context = {'title':'Add Post','form':form,'items':items}
return render (request, template_name, context)
My Form
class APostForm(forms.ModelForm):
class Meta:
model = Post
fields = {'title','photo','content'}
Models
photo = models.ImageField(upload_to='images')
No Image uploaded is Accepted Photo is selected but when Click save. It shows this field is required error. I had searched through the questions here but request.FILES solves others problems but not mines. Whats wrong?
you should use in template where you are uploading form:
<form class="form-horizontal form_middle" enctype='multipart/form-data' method="POST">
#apply logic for media upload
</form>
in views.y, the form you are saving should also have request.FILES
studentProfileForm = StudentRegisterForm(request.POST, request.FILES)
if studentProfileForm.is_valid():
user = studentProfileForm.save()
File upload is a bit weird in model forms in django.
Change your forms.py to -
class APostForm(forms.ModelForm):
photo=forms.FileField(label='Upload image') # or image field
class Meta:
model = Post
fields = {'title','content'}
form.save() will automatically save the field.
Related
Let's say I submit a form to the back-end and I save a record of the model in the following way:
views.py:
def viewName(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save() #I want to get the id of this after it is saved
else:
print (form.errors)
form = ProjectForm()
return render(request, 'index.html', context)
forms.py:
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = '__all__'
Right after saving the form, I would like to get the id of the record for the model.
I tried with form.id and form.pk as I saw in other similar questions without success.
How can I get the id or the pk of the new entry added to the Project model?
form.save() returns the object, so:
obj = form.save()
print(obj.pk)
I Tried To Add An Image To My Database But I Can Only Insert It Manually In My Admin Panel, It Doesn't Add It Automatically From My Form
This Is My models.py
option1photo = models.ImageField(null=True, blank=True)
option2photo = models.ImageField(null=True,blank=True)
option3photo = models.ImageField(null=True,blank=True)
And My forms.py
class AddpollForm(forms.ModelForm):
class Meta:
model = PollOptions
fields = ['option1photo','option2photo','option3photo']
And My views.py
polloptions_form = AddpollForm()
if request.method == 'POST':
polloptions_form = AddpollForm(request.POST)
if polloptions_form.is_valid():
polloptions = polloptions_form.save(commit=True)
return redirect('home')
Any files in the form are put in request.FILES by Django. Also one should make sure their form tag has the following set: enctype="multipart/form-data" if they are submitting file data.
Your view should be like:
polloptions_form = AddpollForm()
if request.method == 'POST':
polloptions_form = AddpollForm(request.POST, request.FILES)
if polloptions_form.is_valid():
polloptions = polloptions_form.save(commit=True)
return redirect('home')
And your form tag when you are uploading files should be like:
<form method="post" enctype="multipart/form-data">
I want to save 400 picture to my Image model using one single file field and i dont know how tp get each image from the form and create an instance on the Image model
here is my model function:
class Image(models.Model):
image = models.ImageField(null=True, blank=True)
and here is my form:
class AddImageForm(forms.ModelForm):
image = forms.FileField(widget=forms.FileInput(attrs={'class':'form-control','multiple':'true'}))
class Meta:
model = Image
fields = ['image']
and here is my view which i know is wrong just to make sure i share everything:
def imagesform(request):
form = AddImageForm()
if request.method == 'POST':
if form.is_valid():
for i in form['image']:
Image.objects.create(image=i)
context = {'form':form}
return render(request, 'members/imagesform.html', context)
Multiple file uploads can be a pain to implement, but you're almost there! From what I see, the only thing that's missing is that you should instantiate your form with the request.POST and request.FILES arguments:
def imagesform(request):
if request.method == 'POST':
form = AddImageForm(request.POST, request.FILES)
if form.is_valid():
for i in form['image']:
Image(image=i).save()
form = AddImageForm()
context = {'form':form}
return render(request, 'members/imagesform.html', context)
Also, make you sure you add the attribute enctype="multipart/form-data" to your <form> tag.
I have a ModelForm:
class UploadForm(forms.ModelForm):
class Meta:
model = Image
fields = ['image']
which is based on model Image
class Image(models.Model):
def content_file_name(instance, filename):
return filename
name = models.CharField(max_length=50)
image = models.ImageField(upload_to=content_file_name)
user = models.ForeignKey(MyUser, related_name='image')
In views.py, I try to save the image name and user object (from session) along with the uploaded image to database.
form1 = UploadForm(request.POST, request.FILES)
if form1.is_valid():
image = request.FILES['image'] # image is of UploadedFile class
form1.Meta.model.name = image.name
form1.Meta.model.user = get_object_or_404(MyUser,username=request.session['user'])
form1.save()
return render(request, '16_upload01.html', context)
Problem is only the uploaded image gets saved. Error message in browser:
IntegrityError at /competition-big/big1/upload
comp_app_image.user_id may not be NULL
I confirmed this by checking on SQL command:
INSERT INTO "comp_app_image" ("name", "image", "user_id") VALUES ('', 'grey-160-100_1.png', None)
I figure that image name and user are not bounded to form1. But how can I achieve that?
EDIT
After some digging, I know I messed up with above code. Now I changed my code to this:
if form1.is_valid():
form1.cleaned_data['user'] = get_object_or_404(MyUser, username=request.session['user'])
form1.save()
But I still get null user_id error.
EDIT 2
Thanks Jacinda. Now I get this cleaner code:
if form1.is_valid():
form1.cleaned_data['user'] = request.user
form1.save()
But error null user_id remains.
If this form can only be accessed by a logged in user, use the login_required decorator, and you should always redirect after a POST. You should also read this section in the ModelForms documentation; which describes how to properly use a model form that has limited fields.
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
#login_required
def your_view(request):
form1 = UploadForm(request.POST, request.FILES)
if form1.is_valid():
image = request.FILES['image'] # image is of UploadedFile class
obj = form1.save(commit=False)
obj.name = image.name
obj.user = request.user
obj.save()
return redirect('your-view-name')
else:
return render(request, 'form.html', {'form': form1})
I think your issue is probably this line:
form1.Meta.model.user = get_object_or_404(MyUser,username=request.session['user'])
When I try and use your syntax (using the Django default django.contrib.auth) I get a KeyError on 'user'.
What I've always done when I need information about the user associated with a request is this:
username = request.user.username
Reference: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.user
Of course, this will only work if your users are required to be logged in to upload images.
I read some documents in Django site such as: Basic file uploads and FileField.storage. However, I still don't understand how to upload a file (or an image) to server and store its link in database. I would like to write the files to the following directory such as: 'image/%Y/%m/%d'
Please give me a sample code. Thank you so much.
My code follows as:
#models.py
class Image(models.Model):
imageid = models.AutoField()
title = models.CharField(max_length=100)
imagepath = models.ImageField(upload_to='images/%Y/%m/%d/')
#forms.py
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=100)
image = forms.FileField()
#views.py
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
# How to upload file to folder named 'images/%Y/%m/%d/'
# How to save the link above to database
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
I believe if you create the upload form as a model form and then just save it in the view, it will have the effect of saving the file to the filesystem and the path to the model. This is a basic example, but I think it should work.
# forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = models.Image
# views.py
...
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')