Getting the currently logged in user from django view form - django

This is my model.
class Project(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False)
name = models.CharField(max_length=20)
total = models.DecimalField(max_digits=7, decimal_places=2, default=0)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
comission_owed = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0)
comission_paid = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0)
def __str__(self):
return self.name
And this is my model form:
class ProjectForm(ModelForm):
required_css_class = 'required'
class Meta:
model = Project
fields = '__all__'
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super().__init__(*args, **kwargs)
self.fields['user'].initial = self.user
and then here's my view:
def add_project(request):
submitted = False
if request.method == "POST":
form = ProjectForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add_project/?submitted=True')
else:
form = ProjectForm()
if 'submitted' in request.GET:
submitted = True
return render(request,
'add_project.html',
{'form': form, 'submitted': submitted}
)
I am trying to get the "user" filled by getting the logged in user but when loading the url "add_project/" where the form should load and let me submit I get an error that traces back to
KeyError at /add_project/
'user'
Request Method: GET
Request URL: http://127.0.0.1:8000/add_project/
Django Version: 3.1.2
Exception Type: KeyError
Exception Value:
'user'
Exception Location: /ArtistShop/homepage/forms.py, line 12, in init
Python Executable: /usr/local/bin/python
Python Version: 3.8.6
Python Path:
['/ArtistShop',
'/usr/local/lib/python38.zip',
'/usr/local/lib/python3.8',
'/usr/local/lib/python3.8/lib-dynload',
'/usr/local/lib/python3.8/site-packages']
Server time: Sat, 30 Jan 2021 19:16:12 -0500

You are getting this error because you are not passing the user object to your ProjectForm in the else block.
def add_project(request):
submitted = False
if request.method == "POST":
...
else:
# Here, you should pass the user object too
form = ProjectForm(user=request.user)
...

def add_project(request):
submitted = False
if request.method == "POST":
project = ProjectForm.save(commit=False)
project.user = request.user
else:
.....
you can try this to get the user, and save in projectv.user

Related

NOT NULL constraint failed: cms_viewcount.session

I am trying to get users ip address for a blog project view counts, and when the user isn't logged in a get this error
integrityError at /article/another-post-to-test-things-out/
NOT NULL constraint failed: cms_viewcount.session
Here is my views.py
# regular blog details
def blog_detail(request, slug):
template_name = 'cms/single.html'
blog = Blog.objects.get(slug=slug)
msg = False
form = CommentForm()
ip=request.META['REMOTE_ADDR']
if not ViewCount.objects.filter(blogview=blog, session=request.session.session_key):
view=ViewCount(blogview=blog, ip_address=ip, session=request.session.session_key)
view.save()
blog_views=ViewCount.objects.filter(blogview=blog).count()
if request.user.is_authenticated:
user = request.user
if blog.likes.filter(id=user.id).exists():
msg = True
context = {'blog': blog, 'msg':msg, 'form':form, "view_count":blog_views,}
try:
if request.method == 'POST':
form = CommentForm(request.POST)
comment = form.save(commit=False)
comment.blog = blog
comment.owner = request.user
comment.save()
messages.success(request, 'Your review was successfully submitted!')
return redirect('blog-detail', slug=blog.slug)
if not request.user or not request.user.is_authenticated:
return render(request, template_name, context)
else:
return render(request, template_name, context)
except:
return render(request, "cms/login-prompt.html", context)
Here is the error on my browser also
view.save() …
Local vars
Variable Value
blog
<Blog: Another Post to test things out>
form
<CommentForm bound=False, valid=Unknown, fields=(body)>
msg
False
request
<WSGIRequest: GET '/article/another-post-to-test-things-out/'>
slug
'another-post-to-test-things-out'
template_name
'cms/single.html'
view
<ViewCount:>
PLease how can I fix this error , note everthing works fine when the user is logged in
models.py
#views count models
class ViewCount(models.Model):
blogview=models.ForeignKey(Blog, related_name="view_count", on_delete=models.CASCADE)
ip_address=models.CharField(max_length=50)
session=models.CharField(max_length=50)
def __str__(self):
return str(self.ip_address)
#comment model
class Comment(models.Model):
owner= models.ForeignKey(User, on_delete=models.CASCADE, null=True)
blog= models.ForeignKey(Blog, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False)
class Meta:
ordering = ['-created']
def __str__(self):
return str(self.blog)
forms.py if need be
#comment form
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
labels = {
'body': 'Add a comment'
}
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Here is the error again
IntegrityError at /article/another-post-to-test-things-out/
NOT NULL constraint failed: cms_viewcount.session
You aren't passing the required session argument in this line:
view=ViewCount(blogview=blog, ip_address=ip, session=request.session.session_key)
Since the user isn't logged in, the value is Null.
Allow the value to be Null:
`session=models.CharField(max_length=50, null = True)`
Or generate a session for an anonymous user.

