How to get only Tweet (only posts) from the timeline? - django-rest-framework

Whenever tweet is created, it's activity is added to getStream production app.
class Tweet(models.Model, Activity):
user = models.ForeignKey()
text = models.CharField()
class Follow(models.Model, Activity): <- This is adding new activity to the timeline
def follow_feed_lisnner(~)
signal.post_save.connect(~)
class Like(models.Model, Activity): <- Like is adding to activity so timeline automatically shows who liked this post,
My Expectation:
Feed: only shows Tweet on timeline (I don't want to see who started to follow me, or liked any post) - Just Like Instagram!
Notification: Who started to follow me, Who liked my post, Who commented on my post.
views.py
feeds = feed_manager.get_news_feeds(request.user.id)
# get the newsfeed for user.
activities = feeds.get('timeline').get()['results']
activities = enricher.enrich_activities(activities)
Possible Solutions
Use python-stream (more low level) to deal with this problem. (I don't know if it helps)
Maybe I'm missing a cool feature of stream-django
How can we get only Tweet (Not Like, Follow or other activities which should be in notification) on the timeline?
Thank you
UPDATE
If I understood correctly, this should work. Is this valid?
class Follow(models.Model, Activity):
follower =
following
#property
def activity_author_feed(self):
return 'notification'
Activity 1: user A follows user B.
Activity 1 goes to 'user' feed + 'notification' feed (not timeline feed)
//notification feed name already exists so I don't need to create follow feed group
Activity 2: user B creates Post
Activity 2 goes to 'user' feed + 'timeline' feed

Note: I'm assuming your Follow and Like models have a "user" field. If not, best update the question with the full Model classes and also confirm if you're setting up any other following relationships.
The stream-django integration provides an 'Activity' model Mixin and the FeedManager model Manager. They work together to add activities to a Feed Group and Feed whose unique "feed id" is derived from the Model instance.
By default, the feed id is determined by the application wide settings.USER_FEED setting. That should work well for your Tweet model but is probably not what you want for the Follow and Like models. The activities associated with those models ideally belong in separate feeds. This can be setup by overriding the Activity.activity_author_feed property function.
class Follow(models.Model, Activity):
# snipping fields
#property
def activity_author_feed(self):
return 'Follow' # Must match a Feed Group defined in the Stream dashboard
#property
def activity_actor_attr(self):
return self.author
To have to those activities copied into the notification feed, implement the Activity.activity_notify() function to return a list of target feeds.
#property
def activity_notify(self):
return [feed_manager.get_notification_feed(self.user.id)]

Related

Association Exclude Based on Field

I'm looking for the best Ruby way to accomplish this.
I have a Person that has_many Feeds through Subscriptions. So we can do things like Person.feeds, and it gets all the feeds a person is subscribed to.
Problem is, subscriptions are either authorized or deauthorized. What is the best way to make Person.feeds respect the Authorized status bit on the Subscription model?
So we can do something like Person.feeds.where(:status => authorized).
You can call this with a command like the following:
#person.feeds.joins(:subscription).where(subscriptions: { status: 'authorized' })
N.B. the joins takes the association's format, singular in this case, while where takes the table name, typically pluralised.
What this does in order is:
Loads the feeds belonging to a person
Joins these feeds to their subscription
Queries the subscriptions table to return only the feeds where the subscription is active
To refactor this, I'd include a couple of methods in the relevant models:
# feed.rb
scope :active, -> { joins(:subscription).where(subscriptions: { status: 'authorized' }) }
# person.rb
def active_feeds
feeds.active
end
Then, you can just call #person.active_feeds to get the results you want from anywhere in your code base.
(There's also the added bonus of Feed.active being available anywhere should you wish to display active feeds outside of a user's scope.)
Hope that helps - let me know if you've any questions.

Get instances during serializer validation in DRF

I am starting to work with the Django REST framework for a mini-reddit project I already developed.
The problem is that I am stuck in this situation:
A Minisub is like a subreddit. It has, among others, a field named managers which is ManyToMany with User.
An Ad is an advertising which will be displayed on the minisub, and it has a field named minisubs which is ManyToMany with Minisub. It has also a author field, foreign key with User.
I would like to allow these managers to add some ads on their minisubs through a DRF API. It is actually working. But I want to check that they put in minisubs only minisubs where they are managers.
I found a way like that:
class AdSerializer(serializers.HyperlinkedModelSerializer):
# ...
def validate_minisubs(self, value):
for m in value:
if user not in m.managers.all():
raise serializers.ValidationError("...")
return value
My question is: How to get user ? I can't find a way to get the value Ad.author (this field is set automatically in the serial data according to the user authentication). Maybe I don't find a way because there is no ways ? The place to do this is somewhere else ?
Thanks in advance.
You may get it out of the serializer this way:
class YourModelSeializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=YourModel
def validate_myfield(self):
instance = getattr(self, 'instance', None)
...
I believe that this is a job for the permissions, if you are performing CRUD operations for inserting that into a database then u can have a permission class returns True if the user is a manager.
a permissions instance has access to the request which u can use to get the user and check if he is a manager:
http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

Django autocomplete Light in list filters for admin

I have successfully setup the Autocomplete Registry and have my django admin forms where if you go to the form, the auto completes works. I would like to be able to extend the autocompletes to work on the list_filter view as well. So when you are looking at the view generated by Admin.py -- that the list_filter inputs that are generated would also use the autocomplete jquery + service URL.
I didn't see anything listed in the documentation, anyone have any pointers?
If you are using Django version greater then 2.0, you can try using the built-in autocomplete fields for this purpose.
By default, the admin uses a select-box interface () for those fields. Sometimes you don’t want to incur the overhead of selecting all the related instances to display in the dropdown.
The Select2 input looks similar to the default input but comes with a search feature that loads the options asynchronously
There is a simple app which does this:
To install use: pip install django-admin-autocomplete-filter
Then add admin_auto_filters to your INSTALLED_APPS inside settings.py of your project.
Let's say we have following models:
class Artist(models.Model):
name = models.CharField(max_length=128)
class Album(models.Model):
name = models.CharField(max_length=64)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
cover = models.CharField(max_length=256, null=True, default=None)
And you would like to filter results in Album Admin on the basis of artist, then you can define search fields in Artist and then define filter as:
from admin_auto_filters.filters import AutocompleteFilter
class ArtistFilter(AutocompleteFilter):
title = 'Artist' # display title
field_name = 'artist' # name of the foreign key field
class ArtistAdmin(admin.ModelAdmin):
search_fields = ['name'] # this is required for django's autocomplete functionality
...
class AlbumAdmin(admin.ModelAdmin):
list_filter = [ArtistFilter]
'''
defining this class is required for AutocompleteFilter
it's a bug and I am working on it.
'''
class Media:
pass
After following these steps you may see the filter as:
You should define your own admin filter that inherits from django.contrib.admin.SimpleListFilter. Then should provide your own HTML template for this filter which will use one of django-autocomplete-light widgets. As a parameter for widget you should define required autocomplete URL. And do not forget to include proper JS and CSS for it.
All of this is done in special app for this: dal-admin-filters

Update model attribute without refreshing database

I'm building a website listing poker tournaments. I would like to allow user mark some tournaments as his favourite and avoid forms or extra page with GET parameter - I would like to to update it without refreshing website. From what I understand, it's done by ajax and jquery. But there are many ajax libraries and I would like you to tell me, which one should I use and how to do this simple functionality best.
This is my tournament table:
I would like to have another column before event time, that would contain image for heart. It would be black (not favourite) and if user clicks on it, it would turn red (favourite).
I think m2m relationship should be used here. This is my tournament model.
class Tournament(models.Model):
favourite = models.ManyToManyField(User)
date = models.DateTimeField('Event time')
currency = models.CharField(max_length=5, choices=CURRENCIES, default='USD')
name = models.CharField("Tournament name", max_length=200)
prize = models.DecimalField(max_digits=20, decimal_places=2)
entry = models.DecimalField(max_digits=20, decimal_places=2)
fee = models.DecimalField(max_digits=20, decimal_places=2)
password = models.CharField("password", max_length=200)
type = models.ForeignKey('room.Type')
room = models.ForeignKey('room.Room')
requirements_difficulty = models.IntegerField('Tournament Difficulty',
validators=[MinValueValidator(1), MaxValueValidator(30)])
requirements_text = models.CharField("Requirements Description", max_length=1000)
recurrence = models.CharField(max_length=5,
choices=RECURRENCE_CHOICES,
default='NONE')
So how do I add m2m relationship between user and tournament? Do I use ajax code or dajax? How do I create this m2m without refreshing page?
So how do I add m2m relationship between user and tournament?
Assuming that you use the default django user model:
Class Tournament(models.Model):
user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='user_tournament')
...
Do I use ajax code or dajax?
As #doniyor said, you should define your real problem and split your question. SO is not "do it for me", anyway, what I can do for you, is give you some good links ;)
W3 schools definition for ajax:
http://www.w3schools.com/ajax/ajax_intro.asp
Good ajax plugin for djando that seems you already know:
http://www.dajaxproject.com/
By the way, you should use dajax, is easy and faster to create ajax pages integrated with django (you just have to follow the tutorials, is pretty simple).
How do I create this m2m without refreshing page?
Using dajax

Bring real data tables with FK

I have 3 classes: Document, Layout and Company
1 Document has 1 Layout and 1 Company.
Document class:
layout = models.ForeignKey (Layout)
company = models.ForeignKey (Company)
I have a search page that is being filled by JSON, then the data layout and the company is returning the ID of them respectively, and the ideal would be to show the names of each data (Name and Company Name Layout).
How can I accomplish this query as quoted above?
You need to define a __unicode__(self): method for Layout and Company.
It might look something like:
class Layout(models.Model):
name = models.CharField(...)
def __unicode__(self):
return self.name
Of course, I'm only guessing at what your Layout class looks like. You'll have to change __unicode__ to make it appropriate for your model.
In the future, try to search the Django Documentation. It's actually quite good. Here's the relevant information for what you're asking. https://docs.djangoproject.com/en/dev/ref/models/instances/#unicode

Resources