When I clicked the publish button. I get this error (image field = `This field is required), and it's not submitting the post.
models.py:
class Blog(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author')
blog_title = models.CharField(max_length=300, verbose_name='Put a Title')
slug = models.SlugField(max_length=264, unique=True, null=True)
blog_content = models.TextField(verbose_name='What is on your mind')
blog_image = models.ImageField(upload_to='blog_images', verbose_name='Image', null=True)
publish_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.blog_title
views.py:
#login_required
def createblog(request):
form = CreateBlogPost()
if request.method == 'POST':
form = CreateBlogPost(request.POST, request.FILES)
if form.is_valid():
blog_obj = form.save(commit=False)
blog_obj.author = request.user
title = blog_obj.blog_title
print(title)
blog_obj.slug = title.replace(" ", "-")+"-"+str(uuid.uuid4())
print(blog_obj.slug)
blog_obj.save()
return HttpResponseRedirect(reverse('index'))
return render(request, 'App_Blog/create_blog.html', {'form': form})
This field is required this is a Validation error from Django form and it depends on your models, if you are using model form you have to set blank=True like this
blog_image = models.ImageField(upload_to='blog_images', verbose_name='Image', null=True,blank=True)
blank=True means field can be empty (it is not required field) and null=True means your database table column can accept null values.
Related
I am new to django and I am working on a project whereby users fill a form from frontend and the data is saved to a gig model where the writer extends from a profile foreignkey. The error says
ValueError at /seller_profile/ The Gig could not be created because
the data didn't validate.
Here is the models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
writer = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
image = models.ImageField(null=False, blank=False)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Views.py:
def createGig(request):
gig = request.user.profile
form = CreateGigForm()
if request.method == 'POST':
form = CreateGigForm(request.POST, request.FILES)
if form.is_valid:
gig = form.save(commit=False)
gig.writer = gig
gig.save()
messages.info(request, 'Profile Succesfully Created')
return redirect('create')
else:
messages.error(request, 'Gig Not Created! Try Again Later')
context = {'form':form}
return render(request, 'starter/create_gig.html', context)
And here is a screenshot of the error message: Error message screenshot
I found the solution to this. The problem was with checking if form is valid there was an error with missing brackets. if form.is_valid: should be if form.is_valid:.
My process for this is for them to request an item through the project request view and is stored in the Activity model, if a request has been posted they can either approve or reject it using the request approve or request reject view. Now, I want to create a history table that automatically stores the approved or rejected status of a requested item after they approve/reject it, who approved/rejected it, when it was done.
Models.py
class Activity(models.Model):
Item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, limit_choices_to={'Quantity__gt': 0})
staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, limit_choices_to={'Quantity__gt': 0})
project_site = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True)
Quantity = models.PositiveIntegerField(null=True, default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
])
date_created = models.DateTimeField(auto_now_add=True)
is_draft = models.BooleanField(default=True)
request_status = models.IntegerField(default=0,
validators=[
MaxValueValidator(3)
])
return_status = models.IntegerField(default=0,
validators=[
MaxValueValidator(3)
])
note = models.TextField(max_length=255, null=True)
class Meta:
verbose_name_plural = 'Item Request'
def __str__(self):
return f'{self.Item}'
Views.py
def project_request(request):
activities = Activity.objects.all()
returns = ReturnItem.objects.all()
if request.method == 'POST':
form = ActivityForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.staff = request.user
instance.request_status = 2
instance.return_status = 2
instance.save()
return redirect('project_request')
else:
form = ActivityForm()
context={
'activities' : activities,
'returns' : returns,
'form' : form,
}
template_name ='project-admin/project-request-items.html'
return render(request, template_name, context)
def request_approve(request, pk):
activities = Activity.objects.get(id=pk)
activities.request_status = 1
activities.save()
return redirect('project_request')
def request_reject(request, pk):
activities = Activity.objects.get(id=pk)
activities.request_status = 0
activities.save()
return redirect('project_request')
hi am working on a project where am using multiple user data a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post is not selected on which he adds price this is my post model.py
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
this is my second model of adding price to a particular post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices')
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
status = models.BooleanField(default=False)
this is my adding price to the post views.py
#login_required
def add_price_to_post(request, pk):
post = get_object_or_404(Loader_post, pk=pk)
user = request.user
if request.method == "POST":
form = price_form(request.POST)
if form.is_valid():
ps = form.save(commit=False)
ps.user = request.user
ps.status = True
ps.post = post
ps.save()
return redirect('Driver:Driverview')
else:
form = price_form()
return render(request, 'price_form.html', {'form': form})
this is my html add post button
{% for loader in Loader %}
this is loop and this is button
add price
you can see my_post is select automatically
In your model the field name is my_post while in the add_price_to_post you are adding ps.post. change that to ps.my_post.
I would like the slug to be generated automatically from the title the user imports, or have random integers generated if the title is blank. The way I currently have it, the slug is supposed to be populated from the form title, but I get an error saying the form doesn't have a title field.
So, I need to:
change the slug in the views.py to be populated from the inputed title
create a random integer generator if the title is blank (I'm assuming in models.py and views.py?)
Could someone please help me with this?
Thank you in advance! I appreciate any and all help!
forms.py:
class PhotoUploadForm(forms.ModelForm):
title = forms.CharField(
widget=forms.TextInput(attrs={"placeholder": "Title of photo", "size": "30"})
)
description = forms.CharField(
widget=forms.Textarea(attrs={"placeholder": "Description of photo"})
)
class Meta:
model = Photo
fields = ('category', 'title', 'description', 'image')
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
views.py:
def photo_upload_view(request, username):
u = MyUser.objects.get(username=username)
form = PhotoUploadForm()
if request.method == 'POST':
form = PhotoUploadForm(request.POST or None, request.FILES)
new_slug = Photo.objects.get(slug=form.title)
if form.is_valid():
obj = form.save(commit=False)
obj.creator = request.user
obj.slug = slugify(new_slug)
obj.save()
messages.success(request, "Thank you! You have successfully posted your picture!")
return HttpResponseRedirect('/')
else:
form = PhotoUploadForm()
submit_btn = "Upload Post"
context = {
"submit_btn": submit_btn,
"form": form
}
return render(request, "photos/photo_upload.html", context)
This line is your problem:
new_slug = Photo.objects.get(slug=form.title)
You're setting the value of new_slug to a retrieved object, not a string. That isn't going to slugify. You probably just want this:
new_slug = form.title
But if you actually want to retrieve a value from a Photo, reference that attribute at the end, so:
new_slug = Photo.objects.get(slug=form.title).slug
As for generating a random integer:
from random import randint
randint(0,100)
Will return a random integer between 0 and 100 (inclusive).
I have a view which validates data from a form which just has some basic information about an item. I'm confused with how the is_valid method works here even after reading
this . If the user doesn't input some of the required fields like name or image 1, I want them to see the error on the page "this field is required" or something of that nature. I thought if the form.is_valid returned False, these messages would automatically be raised on the page for the user. Or do I need to specify what error message for each field somewhere that I would want the user see?
#view
def sell(request):
if request.method == "POST":
form = AddItem(request.POST, request.FILES)
if form.is_valid():
item = form.save(commit=False)
item.user = request.user
item.is_active = True
item.slug = slugify(item.name)
item.save()
return HttpResponseRedirect('thanks.html')
else:
form = AddItem()
return render_to_response('forsale.html', locals(), context_instance=RequestContext(request))
#form
class AddItem(forms.ModelForm):
name = forms.CharField(label="Title")
class Meta:
model = Item
exclude = ('user','slug','is_active',)
#model
class Item(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=75)
slug = models.SlugField(max_length=50, unique=True)
is_active = models.BooleanField(default=True, blank=True)
image1 = models.ImageField(upload_to='img')
image2 = models.ImageField(upload_to='img', blank=True)
image3 = models.ImageField(upload_to='img', blank=True)
image_caption1 = models.CharField(max_length=200, blank=True)
image_caption2 = models.CharField(max_length=200, blank=True)
image_caption3 = models.CharField(max_length=200, blank=True)
price = models.DecimalField(max_digits=8, decimal_places=2)
quantity = models.IntegerField(default=1)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
shipping_price = models.DecimalField(decimal_places=2, max_digits=6)
categories = models.ManyToManyField(Category)
You need to extract the errors from the form object using form.errors then deal with the dict however you want. If you're using ajax, simply send the dict as json back over and use javascript to handle it. If it was a direct html form submit, then you need to render and respond with a page with the errors in the passed dictionary and deal with the passed error in the template (usually with an {% if errors %} tag