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")
.....
Related
I tryed to add validation to ContactModel, by doing Forms.py but I went too far away with it and now dont know to fix it. Can someone help ?
def addContact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# form = Contact(
# full_name = request.POST ('fullname'),
# relationship = request.POST ('relationship'),
# email = request.POST ('email'),
# phone_number = request.POST ('phone-number'),
# address = request.POST ('address'),
# )
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
def contactProfile(request,pk):
contact = Contact.objects.get(id=pk)
return render(request, 'contact/contact-profile.html', {'contact': contact})
In my opinion in Views I have big mess.. When I fill up all fields data isn't sending to database.
forms.py:
from django.forms import ModelForm
from .models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
models.py:
from django.db import models
# Create your models here.
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number =models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
It seems that your form is not valid and it redirects always to contact.
You should to use redirect only if the form is valid. Otherwise you will never see which errors your form contains.
Try the following code:
def addContact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
else:
form = ContactForm()
context = {'form': form}
return render(request, 'contact/new.html', context)
I can create model objects through admin panel. But I want it to be created on website. The code below allows me to enter values of a model, and when I submit it, it redirects to the written url, which happens after form.save. This is the message from server "POST /taskcreate HTTP/1.1" 302 0. But there is no changes in database. How to solve this issue? Any thoughts... Thanks
models.py
class Task(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=1000)
pub_date = models.DateTimeField('date_published', auto_now_add = True)
cost = models.IntegerField()
def __str__(self):
return '%s' % (self.name)
forms.py
class TaskCreateForm(forms.ModelForm):
class Meta:
model = Task
fields = ('name', 'description', 'cost')
views.py
def TaskCreateView(request):
if request.method == 'POST':
form = TaskCreateForm(request.POST)
if form.is_valid():
form.save
return redirect('home')
else:
form = TaskCreateForm()
return render(request, 'employer/create_task.html')
You didn't actually call the save method.
if form.is_valid():
form.save()
return redirect('home')
When you use ModelForm you just need to write form.save() method right after if is_valid() if case. In your case, you are missing curly brackets after save.
def TaskCreateView(request):
if request.method == 'POST':
form = TaskCreateForm(request.POST)
if form.is_valid():
form.save() # here you were missing curly brackets
return redirect('home')
else:
form = TaskCreateForm()
return render(request, 'employer/create_task.html')
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)
I have 2 models that it must be input to database in same time by submit button in my template.
this is my first model
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID=models.CharField(max_length=5,blank=True,null=True)
SiswaNIS = models.IntegerField(null=True, blank=True)
second model
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.CharField(max_length=10,blank=True,null=True)
and this is my view.py
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
if request.method == 'POST':
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return redirect('index')
else:
form = datasiswa()
form2 = riwayatsekolah()
return render(request, 'siswa/tambah_siswa.html', {'form': form, 'form2': form2})
how to insert SiswaID fromDataPribadiSiswa to SiswaID_FK in RiwayatSekolah at same time where all form is blank?
You can use ForeignKey field.
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.ForeignKey(DataPribadiSiswa)
Now in view you can try to save Siswa instance first and then to add it into Sekolah instance:
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
if request.method == 'POST':
if form.is_valid() and form2.is_valid():
siiswa_instance = form.save()
Sekolah_instance = form2.save(commit=False)
Sekolah_instance.SiswaID_FK = siiswa_instance
Sekolah_instance.save()
I want to pass a pk from one form to another so that it can be used as the foreign key for the second form. Here are the model:
models.py
class CompanyDetails(models.Model):
name = models.CharField(max_length=100)
class CompanyDetailsForm(forms.ModelForm):
class Meta:
model = CompanyDetails
class DataRequest(models.Model):
company = models.ForeignKey(CompanyDetails, default="0")
agency_name = models.CharField(max_length=100)
class DataRequestForm(forms.ModelForm):
class Meta:
model = DataRequest
exclude = ['company']
And here is the view for the first form:
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', data.id))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
How should I set up my second view so that the form will save an object that has the foreign key for the object created by the first form in it?
I got it to work by passing the primary key of the first object through the url. It goes abc.com/form -> abc.com/form/16/datarequest. Not super ideal since by changing the number in the url the second object will use some other foreign key.
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', args=(data.id,)))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
def datarequest(request, company_id):
if request.method == 'POST':
form = DataRequestForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.company = CompanyDetails.objects.get(pk=company_id)
data.save()
return HttpResponse("Thanks")
else:
form = DataRequestForm()
return render(request, 'canareeform/datarequest.html', {'form': form})
If anyone has a better solution I'd love to hear it.