Django: Show data from current user - python

I'm having trouble displaying data from current user. It shows all the shifts that was given to other users also. I don't have any idea how to do this. Below is my code.
models.py
class User(models.Model):
user_name = models.CharField(max_length=32, unique=True)
pass_word = models.CharField(max_length=150)
is_active = models.BooleanField(default=True)
class Rostering(models.Model):
name = models.CharField(max_length=64)
begin_time = models.TimeField(default="")
end_time = models.TimeField(default="")
is_active = models.BooleanField(default=True)
class RosteringUser(models.Model):
rostering_user = models.ForeignKey(Rostering, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
views.py
def my_shift(request):
if request.method == 'GET':
queryset = RosteringUser.objects.all()
if queryset:
for obj in queryset:
id = Rostering.objects.get(rosteringuser=obj.id)
obj.id = id
return render(request, 'my_shift.html', {'queryset': queryset})
my_shift.html
{% for obj in queryset %}
<tr>
<td>{{ obj.user.user_name }}</td>
<td>{{ obj.id.name }}-{{ obj.id.begin_time }}</td>
<td>{{ obj.id.name }}-{{ obj.id.end_time }}</td>
</tr>
{% endfor %}
Thank you in advance!

Simply you can try like this:
if queryset:
for obj in queryset:
id = Rostering.objects.get(rosteringuser=obj.id)
obj.id = id
querysets = obj
return render(request, 'my_shift.html', {'querysets': querysets})
And in templates:
{% for object in querysets %}
<tr>
<td>{{ object.user.user_name }}</td>
<td>{{ object.id.name }}-{{ object.id.begin_time }}</td>
<td>{{ object.id.name }}-{{ object.id.end_time }}</td>
</tr>
{% endfor %}

def my_shift(request):
if request.method == 'GET':
rost_id = RosteringUser.objects.filter(user_id=request.user.id).values("rostering_user_id").first()
if rost_id :
data = Rostering.objects.get(id=rost_id['rostering_user_id'])
return render(request, 'my_shift.html', {'queryset': data })
in template you can directly display logged in username {{ request.user.first_name }}

Related

Cannot access foreign key elements in html templates DJANGO

Views:
def search_devis(request):
devis = Devis.objects.all()
commercial = User.objects.all()
client = Client.objects.all()
context={
'devis': devis,
'commercial': commercial,
'client_': client,
}
return render(request, "manage_devis/search_devis.html",context )
Models:
class Devis(models.Model):
titre = models.CharField(max_length=30, )
date_ecriture = models.DateField(auto_now_add=True)
date_expiration = models.DateField()
client = models.ForeignKey(Client, name="CLIENT_FK", default=1 ,on_delete=models.SET_DEFAULT)
total = models.DecimalField(max_digits=10, decimal_places=2)
commercial = models.ForeignKey(User, name="COMMERCIALFK", default=1 ,on_delete=models.SET_DEFAULT)
def __str__(self):
return "DV"+str(self.pk)
Templates:
{% for devis_ in devis %}
<tr>
<th scope="row">DV{{devis_.id }}</th>
<td>{{ devis_.date_ecriture }}</td>
<td>{{ devis_.date_expiration }}</td>
<td>{{devis_.client.nom}}</td>
<td>{{ devis_.total}} DH</td>
<td>{{ devis_.commercial.last_name}}</td>
</tr>
{% endfor %}
I can't display the attributes of the foreign key object, no value in it.
nothing appear in the column.
I'm using postgresql database.
First of all, try removing the name="CLIENT_FK" in the model and then make the migration (python manage.py makemigrations and python manage.py migrate).
Your model now should look something like:
class Devis(models.Model):
titre = models.CharField(max_length=30, )
date_ecriture = models.DateField(auto_now_add=True)
date_expiration = models.DateField()
client = models.ForeignKey(Client, default=1 ,on_delete=models.SET_DEFAULT)
total = models.DecimalField(max_digits=10, decimal_places=2)
commercial = models.ForeignKey(User, default=1 ,on_delete=models.SET_DEFAULT)
def __str__(self):
return "DV"+str(self.pk)
After that, you can iterate in your forloop, please, avoid using something like devis_. I suggest you to use a forloop like this:
{% for dev in devis %}
<tr>
<th scope="row">DV{{dev.id }}</th>
<td>{{ dev.date_ecriture }}</td>
<td>{{ dev.date_expiration }}</td>
<td>{{dev.client.nom}}</td>
<td>{{ dev.total}} DH</td>
<td>{{ dev.commercial.last_name}}</td>
</tr>
{% endfor %}
Try {% for devis in object.devis_set.all %}
And don’t use _ at the end of the devis

I can't get the notifications by i.d after saving it as a many to many field

I have previously figured out how to send and save notifications by many to many fields to send to users, now i can't specifically call the notifications by current user logged in i.d.
Models.py
class Notifications(models.Model):
id=models.AutoField(primary_key=True)
sent_to = models.ManyToManyField(CustomUser)
message = models.TextField(null=True)
message_reply = models.TextField(null=True)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
The notifications_sent_to is the created table after I created the many to many save
Notifications_sent_to table (which is not created in the models)
Notifications table (which stores the message)
Views.py
def add_notification(request):
notifs = Notifications.objects.all()
users = CustomUser.objects.filter(is_staff=True)
if request.method == 'POST':
form = AddNotifForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.message_reply = "none"
instance.save()
form.save_m2m()
sent_to = form.cleaned_data.get('sent_to')
messages.success(request, f'Message has been successfully sent .')
return redirect('add_notif')
else:
form = AddNotifForm()
context={
'notifs' : notifs,
'form' : form,
'users' : users,
}
template_name ='main-admin/add-notif.html'
return render(request, template_name, context)
Forms.py
class AddNotifForm(forms.ModelForm):
sent_to = forms.ModelMultipleChoiceField(
queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True),
widget=forms.CheckboxSelectMultiple,
required=True)
class Meta:
model = Notifications
fields = ['sent_to', 'message']
Templates view
{% for sent_to_users in sent_to_users %}
<tr>
<td>{{ sent_to_users.id }}</td>
<td>{{ sent_to_users.sent_to }}</td>
<td>{{ sent_to_users.message }}</td>
<td>
{% if sent_to_users.message_reply == "none" %}
<button type="button" class="btn btn-primary reply_open_modal" data-bs-toggle="modal" data-bs-target="#replyModal">Reply</button>
{% else %}
{{ sent_to_users.message_reply }}
{% endif %}
</td>
<td>{{ sent_to_users.created_at }}</td>
</tr>
{% endfor %}