Trying to add slug to end of get_absolute_url function in models (Django)

I have a function in my Post model, a get_absolute_url which is a reverse for 'post-detail', it has kwargs for primary key , how do i add another for slug; which is in my Profile model.
At the moment I'm getting error :
NoReverseMatch at /post/26/tested123/update/
Reverse for 'post-detail' with keyword arguments '{'pk': 26}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/$']
This error occurs when I click the update button on my update post page
feed model
feed/models.py
class Post(models.Model):
description = models.TextField(max_length=255)
pic = models.ImageField(upload_to='path/to/img', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
profile model
users/models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField('Profile', blank=True)
def __str__(self):
return str(self.user.username)
def get_absolute_url(self):
return "/users/{}".format(self.slug)
views.py
#login_required
def post_detail(request, pk, slug):
post = get_object_or_404(Post, pk=pk)
user = request.user
is_liked = Like.objects.filter(user=user, post=post)
if request.method == 'POST':
form = NewCommentForm(request.POST)
if form.is_valid():
data = form.save(commit=False)
data.post = post
data.username = user
data.save()
return redirect('post-detail', pk=pk, slug=slug)
else:
form = NewCommentForm()
return render(request, 'feed/post_detail.html', {'post':post, 'is_liked':is_liked, 'form':form})
views.py
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['description', 'pic', 'tags']
template_name = 'feed/create_post.html'
def form_valid(self, form):
form.instance.user_name = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.user_name:
return True
return False
Your get_absolute_url in Post doesn't have slug in kwargs or I'm missing something? 'slug': self.user_name.profile.slug

AttributeError at /addimam 'int' object has no attribute '_meta' Django

I got this error when I'm trying to submit data in my view. Masjid is taking data from a specific login user. I cannot understand where the error is coming because my form allow my to view the specific user.
form = ImamForm(request.POST, instance=masjid)
error message is coming from that line
forms.py
class ImamForm(forms.ModelForm):
def __init__(self,user, *args, **kwargs):
super(ImamForm, self).__init__(*args, **kwargs)
try:
masjid_id = Info.objects.values_list('user_id', flat=True).get(user=user)
self.fields['masjid'].queryset = Info.objects.filter(user=masjid_id)
print(masjid_id)
except Info.DoesNotExist:
### there is not userextend corresponding to this user, do what you want
pass
class Meta:
model = Imam
exclude = ('updated_at', 'created_at', 'user')
views.ppy
class NewImam(CreateView):
# template_name = "addimam.html"
# model = Imam
# form_class = ImamForm
# #success_url = reverse_lazy('person_changelist')
# def form_valid(self, form):
# #if not UserProfile.objects.filter(recruiter=self.request.user).exists():
# p = form.save(commit=False)
# p.user = self.request.user
# p.save()
# messages.success(self.request, 'The Imam Details Has Been Added Successully!')
# return redirect('addimam')
# # else:
# # messages.warning(self.request, 'The Profile has been Added Before!')
# # return redirect('recruiter:edit_recruiter_profile')
def get(self, request, *args, **kwargs):
form = ImamForm(user=self.request.user)
context = {'form': form}
return render(request, 'addimam.html', context)
def post(self, request, *args, **kwargs):
user = self.request.user
print(user)
user = CustomUser.objects.get(email=user)
masjid = user.id
print(type(masjid))
form = ImamForm(request.POST, instance=masjid)
print(form)
if form.is_valid():
p = form.save(commit=False)
p.user = self.request.user
p.save()
messages.success(self.request, 'The Project Details Has Been Added Successully!')
return redirect('addimam')
return render(request, 'addimam.html', {'form': form})
models.py
class Imam(models.Model):
CERTIFICATE = (
('PhD', 'PhD'),
('MSc', 'MSc'),
('Bsc', 'Bsc'),
)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
masjid = models.ForeignKey(Info, related_name='imam', on_delete=models.CASCADE)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
imam_address = models.TextField(blank=False, null=False)
phone_no = models.CharField(max_length=20)
certificate = models.CharField(max_length=50, choices=CERTIFICATE)
occupation = models.CharField(max_length=50, blank=False, null=False)
no_of_wives = models.IntegerField(blank=False, null=False)
no_of_children = models.IntegerField(blank=False, null=False)
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
Since you have override the __init__(...) method, Django expects the arguments in the different order.
So change
form = ImamForm(request.POST, instance=masjid)
to
form = ImamForm(masjid,request.POST)

Qualified input but checked invalid by `form.is_valid`

I input qualified content to form but was checked as invalid by form.is_valid,
Here is my views:
I add print(request.POST) # test input to check posted successfully, and print("form is invalid.") #assert invalid to check if it's a valid form,
class CommentCreateView(View):
template_name = "article/article_detail.html"
def get(self, request, pk):
return redirect(f"/article/detail/{ pk }")
def post(self, request, pk):
self.article = Article.objects.get(id=pk)
form = CommentForm(request.POST)
print(request.POST) # test input
if form.is_valid():
print("form is valid.") #assert valid
comment = form.save(commit=False)
print(f"Comment: {form.cleaned_data}")
comment.owner = request.user
comment.article = self.article
comment.status = 0
comment.save()
return redirect(f"/article/detail/{ pk }")
else:
print("form is invalid.") #assert invalid
comments = (Comment.objects
.filter(article=self.article, status=0)
)
context = {'article': self.article,
'comments':comments,
"form": form}
return render(request, self.template_name, context)
The Comment model data`:
class Comment(models.Model):
STATUS = (
(0, 'normal'),
(-1, 'deleted'),
)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
comment = models.TextField() # set the widget
status = models.IntegerField(choices=STATUS)
date_created = models.DateTimeField(default=datetime.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.comment
And the forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment', 'date_created']
widgets = {'comment': forms.Textarea(attrs={'cols': 80})}
The error report:
Django version 1.11.13, using settings 'forum.settings'
Starting development server at http: // 127.0.0.1: 8001/
Quit the server with CONTROL-C.
<QueryDict: {'csrfmiddlewaretoken': ['jL9aDh0cSNgvlmGWtI5sogFlruIvLh4rHqt0jll2V3H70Bel35IDFq6cgkWhAJHK'], 'comment': ['issue a test']} >
form is invalid.
[09/Jun/2018 13:12:32] "POST /article/comment/create/17 HTTP/1.1" 200 4183
It checked that the form is invalid.
How to solve such a problem?

Can't get owner as foreign key to my model -- django

I'm trying to do a form so a user can upload a video, the problem is i can't get current user or it's id as a foreign key on my video model
Error: IntegrityError
Exception Value: (1048, "Column 'owner_id' cannot be null")
How can i solve the problem please, i looked at django documentation but doesn't find answer.
My models.py:
class Videowtm(models.Model):
name = models.CharField(max_length=50, blank=True)
description = models.CharField(max_length=255, blank=True)
uploaded_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User)
video = models.FileField(upload_to='videos/')
My forms.py:
class VideowtmForm(forms.ModelForm):
class Meta:
model = Videowtm
fields = ('name', 'description', 'video', )
My views:
#login_required
def model_form_upload(request):
if request.method == 'POST':
form = VideowtmForm(request.POST, request.FILES)
form.owner = request.user
if form.is_valid():
form.save()
return redirect('home')
else:
form = VideowtmForm()
return render(request, 'model_form_upload.html', {
'form': form
})
Try this one:
first add blank=True to the owner in your model:
###No need for this if you don't include it in your form fields###
class Videowtm(models.Model):
name = models.CharField(max_length=50, blank=True)
description = models.CharField(max_length=255, blank=True)
uploaded_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, blank=True)
video = models.FileField(upload_to='videos/')
and then:
views.py:
#login_required
def model_form_upload(request):
if request.method == 'POST':
form = VideowtmForm(request.POST, request.FILES)
if form.is_valid():
video = form.save(commit=False)
video.owner = request.user
video.save()
return redirect('home')
else:
form = VideowtmForm()
return render(request, 'model_form_upload.html', {
'form': form
})