Django showing in a template a ManytoManyField that is into a Dictionary - python

The thing is quite simple but i don't know how to do it.
I got the next models.py
class ElementoDeRed(models.Model):
IP_Address = models.CharField(max_length=200, primary_key= True)
MAC_Address = models.CharField(max_length=200)
offset_bytes = models.CharField(max_length=200)
transfered_bytes = models.CharField(max_length=200)
time = models.CharField(max_length=200)
previous_bytes = models.CharField(max_length=200)
previous_previous_bytes = models.CharField(max_length=200)
class Meta:
verbose_name = 'Dispositivos en mi nube'
verbose_name_plural = 'Dispositivos en mi nube'
def __unicode__ (self):
return smart_unicode(self.IP_Address)
class Register(models.Model):
user = models.ForeignKey(User)
network_element = models.ManyToManyField(ElementoDeRed)
registered_date = models.DateTimeField(null=True,blank=True)
def __unicode__ (self):
#return smart_unicode(self.network_element)
return smart_unicode("%s: %s" % (self.user,self.network_element.all()[0]))
As you can see, Register is using a ElementoDeRed element to storage on itself.
The thing is that i want to show in my template something like :
"The user <'user'> has the next device configured with this IP : <'IP_Address'>, Mac: <'Mac_Address'> ...."
What I am rendering on the template is a var called "dict_username_registers", is a dictionary witch key value is the username and the items asocciate to it are the "registers" fields.
But im getting something like :
david: [<Register: david: 10.0.0.3>, <Register: david: 10.0.0.1>] , Alice: <Register: Alice: 10.0.0.2>]
How can i access to that field in HTML????
Thank you! Let me know if u need something else!

you can iterate over the elements of dict_username_registers like this
{% for register in dict_username_registers %}
accessing date {{register.registered_date}}
{% endfor %}
you car read more about those tags here

Related

how to show my post only to my friends in django

