I'm using odoo and i want to prohibit printing invoices when client adresse is empty any idea for help please ? How can'i verify if this field or any other field is empty or not
this the function of printing i tried this code but nothing is happend
def invoice_print(self,cr,uid,values):
""" Print the invoice and mark it as sent, so that we can see more
easily the next step of the workflow
"""
res_partner = self.pool.get('res.partner')
adresse_partner = res_partner.browse(cr, uid, values.get('partner_id')).street
code_tva_partner = res_partner.browse(cr, uid, values.get('partner_id')).CodeTVA
if (code_tva_partner==False)or (adresse_partner==False) :
raise UserError(_(
"you cannot print invoice unless you enter partner adress and code TVA "))
elif (code_tva_partner==True) and (adresse_partner==True):
self.ensure_one()
self.sent = True
return self.env['report'].get_action(self, 'account.report_invoice')
In this function self is the record of invoice model that you are trying partner_id which is the client record for this invoice. All you have to do is add a if condition on self.partner_id.street and if that field is False which means not set, return a kind of warning. Which will prevent invoice from printing if the client has no address associated.
Related
How can we query and select specific id of a notification..?
Right now following problem i'm facing... You can see in else section i am sending notification that a person followed other person. Now In if selection when a person unfollow the person he followed. That notification should be removed so that when he follow again the previous notification get removes and new one get generated. I expect kind and help full ans from you guys . Thank you !:)
if follower:
profile_.follower.remove(follower.id)
actor = User.objects.get(pk=user_id)
user = User.objects.get(username=username_to_toggle)
query = Notification.objects.filter(id__in=notificacion_ids).update(deleted=True) #notificacion_ids(I don't understand how to get that.)
print(query,"hey heyh eh")
# json_follower = some_view(user)
else:
new_follower = User.objects.get(username__iexact=username_to_toggle)
profile_.follower.add(new_follower.id)
actor = User.objects.get(pk=user_id)
user = User.objects.get(username=username_to_toggle)
notify.send(actor, recipient=user, verb='follow you')
# json_follower = some_view(username_to_toggle)
is_following = True
you would then filter the notifications model using the 'actor' and the 'recipient'. Something like this:
notification_ids =Notification.objects.filter(actor_object_id=actor.id,recipient_id=user.id).values_list('id', flat=True)
I am trying to pull data from an SQL-Table 'School' via flask sql-alchemy into a SelectField:
form:
school_choices = [(School.id, School.name) for school in School.query.all()]
school = SelectField('Your school', validators=[DataRequired()], choices=school_choices)
routes:
def register():
if current_user.is_authenticated:
return redirect(url_for('home'))
form = RegistrationForm()
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
user = User(username=form.username.data, email=form.email.data, password=hashed_password, school=form.school.data)
db.session.add(user)
db.session.commit()
flash('Your account has been created! You are now able to log in', 'success')
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
model:
class School(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
However, it somehow only displays "School.name", just how it is written in the form.
Also, the number of entries it should display is correct (3, since 3 entries of schools are in the database)
The issue is in your list comprehension that builds the values for the select field and the difference between the rendering of column attributes on the class vs the class instance:
school_choices = [(School.id, School.name) for school in School.query.all()]
In the above comprehension, in each loop school (lowercase 's') is an instance of the class School (uppercase 'S').
In sqlalchemy, the string representation of a column attribute on a Class (not instance of a class) returns the database identity of the column, e.g.: "<tablename>.<columnname>", or in this case "school.name". This is how queries are built, e.g. try running print(School.__table__.select()), it will print SELECT school.id, school.name FROM School. The column identities in that query come from "stringifying" the Column instance.
However, when we access a column attribute on an instance of a class, e.g. school = School(name="myschool"), we get the value of the column that is stored in the database. E.g. print(school.school) # myschool.
Looking at your list comprehension above, you create a tuple of (School.id, School.name) for each school instance in the database. Notice the uppercase 'S' for 'School', which means that you end up rendering the string representation of your column's database identity for each school in the database when your template renders. The answer is as simple as changing your comprehension to:
school_choices = [(school.id, school.name) for school in School.query.all()]
...but understanding the difference is fairly important when using sqlalchemy and python in general.
I want to in every time I created a data on One2many field, at the same time I want it to save as data on my maintenance.equipment. I try to find the solution on other module in addons but i didn't yet find the answer.
The scenario is, before validating the shipment in my product, I need to input serial number on it. Each serial number I created to that product at the same time serves as my equipment name.
and that serial number which is sample1010, I need it to become my equipment name in module maintenance.equipment. I expected it to display here in my equipment.
All i taught is only i need to do is creating Many2one and One2many fields like this
class StockPackOperation(models.Model):
_inherit = 'stock.pack.operation'
lines_ids = fields.One2many('maintenance.equipment', 'lines_id')
sample = fields.Char(string="Sample")
class MaintenanceEquipment(models.Model):
_inherit = 'maintenance.equipment'
lines_id = fields.Many2one('stock.pack.operation')
but nothings happen. Any help or suggestion or advice please. I need to do this. Thanks in advice masters. Anw I am new in odoo.
This can be achieved by inheriting stock.pack.operation.lot class, as entered serial numbers are stored in this class with lot_name (in case of incoming shipment) and with lot_id (in case of outgoing shipment).
You will not need to care about outgoing shipment, as in outgoing shipment we select already existing serial numbers.
class StockPackOperationLot(models.Model):
_inherit = 'stock.pack.operation.lot'
#api.model
def create(self, vals):
res = super(StockPackOperationLot, self).create(vals)
if vals.get('lot_name'):
self.env['maintenance.equipment'].create({'name': vals.get('lot_name')})
return res
#api.multi
def write(self, vals):
if vals.get('lot_name'):
lot_name = self.lot_name
equipment_id = self.env['maintenance.equipment'].search([('name', '=', lot_name)])
res = super(StockPackOperationLot, self).write(vals)
equipment_id.name = vals.get('lot_name')
return res
else:
return super(StockPackOperationLot, self).write(vals)
For this functionality to work properly, you will need to make sure equipment name is unique, else you will need to store related equipment id in each stock.pack.operation.lot record, so that when user edits serial number, equipment is also updated, when there is no unique constraint on name of equipment.
hope this helps you...
I am using QuerySelectField in many pages in a Flask app and it is working fine. Except in one route where I keep getting the message "not a valid choice" when I submit the form.
Yet, the dropdown menu is populated correctly and a choice is indeed selected in it. When I print() the field data, I get a "None" so there seems to be the problem since even if we select a choice, the form seems to pass "None" as the result. Any idea why?
The field is set as:
buy_pc = QuerySelectField('Punch-cards',query_factory=getPunchcards,get_label='label')
Here is the full form:
def getPunchcards():
return Punchcard.query
class Add_participants(Form):
member_name = StringField('Type the tribe\'s member full name:', validators=[DataRequired()])
choice = RadioField('Registration mode',validators=[DataRequired()],choices=[('season_pass','Season Pass'),
('punchcard', 'Punch-card'),
('free_pass','Using a free pass'),
('old_punchcard','Using old punch-card'),
('dropin','Drop-in'),
('checked','Use another member punch-card')])
dropin_ammount = IntegerField('Drop-in ammount',validators=[NumberRange(min=0,max=25,message='Please '
'enter an amount btw 0 and 25')],default=10)
add_note = BooleanField('Add a note to the member profile')
note_content = TextAreaField()
other_punchcard = StringField('Type the tribe\'s member full name:')
buy_pc = QuerySelectField('Punch-cards',query_factory=getPunchcards,get_label='label')
submit = SubmitField('Add')
I am trying to access data.get_age_display in my email template. I can't seem to get the display of this. I am not sure what I am doing wrong, I've using get_FIELD_display numerous times before but passed as context to a normal template. Is there something different with forms?
class RequestForm(forms.Form):
ADULT = 1
SENIOR = 2
STUDENT = 3
AGE_GROUP = (
(ADULT, 'Adult'),
(SENIOR, 'Senior'),
(STUDENT, 'Student'),
)
name = forms.CharField(max_length=255)
phone = forms.CharField(max_length=15)
age = forms.ChoiceField(choices=AGE_GROUP)
details = forms.CharField(widget=forms.Textarea())
def save(self):
order = Order(
name = self.cleaned_data['name'],
phone = self.cleaned_data['phone'],
age = self.cleaned_data['age'],
details = self.cleaned_data['details'],
)
order.save()
template = loader.get_template('request_email.txt')
# send over the order object in an email extracted so they can handle the ticket order
context = Context({
'data': order,
})
#import pdb; pdb.set_trace()
email_subject = 'Request Tickets'
mail_managers(email_subject, template.render(context))
in my request_email.txt all I am doing is {{ data.get_age_display }} any ideas?
Jeff
You haven't shown the code for the Order model that you're creating. Are you sure that the age field on the model has choices set?
Any reason you're not using a ModelForm? You're creating an Order object within the form's save() method, but not returning it. A modelform would do that for you, as well as removing the need to redeclare the fields for the form.
I know this is coming WAAAAAY later than the question being posted but here's my answer for completeness and anyone else who might benefit from it :-)
I'm going to assume that in AGE_GROUP, ADULT, SENIOR and STUDENT are integers. Your form cleaning will NOT automatically clean the string contained in the POST and return an integer. So in this code:
context = Context({
'data': order,
})
you would think order.age is referring to an integer but that is, in fact, incorrect. It's burned me a few times before because this will correctly save the integer to the physical table, but the order instance still has the string representation of the age field.
You could do one of two things:
1. Clean this in the field:
clean_age(self):
return int(self.cleaned_data['age'])
or create a new field type:
def MyChoiceField(forms.ChoiceField):
def clean(self, value):
if not value:
if self.required:
raise forms.ValidationError(self.error_messages['required'])
return None
else:
return None
return int(value)
link that to the form field:
age = MyChoiceField(choices=AGE_GROUP)
and then you'll be able to apply this logic to any other such choice field in future. Personally, I find the latter approach the best one and I stick all my custom field types into a form_utils file so that I can use them everywhere. Another gotcha is that forms.charField doesn't automatically strip the entered text and you can use this approach to fix that too.