expected string or buffer: Private Messages App - python

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

Related

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

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

I am trying to get chapterdetails from model but i am redirecting to this url '/accounts/django'?

my views.py
#login_required
#api_view(['GET'])
def ChapterNames(request, id):
liveclass_id = models.LiveClass_details.objects.filter(id=id).first()
chapter_names = liveclass_id.chapter_ids.all()
serializer = serializers.chapterNames_serializer(chapter_names, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
models.py
class ChapterNames(models.Model):
chapter_names = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.chapter_names
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_ids = models.ManyToManyField(ChapterNames)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField(default=timezone.now())
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.IntegerField(default=0)
no_of_students_registered = models.IntegerField(default=0)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
def __str__(self):
return self.chapter_details
here chapternames are added as many to many field in Django, user authentication and all the apis are working fine and only this one is causing error
urls.py
path('liveclass/', views.LiveClassView.as_view(), name='liveclass'),
path('liveclass/<int:id>', views.LiveClassViewId.as_view()),
path('liveclass/<int:id>/chapter-names', views.ChapterNames),
I am trying to hit liveclass/id/chapter-names but it is redirecting me to /accounts/login/?next=/liveclass/1/chapter-names when i tried to access it in postman but it is giving me fine results in rest framework api view
You put decorator #login_required in front of your view so it will try to login befor accessing the view if you are not yet logged in

Why I dont get response after successfully saving a serial number using ModelForm?

I am sending a post request from a scanner with scanned serial numbers to django server.
{"serial_number": "70:B3:D5:A9:C8:62", "bom": "2019/05/08"}
views.py
def camera_register(request):
form = forms.RegisterCamerasForm(data=request.POST)
if form.is_valid():
instances = form.save(commit=False)
# instances.serial_number = instances.serial_number.lower()
instances.last_sighting_ip = request.META.get('REMOTE_ADDR')
instances.last_sighting_time = datetime.datetime.now()
form.save()
form.save_m2m()
return JsonResponse(1, safe=False)
else:
return JsonResponse(form.errors, status=200)
forms.py
class RegisterCamerasForm(forms.ModelForm):
def clean(self):
super().clean()
class Meta:
fields = '__all__'
exclude = ['group']
model = camera_models.Camera
models.py
class Camera(TimeStampedModel):
public_identifier = models.UUIDField(unique=True,
default=uuid.uuid4,
editable=False)
serial_number = models.CharField(max_length=100,
unique=True,
null=True)
name = models.CharField(max_length=50, blank=True, null=True)
group = models.ForeignKey('CameraGroup',
on_delete=models.SET_NULL,
null=True,
related_name='cameras',
related_query_name='cameras')
# last seen at ip
last_sighting_ip = models.CharField(max_length=50, blank=True, null=True)
last_sighting_time = models.DateTimeField(null=True, blank=True)
objects = CameraQuerySet.as_manager()
def __str__(self):
return self.name or self.serial_number or str(self.public_identifier)
def as_json(self):
return {
'serial_number': self.serial_number
}
I am sending the request and I save it to the database, but I do not get a response and I need that to be able to make a pytest and merge it to develop.
I tried saving it with form.save() form.save_m2m() since I am modifying some datata. I add time and IP adress.(Have to make it all lowercase but one thing a a time)
When I am not saving it with form.save() I get a response, so this means my data is not valid in some way but I can't figure out how exactly.
I am sending the request via Restlet client , something similar to Postman and if I dont abourt the request it keeps going till infinity...

How to display form in django

I'am little confiused because my code in django does't work and I don't know why. I want to create a form displaying in html file. When I click on thh button, the url have to redirect me in the html file where I've put the form code. But the django return me a error
'User' object has no attribute 'nazwa_set'
My models.py is:
from django.db import models
from django.contrib.auth.models import User
class Firma(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik")
nazwa = models.CharField(max_length=250,verbose_name='Nazwa firmy', unique=False)
class Meta:
verbose_name = 'Firmę'
verbose_name_plural = 'Firmy'
def __str__(self):
return self.nazwa
class Cudzoziemiec(models.Model):
OBYWATELSTWA = (
('RU', 'Rosja'),
('UA', 'Ukraina'),
('BY', 'Białoruś'),
)
TYTUL_POBYTOWY = (
('WZ', 'Wiza'),
('KP', 'Karta pobytu')
)
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik")
nazwa = models.ForeignKey(Firma, on_delete=models.CASCADE, verbose_name="Firma")
obywatelstwo = models.CharField(max_length=250,choices=OBYWATELSTWA, verbose_name="Obywatelstwo")
imie = models.CharField(max_length=80, verbose_name="Imię", unique=False)
nazwisko = models.CharField(max_length=150, verbose_name="Nazwisko", unique=False)
data_ur = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data urodzenia")
miejsce_ur = models.CharField(max_length=100, verbose_name="Miejsce urodzenia")
paszport = models.CharField(max_length=30, verbose_name="Paszport")
data_start_pasz = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data wydania paszportu")
data_koniec_pasz = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data ważności paszportu")
dok_pobytowy = models.CharField(max_length=250,choices=TYTUL_POBYTOWY, verbose_name="Tytuł pobytowy")
data_start_pobyt = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Dokument pobytowy ważny od")
data_koniec_pobyt = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Dokument pobytowy ważny do")
class Meta:
verbose_name = 'Cudzoziemca'
verbose_name_plural = 'Cudzoziemcy'
def __str__(self):
return f'{self.imie} {self.nazwisko}'
in the view.py responsible def for adding the new record:
#login_required
def nowy_pracownik(request):
if request.method == "POST":
nowy_pracownik = CudzoziemiecForm(request.user, request.POST)
if nowy_pracownik.is_valid():
nowy_pracownik.save()
messages.success(request, 'Pomyślnie dodano pracownika !')
return render(request, 'cudzoziemiec/nowy_pracownik_ok.html')
else:
nowy_pracownik = CudzoziemiecForm(request.user)
return render(request, 'cudzoziemiec/nowy_pracownik.html', {'nowy_pracownik':nowy_pracownik})
And on the end here is my forms.py :
class FirmaForm(forms.ModelForm):
class Meta:
model = Firma
fields = ('nazwa',)
class CudzoziemiecForm(forms.ModelForm):
class Meta:
model = Cudzoziemiec
fields = ('nazwa','imie', 'nazwisko','obywatelstwo', 'data_ur','paszport', 'data_start_pasz', 'data_koniec_pasz', 'dok_pobytowy', 'data_start_pobyt', 'data_koniec_pobyt')
def __init__(self, user, *args, **kwargs):
super(CudzoziemiecForm, self).__init__(*args, **kwargs)
self.fields['nazwa'].queryset = user.nazwa_set.all()
self.user = user
def save(self, commit=True):
instance = super(CudzoziemiecForm, self).save(commit=False)
instance.user = self.user
if commit:
instance.save()
return instance
The error is probably somewhere in the forms. py in the class CudzoziemiecForm in line self.fields['nazwa'].queryset = user.nazwa_set.all()
In django default reverse lookup name is modelname_set. So when you trying to get user.nazwa_set.all() this means that there is some model Nazwa related with User. Since in your code you don't have model named Nazwa this line raise the error. I suppose you mean Cudzoziemiec or Firma so to fix problem you need to replace user.nazwa_set.all() with user.firma_set.all() in form's __init__ method.

django - Query the list of objects and their objects field

I want to check the MessageState of all the Message in each Threads (i.e. order_threads_message), and if any of the Threads has all the messages hidden then make that Thread as hidden too (/ or else remove it from order_threads_message). I want to do that in the view before passing it to the template. How do I do that? If you didn't get me, please ask. I will be happy to explain. Please help me how to do this in the views. I will be grateful. Thank you.
models.py:
class Thread(models.Model):
subject = models.CharField(max_length=50, blank=True, null=True)
user = models.ManyToManyField(User)
class ThreadState(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey(User)
thread_hidden = models.BooleanField(default=False)
class Message(models.Model):
thread = models.ForeignKey(Thread)
sender = models.ForeignKey(User)
sent_date = models.DateTimeField(default=datetime.now)
body = models.TextField()
class MessageState(models.Model):
message = models.ForeignKey(Message)
user = models.ForeignKey(User)
read = models.BooleanField(default=False)
message_hidden = models.BooleanField(default=False)
views.py
#login_required
def message(request):
user = request.user
threads = user.thread_set.all()
order_threads_message = threads.annotate(max_sent_date=Max('message__sent_date')).order_by('-max_sent_date')
if order_threads_message.count() > 0:
recent_thread = order_threads_message[0]
if recent_thread.message_set.all().count() > 0:
recent_thread_conversations = recent_thread.message_set.all()
return render(request, 'conversations.html', {
'all_threads':order_threads_message,
'conversations':recent_thread_conversations,
'active': recent_thread.id
})
else:
recent_thread_conversations = 0
return render(request, 'conversations.html', {
'all_threads':order_threads_message,
'conversations':recent_thread_conversations,
'active': recent_thread.id
})
else:
order_threads_message = 0
recent_thread_conversations = 0
return render(request, 'conversations.html', {
'all_threads':order_threads_message,
'conversations':recent_thread_conversations,
})
I have ran this query for the following models:
Models
class Thread(models.Model):
subject = models.CharField(max_length=50, blank=True, null=True)
user = models.ManyToManyField(User)
class ThreadState(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey(User)
thread_hidden = models.BooleanField(default=False)
class Message(models.Model):
thread = models.ForeignKey(Thread, related_name = 'message_thread')
sender = models.ForeignKey(User)
sent_date = models.DateTimeField(default=datetime.now)
body = models.TextField()
class MessageState(models.Model):
message = models.ForeignKey(Message, related_name='messagestate_message')
user = models.ForeignKey(User)
read = models.BooleanField(default=False)
message_hidden = models.BooleanField(default=False)
Query
Thread.objects.filter(message_thread__in = Message.objects.filter(messagestate_message__in=MessageState.objects.filter(message_hidden=False)))
This query will return the Thread objects if atleast one of its MessageState's message_hidden is False.

Categories