How to assign few objects to one user

I want to have template page with object(orders) list (another list, for another user). Like relations one to many. Where do i need to define that objects(order)(for exemple by id: order_id=1 and order_id=3) is assigned to user(driver) with id=1 etc?
I was trying to create Driver class and than set atribute driver in order Class like this.
form.py
class OrderForm(forms.Form):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'.")
airport = forms.ChoiceField(choices=AIRPORT_CHOICES) ### Jeśli lotnisko jest celem podróży
direction = forms.ChoiceField(choices=DIRECTION_CHOICES) ## to pick_up < plane i odwrotnie!!!
adress = forms.CharField()
client = forms.CharField()
telephone = forms.CharField(validators=[telephone_regex])
flight_number = forms.CharField()
plane = forms.DateTimeField(input_formats=['%Y-%m-%d'])
pick_up = forms.DateTimeField(input_formats=['%Y-%m-%d'])
gate = forms.CharField()
company = forms.ChoiceField(choices=COMPANY_CHOICES)
driver = forms.ChoiceField(choices=DRIVER_CHOICES)
models.py
class Driver(models.Model):
name = models.CharField(max_length=30)
tel = models.CharField(max_length=17)
class Order(models.Model):
telephone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format:
'+999999999'.")
airport = models.CharField(max_length=10, choices=AIRPORT_CHOICES)
direction = models.CharField(max_length=7, choices=DIRECTION_CHOICES)
adress = models.CharField(max_length=100, null=False, blank=False)
client = models.CharField(max_length=50, null=False, blank=False)
telephone = models.CharField(validators=[telephone_regex], max_length=17, blank=False)
flight_number = models.CharField(max_length=7)
plane = models.DateTimeField(null=True)
pick_up = models.DateTimeField(null=True)
gate = models.CharField(max_length=10, null=True, blank=True)
comapny = models.CharField(max_length=50, choices=COMPANY_CHOICES)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE)
order_list.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<h1>Hi {{ user.username }}! Have a good tips!</h1>
{% else %}
<h1>You have to login to see your orders list</h1>
{% endif %}
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">client</th>
<th scope="col">telephone</th>
<th scope="col">flight number</th>
<th scope="col">airport</th>
<th scope="col">direction</th>
<th scope="col">adress</th>
<th scope="col">gate</th>
<th scope="col">plane</th>
<th scope="col">pick up</th>
</tr>
</thead>
{% for order in orders %}
<tbody>
<tr>
<th scope="row">{{ order.id }}</th>
<td>{{ order.client }}</td>
<td>{{ order.telephone }}</td>
<td>{{ order.flight_number }}</td>
<td>{{ order.airport }}</td>
<td>{{ order.direction }}</td>
<td>{{ order.adress }}</td>
<td>{{ order.gate }}</td>
<td>{{ order.plane }}</td>
<td>{{ order.pick_up }}</td>
<td>{{ order.driver }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{% endblock %}
views.py
class OrderView(View):
def get(self, request, id):
orders = Order.objects.get(id=id)
users = User.object.get(id=id)
ctx = {
'orders': orders,
'users': users
}
return render(request, 'order.html', ctx)
class OrderListView(View):
def get(self, request):
form = OrderForm()
orders = Order.objects.all()
ctx = {'form': form, 'orders': orders}
return render(request, 'orders/order_list.html', ctx)
class AddOrderView(View):
def get(self, request):
form = OrderForm()
return render(request, 'orders/add_order.html', {'form': form})
def post(self, request, *args, **kwargs):
form = OrderForm(request.POST)
if form.is_valid():
order = Order.objects.create(airport=form.cleaned_data['airport'],
direction=form.cleaned_data['direction'],
adress=form.cleaned_data['adress'],
client=form.cleaned_data['client'],
telephone=form.cleaned_data['telephone'],
flight_number=form.cleaned_data['flight_number'],
plane=form.cleaned_data['plane'],
pick_up=form.cleaned_data['pick_up'],
gate=form.cleaned_data['gate'],
driver=form.cleaned_data['driver'])
return render(request, 'orders/add_order.html', {'form': form})
I expect to get form when i can input new order and select driver but I'm geting this:
http://dpaste.com/0PD363H

Django - submit multiple forms in a view

I have two forms in my views, when I hit on save it's not working properly, when I want to display on my templates what I saved not showing as expected.
Here's what I have:
views.py
def index(request):
queryset = Personinfo.objects.all()
queryset2 = Person.objects.all()
qs = chain(queryset,queryset2)
form = personform(request.POST or None)
form2 = personinfoform(request.POST or None)
context = {
"queryset": queryset,
"queryset2": queryset2,
"qs": qs,
"form2":form2,
"form":form,
}
form2_valid = form2.is_valid()
form_valid = form.is_valid()
if form2_valid and form_valid:
a = form2.save()
b= form.save(commit=False)
b.ForeignkeytoA = a
b.save()
return render(request, "index.html", context)
index.html
<form method="POST" action="">{% csrf_token %}
{{form2.as_p}}
{{form.as_p}}
<input type="submit" value="Save!" />
</form>
<table >
<tr>
<th>Name</th>
<th>Address</th>
<th>Number</th>
<th>Hobbies</th>
</tr>
{% for item in qs %}
<tr>
<td>{{ item.name }}</td> #form2
<td>{{ item.address }}</td> #form1
<td>{{ item.phone_number }}</td> #form1
<td>{{ item.address }}</td> #form1
</tr>
{% endfor %}
</table>
models.py
class Personinfo(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Person(models.Model):
person = models.ForeignKey(Personinfo)
address = models.TextField()
phone_number = models.CharField(max_length=128)
hobbies =models.CharField(max_length=128)
def __str__(self):
return self.person
my output:
As you can see my table isn't showing my items as expected.
Is there a possible way to show every item in the same row?
Two errors are present. If I understand right, you're expecting the data from a Person instance and the data from its accompanying PersonInfo instance to print on the same line. However, you're trying to achieve this by using chain, which is not joining the querysets based on their relationship, but rather concatenating them blindly.
So if Person.objects.all() returns a queryset which contains the following data
id person address phone_number hobbies
1 1 a a a
2 2 5 5 5
and PersonInfo.objects.all() returns a queryset which contains
id Name
1 aaa
2 aa
chain combines them as
id person name address phone_number hobbies
1 aaa
2 aa
1 1 a a a
2 2 5 5 5
Instead, you should utilize the relationship between the models. If you pass only the Person queryset as context to your template, you could write
{% for p in persons %}
<tr>
<td>{{ p.person.name }}</td>
<td>{{ p.address }}</td>
<td>{{ p.phone_number }}</td>
<td>{{ p.hobbies }}</td>
</tr>
{% endfor %}
--
Additionally you are setting the Personinfo related instance incorrectly when you save your forms. By using b.ForeignkeytoA you are creating a new variable as a member of the object b called ForeignkeytoA, which has nothing to do with the Personinfo relationship. To set the related Personinfo, you should reference the name of the foreign key field, person. To correct this, that segment should be
# ...
b = form.save(commit = False)
b.person = a
b.save()
# ...

Looping in django template with variable parameter

I want to get all the details of class Material where user=user_id
Here is the models.py:
class Material(models.Model):
subject = models.CharField(max_length=10)
topic = models.CharField(max_length=50)
user = models.IntegerField()
and my views.py:
def add_material(request):
c = {}
c.update(csrf(request))
if 'user_session' in request.session:
user_id = request.session['user_session']
material_array = Material.objects.filter(user=user_id).values()
materials_len = len(material_array)
c['m_len'] = materials_len
for i in range(0, materials_len):
c['material_id_'+str(i)] = material_array[i]
return render_to_response('add_material.html',c)
else:
return HttpResponseRedirect('/user')
and my add_material.html is:
{% for i in range(m_len) %}
<tr>
{% for j in material_id_+str(i) %}
{{j.subject}}
{{j.topic}}
{% endfor %}
</tr>
{%endfor%}
So I am getting error in template, how to insert variable in for loop?
This how I would do it.
views.py
def add_material(request):
c = {}
c.update(csrf(request))
if 'user_session' in request.session:
user_id = request.session['user_session']
material_array = Material.objects.filter(user=user_id)
c.update({'materials': material_array})
return render_to_response('add_material.html', c)
else:
return HttpResponseRedirect('/user')
template
{% for material in materials %}
<tr>
<td>{{ material.subject }}</td>
<td>{{ material.topic }}</td>
<td>{{ material.user.username }}</td>
</tr>
{% endfor %}
You can include any user field you like.

Categories