How to find Only the logged in user content in django? - django

class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return '#{}'.format(self.username)
class placement(models.Model):
name=models.CharField(max_length=150, blank=True, null=True)
ad_space=models.CharField(max_length=100, blank=False, null=False)
PID_TYPE = (
('FN','FORMAT_NATIVE'),
('FNB','FORMAT_NATIVE_BANNER'),
('FI','FORMAT_INTERSTITIAL'),
('FB','FORMAT_BANNER'),
('FMR','FORMAT_MEDIUM,RECT'),
('FRV','FORMAT_REWARDED_VIDEO'),
)
format = models.CharField(max_length=3,choices = PID_TYPE,default = 'FN',blank=False, null=False)
pid=models.CharField( max_length=50,default='',blank=False, null=False)
cpm=models.IntegerField(default=0,blank=False, null=False)
ADS_TYPE=(
('FB','FACEBOOK'),
('G','GOOGLE'),
)
source=models.CharField(max_length=2,choices=ADS_TYPE,default='FB',blank=False, null=False)
comments=models.TextField(default='',blank=False, null=False)
objects=models.Manager()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("dashapp:disp")`
Now what should i do to only get only the logged in user content to be displayed on the template.As currently all the stored data is being fetched . That is logged out user for data is being displayed.
I'm Basically a beginner so i dont have any advance idea about this.
Full explanation are needed.

You can access the logged in user like this:
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
In django, the logged in user has an attribute is_authenticated which is a boolean value. If user is logged in, it gives True, else False.
Update
If you meant to see the placement model values in template for current user, you need make some relations with the user to placement. So you need to update the placement model:
class placement(models.Model):
user = models.ForeignKey(User, null=True, default=None)
.... # rest of the fields
And save user info to placement in views:
class SomeCreateView(CreateView):
...
def form_valid(self, form):
form.instance.user = User.objects.get(id = self.request.user.id)
return super(SomeCreateView, self).form_valid(form)
and get placements of a user in view like this:
placements = placement.objects.filter(user=request.user)

Related

Django - Query or for loop with exeption based on login user

Hy,
I have a page that it can be accesed only if the user have a magiclink(made with django-sesame). After open that page using that maginlink i know witch user is, because when link is generated it incorporate the user information and include in that link.
So, the issue/question : in that page i want to show the name and departemnt for all users exept the users with the same department as the login user. I don't know how to make the query in view or forloop in template with that rule.
With another words: if the user logged in is from department "hr" i want to show in the template all the users for all department except those from "hr".
Please help me with a solution.
models.py
class Profil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
username = models.CharField(max_length=200, blank=True, null=True)
nume = models.CharField(max_length=200, blank=True, null=True)
departament = models.CharField(max_length=200, blank=True, null=True)
view.py
#authenticate
def pagina_secreta(request):
utilizatori = User.objects.all()
context = {'utilizatori' : utilizatori}
return render(request, 'feedback/pagina_secreta.html', context)
template.html
{% for d in utilizatori %}
{{d.profil.nume}} {{d.profil.departament}} <br><br>
{% endfor %}
Thank you
You can filter out the department of that person with:
#authenticate
def pagina_secreta(request):
utilizatori = User.objects.exclude(
profil__departament=request.user.profil.departament
)
context = {'utilizatori' : utilizatori}
return render(request, 'feedback/pagina_secreta.html', context)

Django Template Language: Create conditional for entire Model (not record by record)

Newbie problem. Per the following script in a template ...
{% if request.user not in Result %}
<p>You have no account in the system.</p>
{% endif %}
... the statement "You have no account in the system." is appearing 100 times on screen---because there are 100 records and therefore the condition is being checked 100 times.
Is there a way to modify the script so that the statement appears just once? Meaning, it checks the entire database once for evidence that request.user appears anywhere in the model in aggregrate (and not whether it appears in each of the 100 records in the database)?
Maybe there's an easier/better way to do this in views.py vs a template, but that's beyond my knowledge. Thank you. Below is the model called Result.
models.py
class Result(models.Model):
custom_user = models.ForeignKey(CustomUser, default=None,
null=True, on_delete=models.SET_NULL)
decision = models.ForeignKey(Decision, default=None,
null=True, on_delete=models.SET_NULL,
verbose_name="Decision")
vote_eligible = models.BooleanField(default=True)
vote = models.CharField(default="", max_length=100,
blank=True, verbose_name="Your
Vote:")
voted_already = models.BooleanField(default=False)
#staticmethod
def get_absolute_url():
return "/home"
def __str__(self):
return f"{self.custom_user}"
views.py
class VoteForm(LoginRequiredMixin, CreateView):
model = Result
form_class = VotingForm
template_name = 'users/vote_form.html'
def get_context_data(self, **kwargs):
context = super().get_context_data()
context["Result"] = Result.objects.all()
return context
forms.py
class VotingForm(forms.ModelForm):
class Meta:
model = Result
fields = ['decision', 'vote']
views.py
Since the requirement is to display whether the logged in user has account in 'Result' model or not. I have filtered the rows specific to the user. You can loop over the user_specific in your template. If user is present in 'Result' model 'user_specifc' will have elements. If user is not present in 'Result' table, 'user_specific' will be empty. In you template, you can check whether 'user_specific' is empty list or not.
class VoteForm(LoginRequiredMixin, CreateView):
model = Result
form_class = VotingForm
template_name = 'users/vote_form.html'
def get_context_data(self, **kwargs):
context = super().get_context_data()
context["Result"] = Result.objects.all()
context['user_specific'] = Result.objects.filter(custom_user=self.request.user)
return context
template.html
{% if not user_specific %}
<p>You have no account in the system.</p>
{% endif %}

How to add condition to a manytomany relationship

I'm a little new to Django, so my question may be basic, but bare with me. Let's say I'm sharing my posts with some of my friends (who are manytomany relation with the post), but also giving an extra condition for whether they can comment on it, or not. This condition, together with the name of the user to be shared with are submitted through a forum. Now my problem is that I don't know how/where to save this condition. I will show you some of my code.
Models.py
class Task(models.Model):
name = models.CharField(max_length=50)
text = models.TextField()
deadline = models.DateTimeField()
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='taskset')
shared = models.ManyToManyField(User, blank=True, related_name = 'shared_list')
def __str__(self):
return f"{self.name}-{self.user.username}"
class Comment(models.Model):
text = models.TextField()
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments')
created = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.user.username}-{self.task}"
Share form html
{% extends 'base.html'%}
{% load crispy_forms_tags %}
{% block content %}
<h3>Enter the Username of the Friend you want to share with</h3>
<form method="POST">
{% csrf_token %}
{{form|crispy}}
<input type="submit", value="Share">
</form>
{% endblock content %}
And the view processing it
def share(request, id):
task = Task.objects.get(id = id)
if request.method == 'POST':
share_with = User.objects.get(username = request.POST['username'])
if share_with is not None:
task.shared.add(share_with)
task.save()
return redirect('index')
else:
form = ShareForm()
return render(request, 'share.html', {'form':form})
Thanks a lot, I've been stuck for two hours, PLEASE HELP!

Retrieve a user list from a manydomanyfield with information from an intermediate table

it's been a few hours since I tried to retrieve a list of users with the information of an intermediate table.
So I have a workspace model that is a manytomanyfield with users
There is also an intermediary table to differentiate the classic users and the workspace manager
I would like to display the list of users and add a small icon symbolizing the managers in the list.
But unfortunately it seems difficult for Django, to display both the list of users of the workspace with the information of the intermediate table.
In any case I look at the documentation of Django I have not managed to find how to do.
models.py
class Workspace(models.Model):
name = models.CharField(max_length=250, verbose_name="Nom du workspace")
members = models.ManyToManyField(User, through='Membership', verbose_name="Membres du workspace")
token = models.CharField(max_length=500) # token statique
join_token = models.CharField(max_length=500) # token dynamique
join_token_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
payday = models.DateField(max_length=10, verbose_name="Jour de paye", null=True, blank=True)
planning_image = ProcessedImageField(upload_to='planning',
null=True,
blank=True,
processors=[ResizeToFill(1299, 937)],
format='JPEG',
options={'quality': 100})
planning_thumbnail = ImageSpecField(source='planning_image',
processors=[ResizeToFill(280, 202)],
format='JPEG',
options={'quality': 100})
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('create-workspace')
class Membership(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)
is_manager = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
views.py
#login_required
def workspace_detail(request, token):
ins_workspace = get_object_or_404(Workspace, token=token)
list_members = ins_workspace.members.all()
for member in list_members:
if member == request.user:
current_user = Membership.objects.get(workspace=ins_workspace, user=request.user)
context = {
'name': ins_workspace.name,
'token': ins_workspace.token,
'list_members': list_members,
'payday': ins_workspace.payday,
'is_manager': current_user.is_manager,
}
return render(request, 'workspace/workspace_detail.html', context)
else:
return HttpResponseForbidden()
template.html
{% for item in list_members %}
{{ item.username }}
{% endfor %}
This is what I want:
template.html
{% for item in list_members %}
{% item.is_manager %}
{{ item.username }} (♔)
{% else %}
{{ item.username }}
{% endfor %}
You can do it like this:
Update Membership model with related name:
class Membership(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="membership")
workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE)
is_manager = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
Then you can update your view like following:
from django.db.models import F
#login_required
def workspace_detail(request, token):
ins_workspace = get_object_or_404(Workspace, token=token)
list_members = ins_workspace.members.all().annotate(is_manager=F('membership__is_manager'))
context = {
'name': ins_workspace.name,
'token': ins_workspace.token,
'list_members': list_members,
'payday': ins_workspace.payday,
'is_manager': request.user.membership.get(workspace=ins_workspace).is_manager,
}
return render(request, 'workspace/workspace_detail.html', context)
That should do the trick.
Here what I have done is that, I am using a reverse relation to get is_manager value from membership model. I am annotating that value in the queryset using F.

can't use a field of the database in django template

I have a database like this:
from django.db import models
class User(models.Model):
firstName = models.CharField(max_length=30, blank=False, default=None)
lastName = models.CharField(max_length=30, blank=False, default=None)
email = models.EmailField(max_length=100, blank=False, default=None)
password = models.CharField(max_length=100, blank=False, default=None)
score = models.IntegerField(default=0)
in views.py I want to send a user that currently logged in and show its informations from DB at template.
my views.py:
user = User.objects.filter(email=request.POST['email'])
#some code ....
context = RequestContext(request, {
'user': user[0]
})
return HttpResponse(template.render(context))
my template :
{% if user %}
Wellcome {{ user.firstName }}
{% endif %}
but I don't see anything after welcome.also when I use this:
{% if user %}
Wellcome {{ user }}
{% endif %}
I see welcome anonymousUser where I am wrong ?
You cannot use user as the context variable, as it conflicts with the user object that is injected into the context by the processor
django.contrib.auth.context_processors.auth
Now, to fix your issue, rename user to user_obj or something which makes more sense.
Read more here
Based on the behavior you are describing you are likely not getting any objects returned from the call to filter:
user = User.objects.filter(email=request.POST['email'])
I would look at the value that is returned from request.POST['email'] and making sure that value is in your datbase as the starting point.
Also, you should be aware that the filter function returns a QuerySet and not a User object. If you want to retrieve a unique User object you can use the get function instead.