Django DateTimeField save - django

I have a model
class Unit(models.Model):
date = models.DateTimeField()
name = models.CharField(max_length = 128)
Then I have a view with js jquery ui datepicker. Then I have an ajax post function with
data_send['date'] = $('#date').value;
data_send['name'] = $('#name').value;
$.post("/url_1/",data_send, function(data_recieve){
alert(data_recieve);
});
Then in a view I'm trying to save unit like
def url_1(request):
unit = Unit.objects.get(pk = 1)
unit.date = request.POST['date']
unit.name = request.POST['name']
unit.save()
return HttpResponse('ok')
Unit.name changes, but not unit.date. I use django 1.3. I have no csrf protection. I recieve 'ok' from server.
Why does the unit.date not save?
Thanks

Since django datetime field is a representation of a datetime.datetime python instance, I like to make sure that I have a valid instance before inserting into the database.
you can use the datetime module to achieve this, instead of saving unit.date as a string
from datetime import datetime
try:
valid_datetime = datetime.strptime(request.POST['date'], '%d-%m-%Y')
except ValueError:
# handle this
then you can save the valid_datetime as your unit.date
the second param of strptime is formatted using the below values, it should match your datepicker format
http://docs.python.org/library/datetime.html#strftime-strptime-behavior

Related

Django - Saving data without using input fields/forms