I want to show my post only to my friends, How can I filter my post only to my friends? I have tried to filter in html code but as my friends get more, it repeats my post more (I mean repeat one post few times )
My models.py
class PostUser(models.Model):
posttype = models.CharField(max_length=3000, default='postuser')
content = models.TextField(null = True, blank= True)
media_image = models.FileField(null = True, blank= True)
media_video = models.FileField(null = True, blank= True)
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
datetime = models.DateTimeField(auto_now_add=True)
like = models.IntegerField(null=True, blank=True)
comment = models.IntegerField(null=True, blank=True)
share = models.IntegerField(null=True, blank=True)
user_pk = models.IntegerField()
class Friends(models.Model):
# Sender
friend_one = models.IntegerField()
# Reciver
friend_two = models.IntegerField()
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
datetime = models.DateTimeField(auto_now_add=True)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
and this is my views.py
allmyfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk))
You can do it like :-
models.py
Choices = (
(True,'Friends can see Post'),
(False,'Friends cannot see Post'),
)
class Friends(models.Model):
...................
only_friends = models.BooleanField(max_length=30,choices=Choices,default=True)
Accessing Friends model objects in views Because our BooleanField is in Friends model so we have to access Friends model first to access only_friends BooleanField
def some_view(request,user_id):
allmyfriends = get_object_or_404(Friends,user_user_id)
p = request.user
you = p.user
friends = p.friends.all()
context = {'allmyfriends':allmyfriends,'friends':friends}
return render(request, 'mains:your_template.html', context}
urls.py
path('some_view/<int:user_id>/',views.some_view,name='some_view'),
your_template.html
Now do work carefully here.
In showing post, I assume that you're using loop for showing all of users Post. like :-
{% for posts in post %}
{% if posts.user.only_friends == True and posts.user in request.user.friends.all %}
{{ post.posttype }}
{% endif %}
{% endfor %}
Note :- This FrontEnd will only work after you set your PostUser ForeignKey relationship with User like :-
from django.contrib.auth.models import User
class PostUser(models.Model):
..................
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',unique=True)
Also Set your Friends model ForeignKey RelationShip with User
class Friends(models.Model):
.............
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',unique=True)
Explanation :-
In models.py :- I add a BooleanField with Choices.
In views.py :- I access Friends model to access its objects with user_id. ( Check carefully in template urls while using user_id )
In template :- I use a for loop to show all the Posts. AND In for loop i started if statement that If the user who posted a post is in request.user's friends and have BooleanField True then Post will show and if request.user isnot in posted user then the post will not be shown.
#Ramin Zamani- Your friend model is messed up. Have a look at this.
Rename your model Friends to UserFriend. It's a model that shows the relation between 2 entities - The user and his/her friends/followers. The model name shouldn't be plural.
from django.conf import settings
class UserFriend(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
friend = models.ForeignKey(settings.AUTH_USER_MODEL)
................
Also, I could have used a many-to-many relation but I prefer the foreign key relation. It's up to your preference.
Your post model needs to be fixed
class Post(models.Model):
created_by= models.ForeignKey(settings.AUTH_USER_MODEL)
...............
And if you want only specific users to let's say view a post then you can do the following.
in your views.py
post = Post.objects.get(slug=self.kwargs.get('name'))
#to check if the user trying to access the post is a friend of the postcreator user.
friend = UserFriend.objects.get(user=post.created_by,friend=self.request.user)
if friend:
render()
else:
return HttpResponseForbidden()

query ForeignKey of model

**I want get all orders of customer whose id = 3 **
----------------------------------------------------------------
class customer(models.Model):
name = models.CharField(max_length=200,null= True)
phone = models.CharField(max_length=200,null= True)
email = models.CharField(max_length=200,null= True)
date_created = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return self.name
class order(models.Model):
STATUS = (
('pending','pending'),
('out for delivery','out for delivery'),
('deliveried','deliveried')
)
date_created = models.DateTimeField(auto_now_add=True,null=True)
status = models.CharField(max_length = 200 , null=True,choices=STATUS)
customer= models.ForeignKey(customer,null=True,on_delete=models.SET_NULL)
product = models.ForeignKey(product,null=True,on_delete=models.SET_NULL)
There are two possible ways to do it.
One way is from order objects:
order.objects.filter(customer__id=3)
Second from customer objects:
customer.objects.get(id=3).order_set.all()
its actually quite simple.
just do the following
order.objects.filter(customer_id=3)
you can use the filter method provided by Django model class
This method returns all the orders in a query-set object.
so one more question might raise is where we should actually use this method?
You can actually do this in your views.py
Example:
urls.py
path('my_view/<int:id>',views.my_order,name="my_order")
views.py
def my_order(request,id):
my_orders = order.objects.filter(customer_id=3) #this will return a query set
return render(request,'index.html',{'my_orders':my_orders})
index.html
<body>
{% for o in my_orders %}
{{o}}
{% endfor %}
</body>

How to fix trouble with urls better django

I have a section residential interiors on the site, so the typical url looks like this https://caparolcenterspb.ru/decision/livingrooms/kitchen/provans/ (room and style)
However different rooms may have the same styles and when searching for styles in views.py it may output several styles and an error
views.py
selected_room = Room.objects.get(slug=rmslg)
style = Style.objects.get(slug=stslg)
When you try to replace slug with different styles depending on the room(for example, provans_kitchen), an error occurs in the template(just put provans by default will not work)
residentialInteriors.html
{% for room in all_rooms %}
<li class="menu__item menu__item_interiors">{{ room.name }}</li>
{% endfor %}
I have 2 solution ideas(preferably 2):
either change stslg in template by default to 'provans_' + str(room. slug), but this line does not work(especially not the fact that provans will be everywhere)
either search for style in views.py not only for stslg, but also for rmslg, but for this in the style model, you need to create a room field inherited from the room model, which also does not work for me, since Room is declared further than Style
models.py
class Style(models.Model):
name = models.CharField(max_length=30)
full_name = models.CharField(max_length=50)
slug = models.SlugField()
img = models.ImageField(upload_to='img/')
walls = models.TextField()
floor = models.TextField()
roof = models.TextField()
def __str__(self):
return self.full_name
class Meta:
verbose_name = 'Стили'
verbose_name_plural = 'Стили'
class Room(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField()
styles = models.ManyToManyField(Style)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Комнаты'
verbose_name_plural = 'Комнаты'
Sounds like you want to use the relation field that you already have on Room
to only find styles associated with the given room?
selected_room = Room.objects.get(slug=rmslg)
style = selected_room.styles.get(slug=stslg)

Django template sort by 'unrelated' model's field

I'm trying to sort related items in a template by a field in a model three ForeignKey relationships away. I'm assembling the data for the template in the view as proposed in another StackOverflow answer:
Sorting related items in a Django template
As far as I can tell, I copied the code from this as-is except for I had to change variable names. It doesn't throw an error, it just displays no list items in the HTML unordered list.
# checkout.html
{% for item in cart_items %}
<tr>
<td class="left">
{{ item.name }}
<ul>
{% for part in part_list %}
<li>{{ part.name }}
{% endfor %}
</ul></td>
</tr>
{% endfor %}
And the view...
# views.py
def checkout(request):
cart_items = get_cart_items(request)
itemCollection = []
for item in cart_items:
item.part_list = item.product.buildpart.all().order_by('product__family__type')
itemCollection.append(item)
return render(request, 'checkout.html', locals())
And the get_cart_items function:
# cart.py
def get_cart_items(request):
""" return all items from the current user's cart """
return CartItem.objects.filter(cart_id=get_cart_id(request))
As I said, the template and view are pretty much copies of the solution presented in the aforementioned StackOverflow article. One thing I thought was curious was that itemCollection[] from the view is never referenced in the template.
I believe the order_by clause ('product__family__type') is right only because it doesn't generate an error. But in case that is the problem or a part of it here is the chain of models I am attempting to navigate in that order_by clause:
We start from the shopping cart model (CartItem):
class Item(models.Model):
cart_id = models.CharField(max_length=50)
quantity = models.IntegerField(default=1)
product = models.ForeignKey(PartModel, unique=False)
class Meta:
abstract = True
class CartItem(Item):
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['date_added']
verbose_name = "Cart Item"
Through the 'product' field we get to the model holding our inventory and its self-referential BuildPart ManyToMany model:
class PartModel(models.Model):
family = models.ForeignKey(PartFamily)
name = models.CharField("Model Name", max_length=50, unique=True)
buildpart = models.ManyToManyField('self', through='BuildPart',
symmetrical=False, related_name='+')
class Build(models.Model):
build = models.ForeignKey(PartModel, related_name='+')
part = models.ForeignKey(PartModel, related_name='+')
quantity = models.PositiveSmallIntegerField(default=1)
class Meta:
abstract = True
unique_together = ('build', 'part')
def __unicode__(self):
return self.build.name + ' with ' + str(self.quantity) + ' * ' + \
self.part.family.make.name + ' ' + self.part.name
class BuildPart(Build):
pass
class Meta:
verbose_name = "Build Part"
From there we follow the 'family' field to the PartFamily model:
class PartFamily(models.Model):
make = models.ForeignKey(PartMake)
type = models.ForeignKey(PartType)
name = models.CharField("Family Name", max_length=30,
unique=True)
slug = models.SlugField(unique=True)
And lastly, we get to the model with the 'order' field, the one we wish to sort the related items by, PartType:
class PartType(models.Model):
name = models.CharField("Part Type", max_length=30, unique=True)
slug = models.SlugField(unique=True)
order = models.PositiveSmallIntegerField()
description = models.TextField(blank=True, null=True)
To recap, how do I get the shopping cart products' related items, and sort them by the 'order' field in the PartType model?
You have two errors, both in the template.
Firstly, you've put your items with the sorted relationship in a list called itemCollection, but in the template you're iterating over cart_item instead. This is a very good example of why you should be explicit about what variables you pass to the template, rather than relying on locals().
Secondly, you then iterate over part_list without defining it. You mean item.part_list.

How to use Django Haystack EdgeNGrams with Many-to-Many field?

I've recently been trying to implement full text search on my webapp with Django Haystack (v2.1.0) with Elasticsearch (v0.90.5) as my search engine. My goal is to be able to, with one query, search through a title field, key line field, and an authors field for a given Song object. Here is my code:
Models.py
class Song(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
key_line = models.CharField(max_length=300, blank=True)
def __unicode__(self):
return self.title
class Author(models.Model):
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=40)
email = models.EmailField(blank=True, verbose_name='e-mail')
def __unicode__(self):
if self.middle_name:
return u'%s %s %s' % (self.first_name, self.middle_name, self.last_name)
else:
return u'%s %s' % (self.first_name, self.last_name)
class Meta:
ordering = ('last_name','first_name')
Search_index.py
from haystack import indexes
from songs.models import Song
class SongIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.EdgeNgramField(model_attr='title')
content_auto = indexes.EdgeNgramField(model_attr='key_line')
authors = indexes.MultiValueField()
content_auto = indexes.EdgeNgramField(model_attr='authors')
def get_model(self):
return Song
def prepare_authors(self, object):
return [author.last_name for author in object.authors.all()]
def index_queryset(self, using=None):
return self.get_model().objects.all()
song_text.txt
{{ object.title}}
{{ object.key_line}}
{% for author in object.authors.all %}
{{ author.last_name}}
{% endfor %}
I'm sure my search_index.py is terribly wrong for the authors but I was getting desperate. I've been able to get the title and the key_line to work properly in that if i type in a query, I get results that have the query in the title or have the query in the key line. Performing the same test but instead querying the author's last name doesn't give me results with that author.
I've gone through the documentation and though I've found some information on indexing related fields, I haven't been able to find anything specific related to using EdgeNGrams with a related field. Is this possible to do? Ideally, I'd like to be able to query over the author's first, middle, and last name.
Thanks in advance for any help you can give! Let me know if you need any more information.
Similar problem is addressed # Haystack search on a many to many field is not working
def prepare_category(self, obj):
return [category.name for category in obj.category_set.all()]
Your code should be ;
def prepare_authors(self, object):
return [author.last_name for author in object.authors_set.all()]
Change song_text.txt to ;
{{ object.title}}
{{ object.key_line}}
{% for author in object.authors.all %}
{{ author.first_name}}
{{ author.middle_name}}
{{ author.last_name}}
{% endfor %}
Changing object.authors.all() to object.authors_set.all() should solve this problem.

Categories

Resources