i'm creating a form for product create and i have 5 image fields in product model ,user can upload 5 or 0 images as per requirement , but form is not saving data
python
models.py
class Category(models.Model):
cate_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=45)
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=45)
product_description = models.CharField(max_length=500, blank=True, null=True)
price = models.IntegerField()
quantity = models.IntegerField()
product_category_fk = models.ForeignKey('Category', on_delete=models.CASCADE,db_column='product_category_fk',related_name='pros')
image1 = models.ImageField(upload_to='chand_imgs',blank=True)
image2 = models.ImageField(upload_to='chand_imgs',blank=True)
image3 = models.ImageField(upload_to='chand_imgs',blank=True)
image4 = models.ImageField(upload_to='chand_imgs',blank=True)
image5 = models.ImageField(upload_to='chand_imgs',blank=True)
#forms.py
class CategoryForm(forms.ModelForm):
category_name = forms.CharField(max_length=50)
class Meta:
model = Category
fields = ('category_name', )
class ProductForm(forms.ModelForm):
class Meta():
model = Product
fields = ('product_category_fk','product_name','product_description','price','quantity','image1','image2','image3','image4','image5',)
#views.py
#login_required
def product_management(request):
form = ProductForm(data=request.POST)
if request.method =='POST':
if form.is_valid():
post=form.save(commit=True)
if 'picture' in request.FILES:
form.picture =request.FILES['picture']
return HttpResponseRedirect(reverse('index'))
else:
return render(request,'chandler/index.html',{'form':form})
else:
form = ProductForm()
return render(request,'chandler/product.html',{'form':form})
#product.html
{% if user.is_authenticated %}
<form method=”post” enctype=”multipart/form-data” action="" >
<h2>New post</h2>
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% else %}
<h2>Please login first!!!!</h2>
{% endif %}
form not saving any data i know my view is incorrect ,already tried different methods
change
<form method=”post” enctype=”multipart/form-data” action="" >
to
<form method="post" enctype="multipart/form-data" action="" >
Related
I stuck by an integrity error when I passed comment to my product review page. Help Me through this.
I think the error occurs because of the args which passed through the render function.
My models.py
class Comment(models.Model):
post = models.ForeignKey(List, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
subject = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def __str__(self):
return str(self.user)
views.py
def addcomment(request, id):
list = get_object_or_404(List, pk=id)
form = CommentForm(request.POST or None)
if form.is_valid():
data = Comment()
data.subject = form.cleaned_data['subject']
data.text = form.cleaned_data['text']
print("Redirected.....")
current_user = request.user
data.user_id = current_user.id
data.save()
messages.success(request, "Your Comment has been sent. Thank you for your interest.")
return HttpResponseRedirect(reverse('main:hackathonList', args=[list.id]))
return render(request, 'product.html', {'list': list, 'form': form})
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('subject', 'text')
urls.py
path('addcomment/<int:id>', views.addcomment, name='addcomment'),
template.html
<form action="{% url 'main:addcomment' user.id %}" role="form" method="post">
{% csrf_token %}
<p>{{ form | crispy }}</p>
{% if user.id is not none %}
<button type="submit" class="btn btn-secondary">Comment</button>
{% else %}
You must be logged in to post a review.
{% endif %}
</form>
In views.py instead of data.user_id = current_user.id ie remove this line and add int its place
data.user = current_user
data.post = list
You need to change
<form action="{% url 'main:addcomment' list.id %}" role="form" method="post">
this first. After that, just add a new line before save method call like:
data.post = list
I was able to render the form onto the html, input data and submit it but i got a NOT NULL constraint failure. Isn't the owner assigned to its respective owners when as i have indicated in my views? i do not know what is wrong here please help!
Models
class Car(models.Model):
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
model = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now_add=False)
mileage = models.IntegerField()
open_market_value = models.DecimalField(max_digits=12, decimal_places=2)
depreciation = models.DecimalField(max_digits=10, decimal_places=2)
down_payment = models.DecimalField(max_digits=10, decimal_places=2)
road_tax = models.DecimalField(max_digits=8, decimal_places=2)
installment = models.DecimalField(max_digits=8, decimal_places=2)
objects = models.Manager()
def __str__(self):
return self.name
Views
class CarCreate(CreateView):
model = Car
fields = [
'name', 'model',
'description', 'image',
'updated', 'mileage',
'open_market_value', 'depreciation',
'down_payment', 'road_tax',
'installment']
template_name = 'cars/create_car.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Default form contact -->
<form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<input type="submit" value="save">
</form>
<!-- Default form contact -->
{% endblock %}
Your model has a foreign key to the User model from 'django.auth'. While you are trying to save the object of 'Car' model as there was no object mentioned for the 'owner' field of the model, it is showing the error. So, you might want to explicitly mention it.
You can do something like this. Assuming that you have 'CarForm', a model form for you 'Car' model.
user = request.user
car_form = CarForm(request.POST)
if car_form.is_valid():
car = car_form.save(False)
car.owner = user
car.save()
This is most likely because owner is a required field in your model Car but you have not included it in the fields in your CreateView.
It's my first time with formsets / images and this is my error:
KeyError at /houses/new/
'image'
This is my code:
models.py
class House(models.Model):
user = models.ForeignKey(User, related_name='houses', on_delete=models.CASCADE)
address = models.CharField(max_length=500)
type = models.CharField(default='House', max_length=100)
stories = models.IntegerField()
square_feet = models.IntegerField()
description = models.TextField()
# Class is for the houses images
class Image(models.Model):
house = models.ForeignKey(House, default=None, related_name="images", on_delete=models.CASCADE)
image = models.ImageField(verbose_name='image')
forms.py
# This is the blueprint for House forms
class AlbumForm(forms.ModelForm):
address = forms.CharField(label="Address:")
type = forms.CharField(label="Type of House (House, Condo, Cottage):")
stories = forms.IntegerField(label="House Stories:")
square_feet = forms.IntegerField(label='Square Feet:')
class Meta:
model = House
fields = ['address', 'type', 'stories', 'square_feet', 'description']
# This is the form for images
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image')
class Meta:
model = Image
fields = ('image',)
views.py
def post_house(request):
ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=10)
if request.method == 'POST':
house_form = AlbumForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none())
if house_form.is_valid() and formset.is_valid():
post_form = house_form.save(commit=False)
post_form.user = request.user
post_form.save()
for form in formset.cleaned_data:
image = form['image']
photo = Image(house=post_form, image=image)
photo.save()
messages.success(request, "New house listing success")
house = post_form
return redirect('houses:details', house_id=house.pk)
else:
return render(request, 'login.html')
else:
house_form = AlbumForm()
formset = ImageFormSet(queryset=Image.objects.none())
return render(request, 'houses/house_form.html', {'house_form': house_form, 'formset': formset})
house_form.html
{% extends 'base.html' %}
{% block content %}
<br>
<div class="container">
<h4>Post a New Home</h4>
<form id="post_form" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{house_form}}
{{ formset.management_form }}
{% for form in formset %}
{{ form }} <br>
{% endfor %}
<input type="submit" name="submit" class="btn btn-success" value="Submit" />
</form>
</div>
{% endblock %}
It must be some relation between my form key and what each form in formset is taking. That being said they're both 'image' so I don't see the problem. Please let me know if you got an idea. Thanks a ton!
Try the below code,
if formset.is_valid():
for form in formset:
data = form.cleaned_data
image = data.get('image')
photo = Image(house=post_form, image=image)
photo.save()
form.is_valid() always fails. I tried different ways to handle it but fails every time and it returns false. Please help in figuring out whats wrong with the code.
models.py looks like this -
class Album(models.Model):
album_name = models.CharField(max_length=50, primary_key=True)
place = models.CharField(max_length=50)
date_pub = models.DateTimeField('date published')
def __str__(self):
return self.album_name
class Images(models.Model):
album_name = models.ForeignKey(Album, db_column='album_name')
image_name = models.CharField(max_length=40)
image = models.FileField(null=True, blank=True)
upload_dt = models.DateTimeField(auto_now=True, auto_now_add=False)
like_cntr = models.IntegerField(default=0)
description = models.CharField(max_length=200, null=True)
def __str__(self):
return self.image_name
forms.py is -
class ImagesForm(forms.ModelForm):
description = forms.CharField(required=False)
class Meta:
model = Images
fields = ('album_name', 'description',)
views.py is -
class RandomView(TemplateView):
template_name = 'photos/random.html'
def get(self, request, album_name):
images = Images.objects.filter(album_name=album_name)
context = {'album_name':album_name, 'images' : images}
return render(request, 'photos/random.html', context)
def post(self, request, album_name):
form = ImagesForm(request.POST)
if form.is_valid():
form.save(commit=False)
text = form.cleaned_data['description']
Images.album_name = album_name
form.save()
else:
return HttpResponse("Failed to save")
Templates is -
<h3>Album : {{album_name }}</h3>
{% for image in images %}
<img src="{{image.image.url}}" height="400" width="500">
<h4> {{image.image_name }}</h4>
<form method="POST" action=""> {% csrf_token %}
<span class = "badge">Description</span>
{% if image.description %}
<h4> {{image.description }} </h4>
{% else %}
<input type="text" value=" "/>
<button type="Submit">Submit</button>
{% endif %}
</form>
{% endfor %}
Where is your necessary name and id attributes for your input tag?
<input type="text" name="description" id="id_description"/>
Please try with {{ form.errors }} above "form" tag. And first of all check that what the errors arrive. Then Find the solution based on that error. Let me know if it is helpful or not.
models.py
class Location(models.Model):
name = models.CharField(max_length=100, verbose_name=u"Локация", default=u'')
country = models.ForeignKey("Country")
class Country(models.Model):
name = models.CharField(max_length=50, verbose_name=u"Страна")
class Photo(models.Model):
location = models.ForeignKey(Location, null=True, verbose_name=u'Фото')
photo = models.ImageField(upload_to='photos', null=True)
forms.py
class LocationForm(forms.ModelForm):
class Meta:
model = Location
fields = ['name', 'country']
photos = MultiFileField(min_num=1, max_num=10)
def save(self, commit=True):
instance = super(LocationForm, self).save(commit)
for each in self.cleaned_data['photos']:
Photo.objects.create(photo=each, location=instance)
return instance
views.py
class AddLocationPageView(CreateView):
model = Location
form_class = LocationForm
template_name = 'add_location.html'
class BrowseLocationsPageView(ListView):
model = Country
context_object_name = 'countries'
template_name = "browse_locations.html"
add_location.html
<form action="" method="POST">{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-default" type="submit">Add</button>
</form>
browse_locations.html
{% for country in countries %}
{{ country }}
{% endfor %}
While creating Location object the form field says: "Select a valid choice. That choice is not one of the available choices."
Of course, I do not have any choices, because the design is - if Country is absent in DB, it has to be created during Location creating, and in opposite case (Country is in DB, because someone created it before when he was creating Location) it has to be joined to Location.