How to have a follow/unfollow button on a user's post - python

I have been trying make users follow other users from thier posts like in instagrams explore page. Currently a user can just follow and unfollow other users from their profile but I will like to have that follow/unfollow on their posts too. I tried to make this happen but in the process I got a NameError name 'username' is not defined, How can I fix this error in order to make this work?
models.py (mates model is where the follow/unfollow should go)
class Mates(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True)
req_bio = models.CharField(max_length=400)
class Following(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed = models.ManyToManyField(User, related_name="followed")
follower = models.ManyToManyField(User, related_name="follower")
#classmethod
def follow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.add(another_account)
print("followed")
#classmethod
def unfollow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.remove(another_account)
print("unfollowed")
def __str__(self):
return f'{self.user.username} Profile'
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
connection = models.CharField(max_length = 100, blank=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.profile_pic.path)
if img.height > 300 or img.width > 300:
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.profile_pic.path)
def __str__(self):
return f'{self.user.username} Profile'
views.py
def matesmain(request):
if request.user.has_posts():
contents = Mates.objects.filter(
categories__in=['action', 'sports', 'shooter', 'battle_royale', 'adventure', 'racing']
)
mates_owner = get_object_or_404(User, username=username)
context = {
'contents': contents,
'mates_owner': mates_owner,
}
print("nice3")
return render(request, 'mates.html', context)
else:
return render(request, 'mates-error.html')
def follow(request, username):
main_user = request.user
to_follow = User.objects.get(username=username)
following = Following.objects.filter(user = main_user, followed = to_follow)
is_following = True if following else False
if is_following:
Following.unfollow(main_user, to_follow)
is_following = False
else:
Following.follow(main_user, to_follow)
is_following = True
resp = {
'following': is_following,
}
response = json.dumps(resp)
return HttpResponse(response, content_type="application/json")
html
{% if connection and not request.user == mates_owner %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' mates_owner.username %}">Unfollow</a>
{% elif not connection and not request.user == mates_owner %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' mates_owner.username %}">Follow</a>
{% endif %}
urls.py
urlpatterns = [
path('follow/<str:username>', views.follow, name='follow')
path('mates-main', views.matesmain, name='mates-main'),
]
traceback
Traceback (most recent call last):
File "C:\Users\USER\Envs\startup\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\USER\Envs\startup\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\USER\Envs\startup\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\startup\gstartup\startup_home\views.py", line 126, in matesmain
mates_owner = get_object_or_404(User, username=username)
NameError: name 'username' is not defined
[16/Jul/2020 08:53:25] "GET /mates-main HTTP/1.1" 500 70246

Related

Django ValueError at /updatestudent/3 Cannot assign "'1'": "Student.class_id" must be a "Class" instance

ValueError at /updatestudent/3 Cannot assign "'1'": "Student.class_id" must be a "Class" instance. This error comes when I am trying to update my student model. when I am updating username also than it doesn't throw any error but if I am not updating username than only this throwing this error
Any help is appericiated.
models.py
class CustomUser(AbstractUser):
user_type_data = ((1,'HOD'),(2,'Staff'),(3,'Student'))
user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
class Student(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
gender = models.CharField(default=1, choices=gender_type, max_length=10)
profile = models.ImageField(upload_to='student/profile-images/%y/%m/%d/', default='student/profile-images/default.jpg', blank=False, null=False)
address = models.TextField()
class_id = models.ForeignKey(Class, on_delete=models.CASCADE, default=1)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def full_name(self):
return self.admin.first_name+' '+self.admin.last_name
def __str__(self):
return self.admin.username
class Session(models.Model):
id = models.AutoField(primary_key=True)
session_start= models.IntegerField()
session_end = models.IntegerField()
objects = models.Manager()
def __str__(self):
return f'{self.session_start} {self.session_end}'
class Course(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.name
class Class(models.Model):
id = models.AutoField(primary_key=True)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
branch = models.CharField(default='CSE', choices=branch_data, max_length=40)
year = models.CharField(default='First Year', choices=year_data, max_length=15)
session = models.ForeignKey(Session, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return f'{self.course} {self.branch} {self.year} {self.session}'
def name(self):
return f'{self.course} {self.branch} {self.year} {self.session}'
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.db.models import fields
from .models import (AdminHOD, Staff, Student, Class,
CustomUser, Course, Session, Attendance,
ExamType, Exam, Subject)
from .models import branch_data, year_data
gchoice = (('1','Male'),('2','Female'))
sesschoice = tuple((i.id, i.id) for i in Session.objects.all())
courchoice = tuple((i.id,i) for i in Course.objects.all())
choice_exam = tuple((i.id,i.name) for i in ExamType.objects.all())
all_class = tuple((i.id, i.name) for i in Class.objects.all())
class UserUpdateForm(UserChangeForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email']
class StudentUpdateForm(forms.ModelForm):
gender = forms.ChoiceField(choices=gchoice)
address = forms.CharField()
class_id = forms.ChoiceField(choices=all_class)
class Meta:
model = Student
fields = ['gender', 'class_id', 'address']
views.py
if request.method=='POST':
uform = UserUpdateForm(request.POST)
sform = StudentUpdateForm(request.POST)
if uform.is_valid():
address = request.POST.get('address')
username = request.POST.get('username')
clas = Class.objects.get(id=request.POST['class_id'])
email = request.POST.get('email')
gender = request.POST.get('gender')
print(clas)
try:
student = Student.objects.get(id=id)
user = student.admin
user.username = username
user.email = email
user.save()
student.address = address
student.gender = str(gender)
student.class_id = clas
student.updated_at = datetime.datetime.now()
student.save()
messages.success(request,'Student successfully Updated.')
return redirect('/managestudent')
except:
messages.error(request,'Student has not been Updated due to some technical issues.')
return render(request, 'cmsapp/hod/studentupdate.html', {'uform':uform,'sform':sform})
else:
messages.error(request,sform.errors)
return render(request, 'cmsapp/hod/studentupdate.html', {'uform':uform,'sform':sform})
else:
uform = UserUpdateForm(instance=Student.objects.get(id=id).admin)
sform = StudentUpdateForm(instance=Student.objects.get(id=Student.objects.get(id=id).id))
return render(request, 'cmsapp/hod/studentupdate.html', {'uform':uform,'sform':sform})
studentupdate.html
<h3>Update Student</h3>
<form action="" method="POST" class="form-group">
{% csrf_token %}
{{uform}}
{{sform}}
<button type="submit">Update Student</button>
</form>
</div>
traceback
Traceback (most recent call last):
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Akash Deep Saingar\Desktop\MySite\CollegeErp\cmsapp\hodviews.py", line 176, in update_student
messages.error(request,sform.errors)
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\forms\forms.py", line 172, in errors
self.full_clean()
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\forms\forms.py", line 376, in full_clean
self._post_clean()
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\forms\models.py", line 400, in _post_clean
self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\forms\models.py", line 63, in construct_instance
f.save_form_data(instance, cleaned_data[f.name])
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\db\models\fields\__init__.py", line 891, in save_form_data
setattr(instance, self.name, data)
File "C:\Users\Akash Deep Saingar\Desktop\MySite\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in __set__
raise ValueError(
Exception Type: ValueError at /updatestudent/3
Exception Value: Cannot assign "'1'": "Student.class_id" must be a "Class" instance.
In StudentUpdateForm, try to change the class_id field to:
class_id = forms.ModelChoiceField(queryset=Class.objects.all())

How to have a follower count on django

I have been working on a follow system like in instagram in which a user can follow and unfollow other users, also a profile has to display the number of followers the selected user has and the number of people that user is following. Everything is working fine except for the followers count which is not displaying any number rather than 0 which is the default even tho the user has one or more followers. How can a count function be added to this django project?
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
connection = models.CharField(max_length = 100, blank=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def __str__(self):
return f'{self.user.username} Profile'
class Following(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed = models.ManyToManyField(User, related_name="followed")
follower = models.ManyToManyField(User, related_name="follower")
#classmethod
def follow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.add(another_account)
print("followed")
#classmethod
def unfollow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.remove(another_account)
print("unfollowed")
def __str__(self):
return f'{self.user.username} Profile'
views.py
def profile(request, username=None):
profile, created = Profile.objects.get_or_create(user=request.user)
user = User.objects.filter(username=username)
if user:
post_owner = get_object_or_404(User, username=username)
profile_bio = Profile.objects.filter(user_id=post_owner)
user_posts = Post.objects.filter(user_id=post_owner)
user = user[0]
is_following = Following.objects.filter(user=request.user, followed=user)
following_obj = Following.objects.get(user=user)
follower = following_obj.follower.count()
following = following_obj.followed.count()
else:
post_owner = request.user
user_posts = Post.objects.filter(user=request.user)
profile_bio = Profile.objetcs.filter(user=request.user)
args1 = {
'user_obj':user,
'post_owner': post_owner,
'user_posts': user_posts,
'follower': follower,
'following': following,
'connection': is_following,
'profile_bio': profile_bio,
}
return render(request, 'profile.html', args1)
def follow(request, username):
main_user = request.user
to_follow = User.objects.get(username=username)
following = Following.objects.filter(user = main_user, followed = to_follow)
is_following = True if following else False
if is_following:
Following.unfollow(main_user, to_follow)
is_following = False
else:
Following.follow(main_user, to_follow)
is_following = True
resp = {
'following': is_following,
}
response = json.dumps(resp)
return HttpResponse(response, content_type="application/json")
profile.html
<div class="header-item">
{{ follower }}
</div>
<div class="header-item">
{{ following }}
</div>
{% if connection %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' user_obj.username %}">Unfollow</a>
{% elif not connection %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' user_obj.username %}">Follow</a>
{% endif %}
You have to change follow function like this :
def follow(request, username):
main_user = request.user
to_follow = User.objects.get(username=username)
following = Following.objects.filter(user = main_user, followed = to_follow).first()
if following is not None:
Following.unfollow(main_user, to_follow)
is_following = False
main_user.following -= 1
to_follow.follower -= 1
else:
Following.follow(main_user, to_follow)
is_following = True
main_user.following += 1
to_follow.follower += 1
main_user.save()
to_follow.save()
resp = {
'following': is_following,
}
response = json.dumps(resp)
return HttpResponse(response, content_type="application/json")

Why is the follower count not working on django

I have been trying to implement a follow/unfollow system on django in which a user can follow other users and the user can also be followed, in the user's profile there is a following count which displays how many people the user is following and a follower count which is supposed to display how many followers the user has just like in instagram. Everything is working good except for the follower count which doesn't counting the followers. for doing this follower count, I used signals but it doesnt work. How can I fix this problem?
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
connection = models.CharField(max_length = 100, blank=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def __str__(self):
return f'{self.user.username} Profile'
class Following(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed = models.ManyToManyField(User, related_name="followed")
follower = models.ManyToManyField(User, related_name="follower")
#classmethod
def follow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.add(another_account)
print("followed")
#classmethod
def unfollow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.remove(another_account)
print("unfollowed")
def __str__(self):
return f'{self.user.username} Profile'
views.py
def profile(request, username=None):
profile, created = Profile.objects.get_or_create(user=request.user)
if username:
post_owner = get_object_or_404(User, username=username)
profile_bio = Profile.objects.filter(user_id=post_owner)
user_posts = Post.objects.filter(user_id=post_owner)
user = User.objects.get(username=username)
is_following = Following.objects.filter(user=request.user, followed=user)
following_obj = Following.objects.get(user=user)
follower = following_obj.follower.count()
following = following_obj.followed.count()
else:
post_owner = request.user
user_posts = Post.objects.filter(user=request.user)
profile_bio = Profile.objetcs.filter(user=request.user)
args1 = {
'post_owner': post_owner,
'user_posts': user_posts,
'follower': follower,
'following': following,
'connection': is_following,
'profile_bio': profile_bio,
}
return render(request, 'profile.html', args1)
def follow(request, username):
main_user = request.user
to_follow = User.objects.get(username=username)
following = Following.objects.filter(user = main_user, followed = to_follow)
is_following = True if following else False
if is_following:
Following.unfollow(main_user, to_follow)
is_following = False
else:
Following.follow(main_user, to_follow)
is_following = True
resp = {
'following': is_following,
}
response = json.dumps(resp)
return HttpResponse(response, content_type="application/json")
signals.py
#receiver(m2m_changed, sender = Following.followed.through) # which list is changed
def add_follower(sender, instance, action, reverse, pk_set, **kwargs):
followed_users = [] # list of users main (logged ) user have followed
logged_user = User.objects.get(username = instance) # user who followed other users
for i in pk_set:
user = User.objects.get(pk = i)
following_obj = Following.objects.get(user = user)
followed_users.append(following_obj)
if action == "pre_add":
for i in followed_users:
i.follower.add(logged_user)
i.save()
if action == "pre_remove":
for i in followed_users:
i.follower.remove(logged_user)
i.save()
profile.html
{% if connection and not request.user == post_owner %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' post_owner.username %}">Unfollow</a>
{% elif not connection and not request.user == post_owner %}
<a type="button" class="button-caballo" id="follow" role="button" href="{% url 'follow' post_owner.username %}">Follow</a>
{% endif %}
<div class="header-item">
{{follower}}
</div>
<div class="header-item">
{{following}}
</div>
why creating another field for the followers? you can get the followers count and users from the same Following table without any need for followers field.
your following model should only contain user, followed
you can get the followers by using
following.objects.filter(followed=request.user)

How to stop having a value error on django?

I am trying to add a follow sistem to my django project my when running my code, I am getting a The QuerySet value for an exact lookup must be limited to one result using slicing. error, It is saying that the wrong part is on this line of code of the views.py file following_obj = Following.objects.get(user=user).
views.py
def profile(request, username=None):
profile, created = Profile.objects.get_or_create(user=request.user)
if username:
post_owner = get_object_or_404(User, username=username)
user_posts = Profile.objects.filter(user_id=post_owner)
user = User.objects.filter(username=username)
is_following = Following.objects.filter(user=request.user, followed=user)
following_obj = Following.objects.get(user=user)
follower, following = following_obj.follower.count(), following_obj.followed.count()
else:
post_owner = request.user
user_posts = Profile.objects.filter(user=request.user)
args1 = {
'post_owner': post_owner,
'user_posts': user_posts,
'connection': is_following,
'follower': follower,
'following': following,
}
return render(request, 'profile.html', args1)
def follow(request, username):
main_user = request.user
to_follow = User.objects.get(username=username)
following = Following.objects.filter(user = main_user, followed = to_follow)
is_following = True if following else False
if is_following:
Following.unfollow(main_user, to_follow)
is_following = False
else:
Following.follow(main_user, to_follow)
is_following = True
resp = {
'following': is_following,
}
response = json.dumps(resp)
return HttpResponse(response, content_type="application/json")
models.py
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def __str__(self):
return f'{self.user.username} Profile'
class Following(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed = models.ManyToManyField(User, related_name="followed")
follower = models.ManyToManyField(User, related_name="follower")
#classmethod
def follow(cls, user, another_account):
obj, created = cls.objects.get(user = user)
obj.followed.add(another_account)
print("followed")
#classmethod
def unfollow(cls, user, another_account):
obj, create = cls.objects.get(user = user)
obj.followed.remove(another_account)
print("unfollowed")
def __str__(self):
return f'{self.user.username} Profile'
profile.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{% if connection and not request.user == post_owner %}
<a type="button" class="btn btn-outline-primary" id="follow" role="button" href="{% url 'follow' post_owner.username %}">Unfollow</a>
{% elif not connection and not request.user == post_owner %}
<a type="button" class="btn btn-outline-primary" id="follow" role="button" href="{% url 'follow' post_owner.username %}">Follow</a>
{% endif %}
<p>Follower : {{follower}} Following : {{following}}</p>
<script type="text/javascript">
$("#follow").click(function(e){
e.preventDefault();
var href = this.href;
$.ajax({
url : href,
success : function(response){
if(response["following"]){
$("#follow").html("Unfollow");
}
else{
$("#follow").html("Follow");
}
}
})
})
</script>
The line:
user = User.objects.filter(username=username)
returns a collection of User objects, you should retrieve a single one with .get(…) [Django-doc]:
user = User.objects.get(username=username)

PYTHON/DJANGO: "SUser.user" must be a "User" instance

I have a problem with adding new custom user to the database. I know thare's some threads about it on the internet but I couldn't find solution for my problem. After hitting "Submit" button in registration page which template is here:
{% extends 'strona/Main.html' %}
{% block body %}
< form action="" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}
< /br >
{{ field }}
< /br >
< /br >
{% endfor %}
< button type="submit" class="btn btn-success">Submit</button >
< /form >
{% endblock %}
it keeps saying that: "Cannot assign "< SimpleLazyObject: < django.contrib.auth.models.AnonymousUser object at 0x038B5A70 >>": "SUser.user" must be a "User" instance."
Source Codes:
VIEWS.PY
class RegPanelView(View):
panel = RegPanel
template_name = 'strona/RegistrationTemp.html'
registration = None
def get(self, request):
form = self.panel(None)
return render(request, self.template_name, {'form': form})
def post(self, request):
# form = self.panel(data=request.POST)
form = self.panel(request.POST)
if form.is_valid():
# user = form.save(commit=False)
# username = form.cleaned_data['username']
password1 = form.cleaned_data['password1']
password2 = form.cleaned_data['password2']
if password1 == password2:
newuser = form.save(commit=False)
newuser.user = request.user
newuser.save()
return redirect('strona:index')
return render(request, self.template_name, {'form': form})
MODELS.PY
class SUser(models.Model):
# User = user_model()
user = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.CharField(max_length=200)
# last_login = models.DateTimeField(blank=True)
# is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
relations = models.ManyToManyField('self')
# is_anonymous = False
# is_authenticated = True
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ('', )
FORMS.PY
class RegPanel(UserCreationForm):
# password = forms.CharField(max_length=16, widget=forms.PasswordInput)
# first_name = forms.CharField(max_length=100, required=False)
# last_name = forms.CharField(max_length=100, required=False)
# is_staff = forms.BooleanField(required=False)
# birthday = forms.DateField(required=False)
class Meta:
model = SUser
fields = ['username', 'is_staff', 'first_name', 'last_name']
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data["passwosrd1"])
if commit:
user.set_password(self.cleaned_data["password1"])
user.save()
# if commit:
# user.save()
return user
SETTINGS.PY:
AUTH_USER_MODEL = 'auth.User'
EDIT
FULL ERROR TRACEBACK:
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\core\handlers\exception.py"
in inner
39. response = get_response(request)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\core\handlers\base.py"
in _get_response
187. response = self.process_exception_by_middleware(e, request)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\core\handlers\base.py"
in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\views\generic\base.py"
in view
68. return self.dispatch(request, *args, **kwargs)
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\views\generic\base.py"
in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Dawid\PycharmProjects\Zadanie\strona\views.py" in post
97. newuser.user = request.user
File
"C:\Users\Dawid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django-1.10.3-py3.5.egg\django\db\models\fields\related_descriptors.py"
in set
211. self.field.remote_field.model._meta.object_name,
Exception Type: ValueError at /index/register/ Exception Value: Cannot
assign "< SimpleLazyObject: >": "SUser.user" must be a "User" instance.
Please could someone help me out?
Kind regards.
Django lazy loads request.user so that it can be either User or AnonymousUser depending on the authentication state.
if request.user.is_authenticated(): #then request.user will be `User` instance
newuser = form.save(commit=False)
newuser.user = request.user
newuser.save()

Categories