I am a novice, apologies if this question seems silly. I need to save some data into MySQL database. There are no input fields. The user should click a button, and a table is updated. The data to be saved is two foreign keys and a PK.
Here is my model
class Bids(models.Model):
id=models.AutoField(primary_key=True)
userid = models.ForeignKey(Writer, on_delete=models.DO_NOTHING, related_name='userid ')
orderid = models.ForeignKey(Orders, on_delete=models.DO_NOTHING, related_name='orderids')
biddatetime=models.DateTimeField(auto_now_add=True)
I have tried writing several functions to save these fields into table bids but no joy so far. Hers's a sample.
def saveBid(request):
if request.method!= "POST":
return HttpResponse("Action Not Allowed")
else:
biddatetime=request.POST.get('biddatetime')
bids= Bids(biddatetime=biddatetime)
order=Orders(id=id)
user= CustomUser()
user.save()
bids.save()
Pls assist
I would try sending a POST request to saveBid using Postman and what error you're getting. Post the response from postman here for more help.
It could be that
biddatetime is a string and not a datetime.
On row order=Orders(id=id) you have no variable named id in your code, this will raise error.
In your model Bids the fields userid and orderid do not allow null and blank.
You can use strptime() to convert biddatetime to datetime object.
Try something like that:
from datetime import datetime
def saveBid(request):
if request.method != "POST":
return HttpResponse("Action Not Allowed")
else:
query = request.POST
# See Format Codes - link below
biddatetime = datetime.strptime(query.get('biddatetime'), "%Y-%m-%d")
# get Order
order = Orders.objects.get(id=query.get("order_id")
# create CustomUser
user = CustomUser.objects.create(username="username")
# create Bids
bids = Bids.objects.create(biddatetime=biddatetime, userid=user, orderid=order)
create() method:
create(**kwargs)
A convenience method for creating an object and saving it all in one
step. Thus:
p = Person.objects.create(first_name="Bruce", last_name="Springsteen")
Linkt to Format Codes.
See also Creating objects.
Any reason why you are not using django Form or ModelForm?
class BidForm(forms.Form):
biddatetime = forms.DateTimeField()
.... // other fields
#require_POST
def saveBid(request):
form = BidForm(request.POST)
if form.is_valid():
biddatetime = form.cleaned_data.get('biddatetime')
... // do same for similar fields.
...// after user save
user.refresh_from_db() // post insert you will get the id value for the row
bids = Bids(
biddatetime=biddatetime,
userid=user.userid,
orderid=order.orderids)
bids.save()
I am assuming you are using the id value for user after save if thats not the case you can ignore it.

Saving post from tweepy to django model in a good way

I was wondering if any could point me in the right direction.
I'm trying to fetch twitter data and save it to a DB (with Django ORM / models).
My first approach was to create a model with all relevant information of a tweet (Status) like this:
class Tweet(models.Model):
"""
A tweet (Status) with all the respective metadata
"""
id = models.BigIntegerField()
lang = models.CharField(max_length=10)
retweet_count = models.PositiveIntegerField()
text = models.CharField(max_lenght=150)
source = ....
....
And then fetching like:
#Almost pseudocode
from monitoring.models import Tweet
status = api.get_status('xxxx') # A simple tweet status with tweepy
newtweet = Tweet(id=status.id, screen_name = status.screen_name, followers_count = status.followers_count)
newtweet.save()
I guess I could do better and easy with tweepy models factory but I can't go in the right direction by my own...any suggest? Any example/link/article would be great.
we used pickle and saved the twitter data in a variable(hard disk) if that helps you. Just use pickle in your model like this:
import pickle
filename = 'finalized_model.sav'
pickle.dump(LR_model, open(filename, 'wb'))
pickl={'vectorizer':tf_vector,'model':LR_model,'clean':clean()}
pickle.dump(pickl,open('models'+".p","wb"))
and then put this in your django apps.py:
path = os.path.join(settings.MODELS, 'models.p')
with open(path, 'rb') as pickled:
data = pickle.load(pickled)
model = data['model']
vectorizer = data['vectorizer']
given that you have declared your model in setting.py. then fetch twitter data use it in views.py

Filtering on DateTimeField with Django Rest Framework

I have a model with a DateTimeField:
class MyShell(models):
created = models.DateTimeField(auto_now=true)
I have an api linked to it using Django Rest Framework:
class ShellMessageFilter(django_filters.FilterSet):
created = django_filters.DateTimeFilter(name="created",lookup_type="gte")
class Meta:
model = ShellMessage
fields = ['created']
class ShellListViewSet(viewsets.ModelViewSet):
"""
List all ShellMessages
"""
serializer_class = ShellMessageSerializer
queryset = ShellMessage.objects.all()
filter_class = ShellMessageFilter
When I hit my API using the following URL it works perfectly:
http://127.0.0.1:8000/api/shell/?created=2014-07-17
# It returns all shell with a date greater than the one provided in URL
But, I want to do more than that by filtering base on a date and a time. I tried the following URL without success:
http://127.0.0.1:8000/api/shell/?created=2014-07-17T10:36:34.960Z
# It returns an empty array whereas there are items with a created field greater than 2014-07-17T10:36:34.960Z
If you guys know how to proceed... I don't find any good informations or example in django-filters documentation...
Simpler solution if you don't care about fractions of seconds: replace the "T" with space (%20):
http://127.0.0.1:8000/api/shell/?created=2014-07-17%2010:36:34
Worked for me.
This may not be what you want, but you could simply convert from Unix time. E.g.:
def filter_unix_dt(queryset, value):
if not value:
return queryset
try:
unix_time = int(value)
t = datetime.fromtimestamp(unix_time)
result = queryset.filter(created__gte=t)
return result
except ValueError:
return queryset
class ShellMessageFilter(django_filters.FilterSet):
created = django_filters.DateTimeFilter(action=filter_unix_dt)
class Meta:
model = ShellMessage
fields = ['created']
The issue and solution are documented in this DRF issue page: https://github.com/tomchristie/django-rest-framework/issues/1338
TL;DR: A Django ISO conversion 'issue' is preventing DRF from working as you are expecting. A fix for this has been written in DRF, allowing you to use IsoDateTimeField instead of DateTimeField. Just replaying the T with a space in your request param value also works.

Can't Return JSON object using MongoEngine Pymongo with Django?

So I'm trying to return a JSON object for a project. I've spent a few hours trying to get Django just returning the JSON.
Heres the view that we've been working with:
def json(request, first_name):
user = User.objects.all()
#user = User.objects.all().values()
result = simplejson.dumps(user, default=json_util.default)
return HttpResponse(result)
Here's my model:
class User(Document):
gender = StringField( choices=['male', 'female', 'Unknown'])
age = IntField()
email = EmailField()
display_name = StringField(max_length=50)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
location = StringField(max_length=50)
status = StringField(max_length=50)
hideStatus = BooleanField()
photos = ListField(EmbeddedDocumentField('Photo'))
profile =ListField(EmbeddedDocumentField('ProfileItem'))
allProfile = ListField(EmbeddedDocumentField('ProfileItem')) #only return for your own profile
This is what it's returning:
[<User: User object>, <User: User object>] is not JSON serializable
Any thoughts on how I can just return the JSON?
With MongoEngine 0.8 or greater, objects and querysets have a to_json() method.
>>> User.objects.to_json()
simplejson.dumps() doesn't know how to "reach into" your custom objects; the default function, json_util.default must just be calling str() or repr() on your documents. (Is json_util custom code you've written? If so, showing its source here could prove my claim.)
Ultimately, your default function will need to be able to make sense of the MongoEngine documents. I can think of at least two ways that this might be implemented:
Write a custom default function that works for all MongoEngine documents by introspecting their _fields attribute (though note that the leading underscore means that this is part of the private API/implementation detail of MongoEngine and may be subject to change in future versions)
Have each of your documents implement a as_dict method which returns a dictionary representation of the object. This would work similarly to the to_mongo method provided on documents by MongoEngine, but shouldn't return the _types or _cls fields (again, these are implementation details of MongoEngine).
I'd suggest you go with option #2: the code will be cleaner and easier to read, better encapsulated, and won't require using any private APIs.
As dcrosta suggested you can do something like this, hope that will help you.
Document definition
class MyDocument(Document):
# Your document definition
def to_dict(self):
return mongo_to_dict_helper(self)
helper.py:
from mongoengine import StringField, ListField, IntField, FloatField
def mongo_to_dict_helper(obj):
return_data = []
for field_name in obj._fields:
if field_name in ("id",):
continue
data = obj._data[field_name]
if isinstance(obj._fields[field_name], StringField):
return_data.append((field_name, str(data)))
elif isinstance(obj._fields[field_name], FloatField):
return_data.append((field_name, float(data)))
elif isinstance(obj._fields[field_name], IntField):
return_data.append((field_name, int(data)))
elif isinstance(obj._fields[field_name], ListField):
return_data.append((field_name, data))
else:
# You can define your logic for returning elements
return dict(return_data)

