django rest frame work tutorial 4 serializer concept - django-rest-framework

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

Related

Rails Active Admin unpermitted parameter

I have some problem/issues with active admin on rails, specifically unpermitted params error:
existing active admin parameter
here is the existing active admin parameter
model associated with the main model im working with
As per active admin documentation I should be doin right, as the other attributes for dispatch_information model is being accepted by rails and I was able to read and write with out any issues. Just with this recently added attribute "custom_attorney". Associations already set. and with out declaring an attr_accessor on model file it says this error
No method error
as it seems it cannot read or detect the column that I added for dispatch_information model, while in my console its already there.
When I add it with attr_accessor "while it should not, just to proceed on the form page" then I fill in the attributes need, im getting weird stuff in my console
Console view
as you can see it seems it being added inside efile_order hash instead of dispatch_information_attribute hash, and at the bottom part of the image you can see it says unpermitted parameters, even I added it inside the correct attribute block, we can also notice that the other attributes pf dispatch_information works really fine, just this recently added custom_attorney attribute. I already did everything like migration and other stuff.
Form Input
here is my form where we can see that input is on the same block where dispatch_defendant and dispatch_plaintiff is included and those two attribute works fine as well.
I really dont know what I missed here. TIA
The problem is that custom_attorney should be nested under dispatch_information_attributes you have it in the wrong place so it's unpermitted.
The correct way to do that is to add a block for those attributes and nest them.
- f.simple_fields_for :dispatch_information do |d|
- d.input :custom_attorney, :input_html => { id: 'new-attorney' }
It may be a good idea to provide an object for dispatch_information if you care for existing data. Assuming your ivar is named #e_filling_order then you should have the following.
- f.simple_fields_for :dispatch_information, #e_filling_order.dispatch_information || #e_filling_order.build_dispatch_information do |d|

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

Suggestion with basic drools syntax

The following is a basic drools syntax:
$customer : Customer( )
Account( ) from $customer.accounts
As far as I know the first line create a new variable and assign it to the fact.
However I can't quite understand the second line especially what the "Account()" part means...
You have written class Customer, or must know it to understand what's going on here. Presumably it contains a Collection<Account> accounts (see note), which is (by the engine) retrieved one by one so that the rule fires for each Account object contained in Customer's object.
The rule will fire once for each Account object stored in any of the collections contained in all the Customer facts in working memory, with $customer being bound to the containing Customer.
You can bind another variable to Account.
Note: It could also contain a field Account accounts, but I hope the name was chosen carefully.

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

get magento module config data in Observer

I created a module with an observer for the sales module with event hook ‘sales_order_shipment_save_after’ ,
My module has the following files
Company/Modulename/etc/config.xml
Company/Modulename/etc/system.xml
Company/Modulename/Model/Observer.php
there are four fields in the modules admin configuration fields
I want to get those saved data in the Observer class.
using $this->getConfigData(’password’); gives a
Call to undefined method
error
Any suggestions?
Magento uses a static method on the global Mage application object to get configuration values
$config = Mage::getStoreConfig('section_name/group/field'); //value
$config = Mage::getStoreConfig('section_name/group'); //array
An amendment to Alan's completely correct answer.
Along with path as first parameter, getStoreConfig also accepts storeid as second parameter(optional).
Well, this is useful when you want to retrieve store-wise values.
Alan has mentioned this point in his own tutorial. I guess, he has not mentioned here just because OP has not mentioned this requirement in his question.
Please refer this
In a shipment module I can use $this->getConfigData for fields in system.xml, but in another kind of modules sometimes not, e.g. extends Mage_Core_Model_Abstract, than I must use getStoreConfig. So the answer is you don't have to use always getStoreConfig. But I don't know why ...
Answer: getConfigData is just defined in a shipment class and uses getStoreConfig too. A little confusing that some functions are extra defined and unneeded in fact ...

Resources