I'm very new to Python and Django so please bear with me. I'm running into a persistent error traced back to the "saleitem.save()" line in the below views.py. I'm trying to create a form that will allow me to populate various fields and then save and display that information on an active_listing.html page.
views.py
def create_listing(request):
if request.method == "POST":
saleitem = Listing()
saleitem.user = request.user
saleitem.item =request.POST.get("item")
saleitem.description = request.POST.get("description")
saleitem.category = request.POST.get("category")
saleitem.bid = request.POST.get("bid")
saleitem.image = request.POST.get("image_upload")
saleitem.save()
listings = Listing.objects.all()
empty = False
if len(listings) == 0:
empty= True
return render(request, "auctions/active_listing.html",{
"listings": listings,
"empty": empty
})
else:
return render(request, "auctions/create_listing.html")
models.py
class User(AbstractUser):
pass
class Listing(models.Model):
saleitem = models.CharField(max_length = 60)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller", null=True)
description = models.TextField()
category = models.CharField(blank = True, max_length= 60)
bid = models.DecimalField(max_digits=5, decimal_places=2, default=0)
image = models.URLField(blank=True, null=True)
listing_status = models.BooleanField(blank=False, default= True)
winning_bidder = models.ForeignKey(User, blank= True, on_delete= models.CASCADE, related_name = "winner", null = True)
bidding_status = models.BooleanField(default=False)
def __str__(self):
return self.item
I've tried using a Django form rather than an html template as well and run into the same issue. When I populate all the fields in my html form and hit the save button, I run into an error:
IntegrityError at /create_listing
NOT NULL constraint failed: auctions_listing.bid
Could anyone point me in the right direction of what to fix? The error message says the issue is with auctions_listing.bid but the traceback points to saleitem.save(). Any advice is appreciated.
Related
I am trying to write a row to database, with data gathered in a form. I need to work with two foreign keys and one of them is causing the creating to fail, although I am unable to figure out why:
here is my model:
def upload_path(instance,file):
file_dir = Path(file).stem
print('usr',instance.user.id)
path = '{}/{}/{}/{}'.format(instance.user.id,"projects",file_dir,file)
return path
class BuildingFilesVersions(models.Model):
version_id = models.AutoField(primary_key=True)
building_id = models.ForeignKey(Building, on_delete=models.CASCADE,related_name='building_id_file')
user = models.ForeignKey(Building, on_delete=models.CASCADE,related_name="user_file")
created_at = models.DateTimeField(auto_now_add=True, blank=True)
description = models.TextField(max_length=200, blank=True, null=True)
modification_type = models.CharField(choices=WORK_TYPE_CHOICES, max_length=200, blank=True, null=True)
filename = models.CharField(max_length=200, blank=True, null=True)
file = models.FileField(upload_to=upload_path, null=True, blank=True)
and here is my view:
#login_required
#owner_required
def RegisterFileView(request,pk):
form = AddBuildingFileForm()
if request.method == 'POST':
form = AddBuildingFileForm(request.POST,request.FILES)
if form.is_valid():
description = form.cleaned_data["description"]
modification_type = form.cleaned_data["modification_type"]
filename = form.cleaned_data["modification_type"]
file = request.FILES['file'].name
BuildingFilesVersions.objects.create(building_id_id=pk,
user_id=request.user,
description=description,
modification_type=modification_type,
filename=filename,
file=file)
return redirect('home')
else:
form = AddBuildingFileForm()
context = {'form':form}
return render(request, 'building_registration/register_file.html', context)
what gets me confused is that the error is Field 'building_id' expected a number but got <SimpleLazyObject: <User: Vladimir>> even though pk return the proper building_id
Can anyone see where I messed up?
to access the id of the foreign key add a double underscore
BuildingFilesVersions.objects.create(building_id=Building.objects.get(pk=pk),
user=request.user,
description=description,
modification_type=modification_type,
filename=filename,
file=file)
Your user must be logged in to assign him in the Model
Answer for Similar Question
See the Docs
I'm writing a function to save notes to the database from a form but it keeps throwing this error CourseNote() got an unexpected keyword argument 'user' and I don't seem to know where this error is coming from.
views.py:
def CourseNote(request, course_slug):
course = Course.objects.get(slug=course_slug)
user = request.user
if request.method == "POST":
course = Course.objects.get(slug=course_slug)
user = request.user
note_title = request.POST.get('note_title')
note_content = request.POST.get('note_content')
# CourseNote.objects.create(user=user, course=course, note_title=note_title, note_content=note_content)
new_note = CourseNote(user=user, course=course, note_title=note_title, note_content=note_content)
new_note.save()
response = 'Saved'
return HttpResponse(response)
urls.py:
path('<slug:course_slug>/save-note', views.CourseNote, name="save-note"),
models.py:
class CourseNote(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="note_user")
course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True)
note_title = models.CharField(max_length=200, blank=True, null=True)
note_content = models.TextField(blank=True, null=True)
date = models.DateTimeField(auto_now_add=True)
#sunderam-dubey It is not good practice to name same your view and model, kindly change it
Hy please am new to Django,I have a childmodel(relationship) referencing a parent model(Profile) through a foreign key. I want to get the relationship status of a particular profile, like querying it from backwards. Here's the code.
from django.db import models
from django.contrib.auth.models import User
#Create your models here.
class Profile(models.Model):
user = models.OneToOneField (User, on_delete= models.CASCADE)
prof_pics = models.ImageField (null = True, blank = True, upload_to = 'images/')
friends = models.ManyToManyField (User, blank=True, related_name="friend" )
bio = models.TextField(blank=True)
def__str__(self):
return str(self.user)
STATUS CHOICES = (
("accept", "accept"),
("send","send"),
)
def ___str__(self):
return str(self.user)
class Relationship(models.Model):
sender = models.Foreignkey(Profile, on_delete = models.CASCADE, null=True, related_name = "senders")
date_created = models.DateTimeField(auto_now_add= True)
receiver = models.ForeignKey(Profile, on_delete= models.CASCADE, null= True, related_name= 'receivers')
status = models.Charfield(max_length=10, choices= STATUS_CHOICES)
def_str_(self):
return f"{self.sender}-{self.receiver}-{self.status}"
The query I ran in my view to get the relationship of a particular profile as I saw a tutorial that did same thing with similar models.
#imported necessary dependencies
def relationship_view(request):
idd = request.user.id
profiles =Profile.objects.get(id=idd)
rel=profiles.relationship_set.all()
Print(rel)
return render(request, "profiles/relationship_query.html", {})
A screenshot from the tutorial
The error I get when I run my own view
File "C:\Users\semper\djangotry\twitterclone\profiles\views.py", line 96, in Relationship_view
rel = profiles.relationship_set.all()
AttributeError: 'Profile object has no attribute 'relationship_set"
You set the related_name fields as senders and receivers in Relationship model, so you need to use those.
def relationship_view(request):
idd = request.user.id
profile = Profile.objects.get(id=idd)
# you can get receivers from you and get senders to you.
receiver_relationship = profile.senders.all()
sender_relationship = profile.receivers.all()
...
I am currently working on a project that would take in a users information and store it. My problem is I keep running into this NOT NULL constraint failed with the user id error. I believe this comes from having a null user when the form is trying to save, but don't know what I could do to fix it. I tried using this line:
form.user = Profile.objects.get(user=self.request.user)
but it didn't work and gave me this error:
NameError at /users/pii/
name 'self' is not defined
Any help or advice that would point me in the right direction would be greatly appreciated!
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
gender = models.CharField(max_length = 1, choices = GENS, default = '')
birthday = models.DateField(default = '1900-01-01')
address = AddressField(on_delete=False, blank=True, null=True)
race = models.CharField(max_length = 2, choices = RACES, default = 'x')
ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default = 'x')
income = models.CharField(max_length = 1, choices = INCBRACKET, default = 'x')
education = models.CharField(max_length = 2, choices = EDUCATION, default = 'x')
employment = models.CharField(max_length = 1, choices = EMPLOYMENT, default = 'x')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kawrgs):
super().save(*args, **kawrgs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
views.py
def PII(request):
if request.method == 'POST':
form = PIIForm(request.POST,)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('finalpii')
else:
form = PIIForm(request.POST)
return render(request, 'users/pii.html', {'form':form})
forms.py
class PIIForm(forms.ModelForm):
birthday = forms.DateField()
class Meta:
model = Profile
fields = [
'gender',
'birthday',
'address',
'race',
'ethnicity'
]
You have to edit your user field of Profile model as...
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
null=True, Django will store empty values as NULL in the database. Default is False.
blank=True, form validation will allow entry of an empty value. Default is False.
Then run python manage.py makemigrations and python manage.py migrate commands and then you can add a profile with Null user.
I am trying to make Private Message App for my website on django.
Models.py:
class Message(models.Model):
sender = models.ForeignKey(User, related_name='sender')
recipient = models.ForeignKey(User, related_name='recipient')
sent_date = models.DateTimeField(blank=True, null=True)
title = models.CharField(max_length=70, default='Без теми', blank=True, null=True)
body = models.TextField(max_length=10000)
def __str__(self):
return self.title
class Meta:
verbose_name = 'повідомлення'
verbose_name_plural = 'Повідомлення'
Views.py:
#login_required
def write(request):
context = {}
context.update(csrf(request))
context['form'] = WriteMessage()
if request.POST:
write_form = WriteMessage(request.POST)
if write_form.is_valid():
cd = write_form.cleaned_data
if User.objects.filter(username=cd['recipient']).exists():
message = Message(sender = request.user, recipient=User.objects.get(username = cd['recipient']), title=cd['title'], body=cd['body'], sent_date=datetime.now)
message.save()
return redirect('/inbox/')
else:
context['errors'] = ["Not found user with this username"]
return render(request, 'send_message.html', context)
else:
return render(request, 'send_message.html', context)
And when I try to send the message, I get the error: expected string or buffer. But, when I send message from admin page - it works wonderful.
What I must do? Help me, please. Thanks.
My solution is replace sent_date = models.DateTimeField(blank=True, null=True) for sent_date = models.DateTimeField(auto_now_add=True) and deleting sent_date=datetime.now from creating new object in views.py
It seems, that trouble was in different types of data in DateField into models.py and datetime module...