How to set default value to Many2one field in odoo10? - python

I created a many2one field that has relationship custom model. I want to know how to self default value. My default value is "Head/Branch".
Here is my code. Thank You.
from odoo import models, fields, api
import logging
class CrmnNewTask(models.Model):
_inherit = 'res.partner'
head_branch=fields.Many2one('head.branch', string='Head/Branch',index=True, ondelete='cascade')
class Headbranch(models.Model):
_name='head.branch'
name=fields.Char('Head/Branch')

Please implement this example in your code :
user_id = fields.Many2one('res.users','User', default=lambda self: self.env.user)
Here I have set current user name in many2one field. You can also set default value using function. This one another example :
*
tax_group_id = fields.Many2one('account.tax.group', string="Tax Group", default=_default_tax_group, required=True)
#api.model
def _default_tax_group(self):
return self.env['account.tax.group'].search([], limit=1)
*

Try this:
Go to your form where is field head_branch
Active developer mode
Populate field and save as default https://imgur.com/a/fQd03

Related

How to Use Many2one Field as selection?

on Odoo, I want to create a many2one field which show some items created according to another field(named 'A') and can be changed once field 'A' is changed.
I have tried to use field.Selection, but failed and I switch to field.Many2one; and until now I don't complete this.
class Selection(models.Model):
_name = 'selection.model'
_rec_name = 'select'
select = fields.Char(string='selections', required=True)
class Checks(models.Model):
_name = 'buy.goods'
strs = fields.Char()
results = fields.Many2one('selection.model', string='Selections')
#api.onchange('strs')
def _get_results(self):
goods = self.strs.split(',')
I want to use the list of words of 'goods' as items of 'results' field and once content of 'strs' field is changed, the list of 'goods' is changed and items of 'results' should be changed automaticly.
When you define the form view in XML you need to add a widget called selection. Through this way you can use your many2one field as a selection field.
For example:
<field name='results' widget='selection'/>
ps: clear cache and try it !

How to automatically fill-in model fields in Django rest_framework serializer?

Let's assume I have a model like this:
class Data(models.Model):
a = models.CharField()
b = models.CharField()
c = models.IntegerField()
I would like to setup a serializer in such a way that it automatically fills in field c and it is not required for a POST. I tried to overwrite the create function of the serializer, but it doesn't work:
class DataSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Data
fields = ('a', 'b')
def create(self, validated_data, **kwargs):
Data.objects.c = 5
return Data.objects.create(**validated_data)
However, if I try this, I end up with an IntegrityError: NOT NULL constraint failed: model_data.c. What is the syntax that I have to use here?
EDIT: Updated formatting.
The reason you're getting the error because field c is not set to null = True - as such an error is raised at the validation stage even before the serializer hits the create method.
Bear in mind that the process goes like this:
Submit serializer data
field-level validation happens - this includes checks for null integrity, min/max length etc and also any custom field validations defined in def validate_<field_name>
object-level validation happens - this calls the def validate method
validated data is passed to the save method, depending on how you designed the serializer - it will save the instance, or route the data to either create or update
All of the info regarding this can be found in Django's and DRF's docs.
A few things to consider:
are you setting a global default for that field? If so, set the default in your models - c = models.IntegerField(default=a_number_or_a_callable_that_returns_an_integer)
do you intend to display the field? If so, include c in your fields and add one more Meta attribute - read_only_fields = ('c',)
If it's neither of the above, you might want to override the validate_c method
Apologies for the poor formatting, typing it on my phone - will update once I get to a computer
In your code Data.objects.c = 5 does nothing.
If you want to set this value yourself use validated_data['c'] = 5 or Data.objects.create(c=5, **validated_data) (just not both at the same time).
Rather than doing this in the serializer, there are hooks in the generic views that allow you to pass values to the serializer. So in your case you might have:
class DataViewSet(ModelViewSet):
# ...
def perform_create(self, serializer):
serializer.save(c=5)
See the "Save and deletion hooks" section here

Why default value for column doesn't work with django

I'm using django to create database tables,model code like this:
class User(models.Model):
uid = models.CharField(max_length=32,primary_key=True)
nick = models.CharField(max_length=20)
sex = models.CharField(max_length=1,default='M')
sign = models.CharField(max_length=40,default="")
but default value doesn't work.when I show table description,shows that:
why this code doesn't work and how can solve this problem?
Django doesn't add default values into the schema, instead it adds the default value if need-be when a User object is created.

How to define a selection field in flask

I want to define a selection field in python, i.e. field that is limited to a set of values. How can I do that in flask framework. I could not find anything on selection fields in the following sources:
Declaring Models
SQLAlchemy in Flask
I am using sqlalchemy for ORM.
I assume you mean a field in a form that has a limited set of options; to do this you can use WTForms and its extensions which allow you to create forms from models.
Once you have done that, you can then limit the choices for a field based on a model condition.
As you haven't posted your model, here is the example give you give you an idea on how this would work:
def enabled_categories():
return Category.query.filter_by(enabled=True)
class BlogPostEdit(Form):
title = TextField()
blog = QuerySelectField(get_label='title')
category = QuerySelectField(query_factory=enabled_categories,
allow_blank=True)
def edit_blog_post(request, id):
post = Post.query.get(id)
form = ArticleEdit(obj=post)
# Since we didn't provide a query_factory for the 'blog' field, we need
# to set a dynamic one in the view.
form.blog.query = Blog.query.filter(Blog.author == request.user) \
.order_by(Blog.name)

Making disabled field in ModelForm subclass

I got a model Layout in my Django app with the following fields:
meta_layout - ForeignKey on model MetaLayout
name - CharField
edited - DateTimeField
is_active - BooleanField
And I have two views using this model - one called NewLayout and other EditLayout each subclassing standard CreateView and UpdateView accordingly. In EditLayout view I want to use some special form that looks the same as form used in NewLayout (which is simply plain ModelForm for this model) but has meta_layout select field displayed with attribute disabled="disabled" (e.d. user can choose meta_layout for each Layout only once - while creating it). Ok, I can create custom ModelForm where widget for meta_layout field has the desired attribute, but the problem is actually that when such attribute set on form field it will not send any values with request - so my validation fails trying to check value for this field and select element does not support "readonly" attribute which will would be just fine here.
I found some really ugly hack to workaround this:
#Here is my Form:
class LayoutEditForm(forms.ModelForm):
meta_layout = forms.ModelChoiceField(
queryset=MetaLayout.objects.all(),
widget=forms.Select(attrs=dict(disabled='disabled')),
empty_label=None,
required=False) # if required=True validation will fail
# because value is not supplied in POST
class Meta:
fields = ('meta_layout', 'name', 'is_active')
model = Layout
class EditLayout(UpdateView):
...
# And one modified method from my View-class
def get_form_kwargs(self):
kwargs = super(EditLayout, self).get_form_kwargs()
# actually POST parameters
if kwargs.has_key('data'):
# can't change QueryDict itself - it's immutable
data = dict(self.request.POST.items())
# emulate POST params from ModelChoiceField
data['meta_layout'] = u'%d' % self.object.meta_layout.id
kwargs['data'] = data
return kwargs
But I believe that it's non-Django, non-Pythonic and not a good-programming-style-at-all of doing such simple thing. Can you suggest any better solution?
Edit:
Oh, I found much less ugly solution: added this in my form class:
def clean_meta_layout(self):
return self.instance.meta_layout
But I still open for suggestions) - may I missed something?

Categories