How to update invoice.line quantity ? - odoo-8

I am trying to create button in Invoice that will update certain field in inovoice lines. I've found how to update field in account.invoice but I am strugling to find right way how to update it in account.invoice.line.
class accountinvoiceext(models.Model):
_inherit = ['account.invoice']
#api.one
def my_button(self,uid):
invoice_id = self.id
#lines = getinvoicelinesbyid(invoice_id)
I am sure there is some proper way how to get invoice.lines related to this invoice, or not ?
I've tried _inherit account.invoice.line but then I cannot define button there.
Second question - what is best way to call some function every time invoice is created ?

if you want to add button to change the line. you need to loops the one2many fields in the invoice, and change #api.one to #api.multi, example:
#api.multi
def my_button(self):
for line in self.invoice_line:
line.write({'your_field': 'your_values'})
and if you want to call this function every invoice is create, you need to modified the create function:
#api.multi
def create_project(self,values):
res = super(SaleOrder, self).create(values)
res.my_button()
return res

Related

Fill the date field (today date) automatically o when you access to a view

I want to change the value of field ( that changes to the date of the day for example)
automatically or when you access an already created view the action is generate in odoo13.
Thaks
You should use fields_view_get method, it will fired with every type of view, if you need it when a form is open you can do something like this:
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(Movimiento, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
)
if view_type == 'form':
# Get today date
today = fields.Date.context_today(self)
# update your field here.
return res
I hope this answer can be helpful for you.

Odoo tree view only show one record with compute

I'm trying to display a user signed documents (from the "Sign app") on his page, so I added this to the inherited model:
x_signatures_relation = fields.One2many("signature.request.item", "partner_id")
x_signatures = fields.One2many("signature.request", compute="_get_signed_documents")
#api.one
def _get_signed_documents(self):
ids = []
for signature in self.x_signatures_relation:
ids.append(signature.signature_request_id)
self.x_signatures = ids
"signature.request.item" is the table relating the partner (user) with "signature.request" the actual signature.
However this return an empty view even though the current user has two signatures, but if I replace :
self.x_signatures = ids
with :
self.x_signatures = ids[0]
or :
self.x_signatures = ids[1]
It displays the record, so what's going on ?
Odoo has a very specific set of rules about how you are "allowed" to manipulate One2many and Many2Many fields.
See my recent answer, which gives a detailed explanation of all options and when/how to use them. The Odoo documentation also explains it as well.
In your case, you are setting the value in a compute method, so you want to completely replace any existing values.
# Instead of
# self.x_signatures = ids
# Try this, which uses the special number 6 to mean
# "replace any existing ids with these ids"
self.x_signatures = [(6, 0, ids)]
Furthermore, you could simplify your compute method:
#api.one
def _get_signed_documents(self):
self.x_signatures = [(6, 0, self.x_signatures_relation.ids)]

Dealing with unique constraints that should be replaced in django_rest_framework