Serialize in django witha query set that contains defer

i have i little problem, and that is how can serialize a django query with defer ?
I have this model :
class Evento(models.Model):
nome=models.CharField(max_length=100)
descricao=models.CharField(max_length=200,null=True)
data_inicio= models.DateTimeField()
data_fim= models.DateTimeField()
preco=models.DecimalField(max_digits=6,decimal_places=2)
consumiveis= models.CharField(max_length=5)
dress_code= models.CharField(max_length=6)
guest_list=models.CharField(max_length=15)
local = models.ForeignKey(Local)
user= models.ManyToManyField(User,null=True,blank=True)
def __unicode__(self):
return unicode('%s %s'%(self.nome,self.descricao))
my query is this :
eventos_totais = Evento.objects.defer("user").filter(data_inicio__gte=default_inicio,
data_fim__lte=default_fim)
it works fine i think (how can i check if the query has realy defer the field user ? ) but when i do:
json_serializer = serializers.get_serializer("json")()
eventos_totais = json_serializer.serialize(eventos_totais,
ensure_ascii=False,
use_natural_keys=True)
it always folow the natural keys for user and local, i need natural keys for this query because of the fields local. But i do not need the field user.
To serialize a subset of your models fields, you need to specify the fields argument to the serializers.serialize()
from django.core import serializers
data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
Ref: Django Docs