Hi I have below setup.
Django 1.9,
mongoDB,
pymongo 2.7,
mongoengine 0.9
I have written an API to store logs at backend server userwise. Below is sample of table
user subject registered changed_on
abc eng Y "2018-04-18T00:00:00Z"
abc maths N "2018-04-18T00:10:00Z"
xyz eng Y "2018-04-18T00:10:00Z"
I also have read API for this in which we give user name and timestamp for filter like below:
{
"user" : "abc",
"from_date" : "2018-04-18T00:00:00Z"
}
The line in serializers.py which is applying filter is
Logs.objects.filter(user__iexact='abc',changed_on__gte=from_date)
Now Sometimes when I add new log and retrieve it from postman, it is not working. I have to restart django server and then it gives me newly added row.
I dont understand why this is happening.
EDIT1 : Full Serializer.py
from rest_framework import serializers
class GetUserLogs(serializers.Serializer):
user = serializers.CharField(label=_("USER"))
token = serializers.CharField(label=_("Token"))
from_date = serializers.CharField(label=_('From date'), default="")
till_date = serializers.CharField(label=_('Till date'), default=datetime.datetime.now().isoformat().split(".")[0]+'Z')
def validate(self, attrs):
user = attrs.get('user')
token = attrs.get('token')
from_date = attrs.get('from_date')
if user:
tokendetails = validate_token(token)
if not tokendetails:
msg = _('Invalid token.')
raise serializers.ValidationError(msg)
else:
userdetails = tokendetails.user
if userdetails.check_user(user):
rows = Logs.objects.all().filter(user__iexact=user,changed_on__gte=from_date, changed_on__lte = till_date)
print(len(rows))
else:
msg = _('Invalid USER)
raise serializers.ValidationError(msg)
else:
msg = _('Must include "USER".')
raise serializers.ValidationError(msg)
attrs['rows'] = rows
return attrs
So After a lot of debugging for almost a day, I found that the default value of till_date that we are setting to current timestamp of system is not increasing as time increase. So I changed default value to empty string and added below code after reading value of till_date.
if till_date == "":
till_date = datetime.datetime.now().isoformat().split(".")[0]+'Z'
It will reset the till_date value to current timestamp every time its value is missing.
Hope it will help someone someday.
Related
I'm getting record does not exist or has been deleted.\n(record: account.move.line(5398,), user: 7) error while updating data to odoo. Following is my code can anyone help to solve this problem.
import xmlrpc.client
endpoint_url = "/api/account.move/"
obj = get_object_or_404(OrderItem, order__id=order_id)
invoice_date = obj.order.created_on
name = obj.product.varient_name
price = obj.total
quantity = obj.quantity
payment_source = obj.order.payment_method
payment_reference = obj.order.order_number
common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
uid = common.authenticate(db, username, password, {})
models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))
ids = models.execute_kw(db, uid, password, 'account.move', 'search_read', [[['source_document', '=', payment_reference]]], {'fields': ['partner_id', 'id']})
invoice_id = ids[0]['id']
partner_id_ = ids[0]['partner_id'][0]
headers = {
"access-token":tokens,
"Content-type":"application/jsonp",
"Cookie":session_id
}
api_invoice_line_id = [(1, invoice_id,{'name':name, 'price_unit':price, 'quantity':quantity})]
data = {
"partner_id":partner_id_,
"invoice_date":str(invoice_date),
"move_type":"out_invoice",
"__api__invoice_line_ids":str(api_invoice_line_id),
"payment_source":payment_source,
"source_document": payment_reference,
"rider":rider_name,
"ref":""
}
datas_ = json.dumps(data, indent=4)
req = requests.put(url+endpoint_url+str(invoice_id), headers=headers, data=datas_)
if req.status_code == 200:
status = "Update Successful"
else:
status = str(req.text)
return status
It looks like your code is failing because of the tuple you give to insert/update data in __api__invoice_line_ids.
I suppose it's some account.move.line Many2many or One2many field.
I see you are using the command 1 with invoice_id (an account.move id) and some data in a dict.
The problem here is that you are then trying to add that in the field pointing to account.move.line. So your ID 5398 is the account.move id, not an account.move.line id.
Not sure what your goal is to achieve here. If it's to push/update some account.move records with new data, change your __api__invoice_line_ids to point to account.move.
If your goal is to push/update some account.move.line records, then you better loop on the line_ids of your invoice_id :)
If I wasn't clear on something or you have any other question don't hesitate asking !
I have a function in Django that accepts a post request. If that post request includes an id, I want to update that object. If the post request sends a blank/null id, I'd like to create a new object and have Django set the ID (primary key) of the model.
Here is what I have:
def save_user_roster_to_db():
name = request.data['name']
id = request.data['id'] # this could be null/blank or be an ID
try:
user_roster = SavedUserRoster.objects.update_or_create(
id=id,
defaults={
"name": name,
}
)
return user_roster.pk
except:
raise Exception
However, this seems to try to assign the blank/null value as the ID when creating a new object. How can I tell Django to set its own ID (which is the primary key) if it's creating a new object?
You can't use update_or_create with the id field. Because in the current situation, id can have a value of None, and the Django model can't create the object with an id of None.
So I think you can try like the following.
def save_user_roster_to_db():
name = request.data['name']
id = request.data['id'] # this could be null/blank or be an ID
try:
if id:
user_roster = SavedUserRoster.objects.get(pk = id).update(name = name)
else:
user_roster = SavedUserRoster.objects.create(name = name)
return user_roster.pk
except:
raise Exception
Traditionally id is auto generated and always unique. In this case replacing None id will create exception when you create record for first time.
There are two possible options.
OPTION 1:
Create another unique_identified i.e username or email.
def save_user_roster_to_db():
name = request.data['name']
unique_identified = request.data['unique_identified'] # this could be null/blank or be an ID
user_roster, is_created = SavedUserRoster.objects.update_or_create(
unique_identified=unique_identified,
defaults={
"name": name,
}
)
return user_roster.pk
OPTION 2:
For Create:
Get the last id from database and add 1 with last id, so that It will be the next id value, It will avoid the None exception.
For Update:
It will update the existence record against id
def save_user_roster_to_db():
name = request.data['name']
id = request.data['id'] # this could be null/blank or be an ID
if id is None:
id = int(MyUserModel.objects.all().last().id)+1
user_roster, is_created = SavedUserRoster.objects.update_or_create(
id=id,
defaults={
"name": name,
}
)
return user_roster.pk
So within Zendesk I created these custom fields as follows:
and now I am trying to create a user with all these fields filled with preset values. But when I try to create users, like follows:
for row in df.iloc[1:11].fillna(0).iterrows():
user = User(name = row[1].first_name,
email = row[1].email,
lifetime_value = row[1].purchased_total_value,
first_order = row[1].first_purchased,
last_order = row[1].last_purchased,
products_ordered = row[1].purchased_product_count,
total_orders = row[1].purchased_unique_orders,
total_returns = row[1].total_returns,
products_returned = row[1].products_returned,
pro_account = pd.notna(row[1].proaccount_deal),
verified=True)
created_user = zenpy_client.users.create(user)
All users are created however only with email and name fields filled up and all the custom fields which I created are empty. Zenpy's User() function is not very informative in this regard however it accepts **kwargs** and as per json representations in documentation, it should work in theory. Any workaround or my mistakes in this regard?
Have you tried using user_fields?
for row in df.iloc[1:11].fillna(0).iterrows():
uf = {"lifetime_value" : row[1].purchased_total_value,
"first_order" : row[1].first_purchased,
"last_order" : row[1].last_purchased,
"products_ordered" : row[1].purchased_product_count,
"total_orders" : row[1].purchased_unique_orders,
"total_returns" : row[1].total_returns,
"products_returned" : row[1].products_returned,
"pro_account" : pd.notna(row[1].proaccount_deal),
"verified":True}
user = User(name = row[1].first_name, email = row[1].email, user_fields=uf)
created_user = zenpy_client.users.create(user)
This should work, but if it doesn't you could try creating the user first and then querying for them, and then seeing all of your custom fields in user.user_field.
Doing so would allow you to see all the available custom user fields you can enter in. From there you can update the object and zenpy_client.users.update(user) it into the system.
There is a trial end field in subscription model, i want to initialize the field with trial_end_date ,
problem I'm facing now trial_end in subscription model showing null value, How can I extract out the field of trial end field and initialize it? I have attached the def create method looked at that.
I will appreciate your help .
def create(self, validated_data):
subscriptions_data = validated_data.pop('plan')
print(subscriptions_data)
user_memberships = UserMembership.objects.create(**validated_data)
trial_end = user_memberships.membership.get_trial_period_days()
trial_end_date = datetime.date.today() + datetime.timedelta(trial_end)
for subscription_data in subscriptions_data:
Subscription.objects.create(user_membership=user_memberships, **subscription_data,)
return user_memberships
[Model][2]
my aim is when in membership model plan contain trial period days , it will add in trial end field of subscription model
Probably because you are not passing trial_end_date's value in Subscription.objects.create(..). So you can fix it like this:
trial_end = user_memberships.membership.get_trial_period_days()
trial_end_date = datetime.date.today() + datetime.timedelta(trial_end)
for subscription_data in subscriptions_data:
Subscription.objects.create(trial_end = trial_end_date, user_membership=user_memberships, **subscription_data,)
I have a Project model with the following fields:
class Project(db.Document):
project_name = db.StringField(max_length=80, required=True)
description = db.StringField(max_length=160, required=True)
start_date = db.DateTimeField(required=True)
end_date = db.DateTimeField(required=True)
created = db.DateTimeField()
status = db.BooleanField(default=False)
releases = db.ListField(db.ReferenceField(Release))
and I am trying to create a route that shows all the active projects only whose status are set to true, and their end date has not being passed.
UPDATED
#app.route('/search/projects', methods=['GET'])
def search_projects_get():
try:
proj = Project.objects
if proj.status is True and proj.end_date < datetime.now():
return jsonify(proj)
except Exception as e:
errors.bad_request(repr(e))
Can someone please help me complete the logic in my route?