tl;dr: How can I ignore (turn off) a unique constraint in django_rest_framework Create calls with a ListCreateAPIView, because I'm going to deal with it manually in the perform_create method?
Im using a third party library django-push-notifications. It has a nice model for APNSDevice (apple push notification service device) that has a unique constraint on a registration_id field.
My problem is that sometimes I want to manually delete old values in the table that have the registration ID, so that I can insert a new value. I'd like to use this serializer:
class APNSDeviceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = APNSDevice
fields = ('name', 'active', 'device_id', 'registration_id')
along with this code for PUT
class MyAppleDevices(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = APNSDeviceSerializer
model = APNSDevice
def get_queryset(self):
return APNSDevice.objects.filter(user = self.request.user)
def perform_create(self, serializer):
print "Looking for old devices with registration id "+str(self.request.registration_id)
oldDevices = APNSDevice.objects.filter(registration_id = self.request.registration_id)
for oldDevice in oldDevices:
oldDevice.delete()
apnsDevice = serializer.save(user=self.request.user)
In other words, I'm trying to manually delete other entries that have the unique constraint in this particular PUT, so that I can insert the new one without violating the unique constraint. The problem is the validator runs before the perform_create method is called, and I can't figure out how to turn off the validator's unique constraint. I tried adding this to the Serializer
def get_validation_exclusions(self, instance = None):
exclusions = super(APNSDeviceSerializer, self).get_validation_exclusions(instance)
return exclusions + ['registration_id']
but it doesn't help so obviously I have no clue even though I've been pouring through the documentation and Stack Overflow posts. Any help appreciated, thanks. I suppose as a last resort I could remove the unique constraint from the model, but it is a valid constraint so I'd rather leave it in.
I found this question because I had this exact problem with that exact library. You can get around it by subclassing the serializer and manually overriding the field definition:
class APNSDeviceSerializerWithNonUniqueRegistrationId(APNSDeviceSerializer):
registration_id = serializers.CharField(min_length=64, max_length=64)
class Meta(APNSDeviceSerializer.Meta):
fields = ("name", "registration_id", "device_id", "active", "date_created")
Then, if you're using django-push-notifications, you'll also need to override the ViewSet that uses that serializer:
class APNSDeviceAuthorizedViewSetWithNonUniqueRegistrationId(AuthorizedMixin, APNSDeviceViewSet):
"""
The out of the box viewset/serializer combo require the registration ID to be unique and won't
allow setting a registration ID to a new user (which is useful if we have potentially more than
one account on a device.)
"""
serializer_class = APNSDeviceSerializerWithNonUniqueRegistrationId
def perform_create(self, serializer):
if self.request.user.is_authenticated():
try:
existing_registration = APNSDevice.objects.get(
registration_id=serializer.validated_data['registration_id'])
existing_registration.delete()
except APNSDevice.DoesNotExist:
pass
serializer.save(user=self.request.user)
return super(DeviceViewSetMixin, self).perform_create(serializer)

how to check if user has permission to delete objects in django

I am trying to write a view method that responds to an AJAX request to delete an entry. I want to check if the end user is the actual author of the Entry before deleting that Entry. Does my "if" statement accomplish this?
VIEWS.PY
latest_entries=Entry.objects.order_by('-pub_date')[:16]
#login_required
def delete_object(request):
if request.is_ajax():
object_name = request.POST.get('entryname')
targetobject = Entry.objects.get(author=object_name)
if request.user = targetobject.author:
targetobject.delete()
return HttpResponseRedirect('/storefront/')
MODELS
Class Entry(models.Model):
author = models.CharField(max_length=30)
subject = models.CharField(max_length=30)
description = models.CharField(max_length=30)
You're almost there. request.user is an instance of django.utils.SimpleLazyObject, so you won't be able to do an == comparison of request.user to a CharField, of which the value is a string under the covers.
You need to do something like:
if request.user.username == targetobject.author:
targetobject.delete()
or just use whatever field from the User object is synonymous with Entry.author.
I'd say your model is wrong. author should be a ForeignKey to the auth.User model. Then your comparison would work (with the change to ==), and there are other benefits too in terms of grouping and querying by user attributes.

custom reason message for magento reward points

How to add a custom reason message for a reward action ?
I have created :
$customerId = 1303177;
$points = 10;
$customer = Mage::getModel('customer/customer')->load($customerId);
$reward = Mage::getModel('enterprise_reward/reward')
->setCustomer($customer)
->setWebsiteId(2)
->loadByCustomer();
$reward->setPointsDelta($points)
->setAction(Enterprise_Reward_Model_Reward::REWARD_ACTION_ADMIN)
->setComment('Added programmatically')
->updateRewardPoints();
i like to add something like
$reward->setReason('bonus point');
that would be visible in the reason column of the customer reward history ( back office )
If reason column already exists in the Rewards database table, then all you need is to use
$reward->setReason('bonus point');
$reward->save();
to save the values.
But if reason column doesn't exist then first create a new column reason in the database and then use the above code to save the values in that field.

Resources