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:.
Related
I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective.
Here is my Models.py
`class User(AbstractUser):
is_buyer=models.BooleanField(default=False)
is_seller=models.BooleanField(default=False)
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):
seller = 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)
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
class Order(models.Model):
buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False)
seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500)
amount = models.IntegerField(max_length=50, blank=False)
is_ordered = models.BooleanField(default=False)
order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False)
slug = models.SlugField(null=True)
def __str__(self):
return self.title`
And views.py where I am getting the submissions;
def createOrder(request):
profile = request.user.profile
form = CreateOrderForm()
if request.method == 'POST':
form = CreateOrderForm(request.POST, request.FILES)
if form.is_valid:
order = form.save(commit=False)
order.buyer = profile
order.save()
# form.save()
messages.info(request, 'Order Succesfully Created')
return redirect('create_order')
else:
messages.error(request, 'Order Not Created! Try Again Later')
context = {'form':form}
return render(request, 'users/create_order.html', context)
Any help will he highly appreciated.
I am beginner to django and I am trying to create a site to send reports after creating a profile, but when I send the report, the username of the author of the report is not saved, Just (None). I searched a lot about it and did not find it
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, verbose_name=("user"), null=True, on_delete=models.CASCADE)
identity_No = models.IntegerField( blank=True, null=True)
mobile_No = models.IntegerField( blank=True, null=True)
city = models.CharField( max_length=15,null=True)
class Meta:
verbose_name =("Profile")
verbose_name_plural =("Profile")
def __str__(self):
return '%s' %(self.user)
class Report(models.Model):
user = models.ForeignKey(User, verbose_name=("user"), on_delete=models.CASCADE)
Report_type =models.CharField( max_length=100, blank=True, null=True)
Region =models.CharField( max_length=30, blank=True, null=True)
city =models.CharField( max_length=30, blank=True, null=True)
sector =models.CharField( max_length=30, blank=True, null=True)
report =models.TextField( max_length=3000, blank=True, null=True)
files =models.FileField( blank=True, null=True)
class Meta:
verbose_name =("Report")
verbose_name_plural =("Report")
def __str__(self):
return '%s' %(self.user)
form.py
Shorten the time, attach only the report
class ReportForm(forms.ModelForm):
class Meta:
model = Report
fields = ['Report_type', 'Region', 'city','sector','report','files' ]
view.py
def report(requst):
if requst.method == 'POST':
report_form = ReportForm(requst.POST)
if report_form.is_valid() :
report_form.save()
return redirect ('accounts:home')
else:
report_form = ReportForm()
return render(requst, 'user/report.html', {
'report_form': report_form,
enter image description here })
You can link the new report wrapped in the ReportForm to the logged in user request.user with:
from django.contrib.auth.decorators import login_required
#login_required
def report(requst):
if requst.method == 'POST':
report_form = ReportForm(requst.POST)
if report_form.is_valid():
report_form.instance.user = request.user
report_form.save()
return redirect ('accounts:home')
else:
report_form = ReportForm()
return render(requst, 'user/report.html', { 'report_form': report_form })
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
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.
I am working on a rental website project where users can create a login and add a listing. Now I want the edit access to be given to only the owners of those listing and superuser. I am able to set the edit access either to superuser or to the user, I am trying to figure out how to do both.
models.py
class Listing(models.Model):
category = models.ForeignKey(
'Category', null=True, blank=True, on_delete=models.SET_NULL)
listing_name = models.CharField(max_length=250, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
price = models.CharField(max_length=250, null=True)
short_description = models.CharField(max_length=720)
description = models.TextField()
bedroom = models.CharField(max_length=250, null=True, blank=True,)
bathroom = models.CharField(max_length=250, null=True, blank=True,)
lease = models.CharField(max_length=250, null=True, blank=True)
contact_name = models.CharField(max_length=250, null=True)
email_address = models.CharField(max_length=250, null=True)
contact_number = models.CharField(max_length=12, null=True)
image_url = models.URLField(max_length=1024, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
image_one = models.ImageField(null=True, blank=True)
image_two = models.ImageField(null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.listing_name
views.py
#login_required
def edit_listing(request, listing_id):
listing = get_object_or_404(Listing, pk=listing_id)
if not request.user.is_superuser or request.user == listing.user:
messages.error(
request, 'Sorry, you dont have the permission to do that.')
return redirect(reverse('home'))
if request.method == 'POST':
if request.user == listing.user:
form = ListingForm(request.POST, request.FILES, instance=listing)
if form.is_valid:
form.instance.user = request.user
form.save()
messages.success(request, 'Successfully updated the listing')
return redirect(reverse('listing_detail', args=[listing.id]))
else:
messages.error(
request, 'Failed to update. Please ensure the form is valid.')
else:
form = ListingForm(instance=listing)
template = 'listings/edit_listing.html'
context = {
'listing': listing,
'form': form,
}
return render(request, template, context)
Particularly this line in the views is what I'm trying to achieve
if not request.user.is_superuser or request.user == listing.user:
messages.error(
request, 'Sorry, you dont have the permission to do that.')
return redirect(reverse('home'))
#views.py
def signup(request):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
*new_user = Profile.objects.create_user(**form.cleaned_data)*
login(request, new_user)
return HttpResponse('signup success.')
else:
form = ProfileForm()
return render(request, 'registration/profile.html', {'form': form})
I want to make new accouont(object) so, I want to use User.objects.create_user method
#models.py
class Profile(models.Model):
studentNumber = models.CharField(max_length=30, blank=True)
name = models.CharField(max_length=10, blank=True)
major = models.CharField(max_length=20, blank=True)
email = models.CharField(max_length=30, blank=True)
password = models.CharField(max_length=15, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
github = models.CharField(max_length=150, blank=True)
sns = models.CharField(max_length=150, blank=True)
it is my model!
How can I save my model to DB?