Bring real data tables with FK - ajax

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

Related

How to get only Tweet (only posts) from the timeline?

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)]

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

How to find a document in Mongoid by ID without the model?

Is there a way to use Mongoid to find a document by id, without knowing which model it is?
Seeing as how Mongoid is an ODM (Object-Document-Mapper) framework for MongoDB in Ruby, I do not believe this is possible. Knowing the model is a crucial component of Mongoid so that it can appropriately translate between your objects in code and the document representation of the data within MongoDB.
Please let me know if you have any questions!
A possible workaround is to iterate over all the collections, and execute the find method for all of them.
(It can have an impact on performance depending on the number and size of the collections.)
This code assumes, that the naming of the collections follows the convention: the name of the model with lower case in plural form.
def self.find_with_id_in_all_collections(id)
all_collections = Mongoid.default_session.collections
all_models = all_collections.collect{|col| col.name.singularize.camelize}
all_models.each {|model|
begin
found_with_id = eval(model + ".find(id)")
return found_with_id
rescue Mongoid::Errors::DocumentNotFound
#nothing to do: keep on searching in the other collections
end
}
# if no such ID has been found in any of the collections:
raise "No document with the ID #{id} found in any of the following collections: #{all_collections}} resp. models: #{all_models}"
end

django rest frame work tutorial 4 serializer concept

I finished tutorial 1-4 at http://django-rest-framework.org/tutorial/4-authentication-and-permissions.html and got the code run.
However, I am not fully understand the explanation around:
owner = serializers.Field(source='owner.username')
I am confused by which field refering to which field.
1.For example, there is an owner field defined in Snippet class in models.py. After looking it up at https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey, it says ForeignKey() returns a class. Does it return the auth.User class?
2.If it does, what "owner" does the
owner = serializers.Field(source='owner.username')
refer to? I do not found owner in the import part of serializers.py.
3.What does serializers.Field(source='owner.username') returns? Does it return the username in the auth.User?
4.Should we add the corresponding field in a serializer class if the corresponding model has a field reference to another table?
source = 'owner.username' will translate to 'user.username' since owner is nothing but FK-User.
Please note that 'owner' on the left side of field is not important here, in your case. i.e, you can still add custom fields like,
xyz = serializers.Field(source='owner.username')

How to develop a backend for a scrum-like board

Currently I'm developing a debate module (much like a scrum/kanban board) for a GPL application (e-cidadania) and I don't have any experience with complex backends. I have developed a basic frontend for it, but now I don't know what approach I should use for the ajax and django backends to save and manipulate the table and notes.
The table can be N rows and N columns, every row and column has a name and position inside the table. Every note has also a position, text and comments (managed with the django comments framework).
I thought to store the parent element of every note (so I can place it later) and store the name of the rows and columns like CSV strings. Is that a good approach?
A screenshot of the current frontend: http: //ur1. ca/4zn4h
Update: I almost forgot, the frontend has been done with jQuery Sortables (so the user can move the note around as he likes) and CSS3.
You just need to model your domain (that is, debates that look like scrum boards) within Django. Think about it in plain English first, like this:
The has debates. These consist of criteria, organised in rows and columns in a specific order. This creates cells, which can have notes inside them.
Then you can set to work translating this into model classes. Don't worry too much about the fields they contain, the most important bit is the relationships (so the ForeignKey bits):
class Debate(models.Model):
title = ...
class Column(models.Model):
title = ...
order = ...
board = models.ForeignKey(ScrumBoard, related_name='columns')
class Row(models.Model):
title = ...
order = ...
board = models.ForeignKey(ScrumBoard, related_name='rows')
class Cell(models.Model):
column = models.ForeignKey(Column)
row = models.ForeignKey(Row)
class Note(models.Model)
text = ...
cell = models.ForeignKey(Cell)
That might be overly complex for what you need, though. I'm not an expert in the problem you're trying to solve? My suggestion, Django is quick – so start hacking, and give it a go, and if it's all wrong then you can go back a few steps, clean out your database and try again.
You might find it useful to play with South, which does database migrations for when you do things like add/remove/edit fields in your models.

Resources