django: CourseNote() got an unexpected keyword argument 'user' - python

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

Related

django: foreign key issues when creating a model object

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

Django - IntegrityError ... NOT NULL constraint failed on save()

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.

Django: Add additional properties to User

I'm trying to add additional attributes to my "Person" model, namely, "age", "city", and "state." I've been struggling with this for a few days now and have looked up the documentation on how to "Extend the User class" in Django. But, I'm stuck, and when I try to create a new account I get the following error:
TypeError at /polls/signup/add
'age' is an invalid keyword argument for this function
Person model:
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
age = models.CharField(max_length=50, null=True)
Create account view (I'm pretty sure this is where the problem is occurring):
def create_account(request):
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"],
age=request.POST["age"],
city=request.POST["city"],
state=request.POST["state"])
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
first_name=str(request.POST.get("first_name")),
last_name=str(request.POST.get("last_name")),
email=str(request.POST.get("email")),
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')
Any ideas on how I can solve this problem and allow users to add these bonus fields that aren't included with the generic User model?
You should use the Person model instead of User.
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"],
)
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')

expected string or buffer: Private Messages App

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...

Django: empty form errors

I've been experiencing a little problem when I try to update some record from database.
Strange thing is that form.errors are empty if form is invalid (I can't understand why).
Here are the
form
class PetitionUpdateForm(forms.ModelForm):
owner = forms.ModelChoiceField(
label=_('Petition creator'),
queryset=User.objects.all(),
widget=forms.HiddenInput()
)
class Meta:
fields = ('title', 'petition_text', 'description',
'category', 'num_signs', 'date_to', 'owner',)
model = Petition
model
class Petition(models.Model):
PETITION_STATUSES = (
('N', _('New petition')), # New one
('M', _('Moderation')), # On moderation
('R', _('Rejected')), # Failed petition
('S', _('Success')) # Succeeded petition
)
title = models.CharField(max_length=512)
slug = models.SlugField(max_length=512, editable=False, blank=True)
description = models.TextField()
petition_text = models.TextField(blank=True, null=True)
petition_picture = models.ImageField(upload_to=get_upload_path, blank=True)
petitioning = models.ManyToManyField(PetitionTarget, editable=False)
signs = models.ManyToManyField(User, editable=False, related_name='petition_signs')
num_signs = models.IntegerField(max_length=11, default=100, blank=True)
category = models.ForeignKey(Category, blank=True, null=True, related_name='petition_category')
date_to = models.DateTimeField(blank=True, null=True)
videos = models.ManyToManyField(Video, editable=False)
photos = models.ManyToManyField(Photo, editable=False)
audios = models.ManyToManyField(Audio, editable=False)
documents = models.ManyToManyField(Document, editable=False)
created = models.DateTimeField(auto_now_add=True, editable=False)
changed = models.DateTimeField(auto_now=True, editable=False)
status = models.CharField(max_length=1, choices=PETITION_STATUSES, default='M', blank=True)
owner = models.ForeignKey(User, related_name='petition_owner')
def __unicode__(self):
return u'{0}: {1}'.format(_('Petition'), self.title)
update view
#login_required
#render_to('petition/edit-petition.html')
def update_petition(request, slug):
p = get_object_or_404(Petition, slug=slug)
form = PetitionUpdateForm(request.POST or None, instance=p)
import pdb
pdb.set_trace()
if form.is_valid():
form.save()
messages.success(request, _('Petition saved'))
else:
print form.errors # errors are empty
messages.success(request, _('Some error happened'))
return {'form': form, 'petition': p}
What's wrong with my code?
I've already tried to set null attributes for the most of model fields, switched from class based view to a standard view and yet I'm unable to update my record.
Sultan,
Thanks
If there is no POST data, then request.POST or None is None, so the form is unbound.
Unbound forms are always invalid, but do not have any errors.
In your case, you may want to change the else: clause to elif request.POST:
See the docs on bound and unbound forms for more details.

Categories