These are chat archives for django/django

2nd
Jul 2017
djangoReactGuy
@SanskarSans
Jul 02 2017 00:54
Can anyone help me to understand the following snippet with an example, please?
property_type = models.ForeignKey(PropertyType)
category = ChainedForeignKey(
      Category,
      chained_field='property_type',
      chained_model_field='property_type'
  )
class Category(models.Model):
    title = models.CharField(_('Category'), max_length=140)
    property_type = models.ForeignKey(PropertyType)
cs89gr
@cs89gr
Jul 02 2017 10:29
hello can i use in one django app two different python paths ?can someone to help me with some examples or docs for this tasks ?
Anish Shrestha
@annshress
Jul 02 2017 15:51
Does anyone know how can I annotate some numeric attribute, normalize that attribute, and keep those normalized values in the previously annotated field
Anish Shrestha
@annshress
Jul 02 2017 15:56
for example.
stores = Store.objects.annotate(distance=annotate_distance(lat, lon)) \
        .order_by("distance")[:4]
dis = list(stores.values_list('distance', flat=1))
print dis
for each in stores:
    print each.distance
    each.distance = (each.distance - dis[0])/(dis[3] - dis[0])
    print each.distance
0.0
1.39765803335
0.263105821585
2.40268722744
0.559099507248
3.89973898349
1.0
Its is printing out fine.
But when I do print stores.values_list('distance', flat=True)
>>> <QuerySet [0.504297652250371, 1.39765803335025, 2.40268722743759, 3.89973898349003]>
This is the resulting output.
How can i FIX this? Where did I go wrong?
John
@flyboy1565
Jul 02 2017 16:03
@annshress What you are seeing is a description of the model on the query set. Add a function to your class
Anish Shrestha
@annshress
Jul 02 2017 16:04
What kind of function
John
@flyboy1565
Jul 02 2017 16:05
sorry, had to switch from phone to laptop..
you need to do something like
def __str__(self):
    return 'how you want you model to look'
example of my own
class CommunicationsIssue(models.Model):
    store = models.ForeignKey(Store)
    issue = models.CharField(max_length=5, choices=issues_choices())
    ticket = models.CharField(max_length=100, null=True, blank=True)
    confirmed = models.BooleanField(default=False)
    down_since = models.DateTimeField(null=True, blank=True)
    last_checked = models.DateTimeField(auto_now=True)
    resolved = models.BooleanField(default=False)
    resolved_time = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return "{} - {} - {}".format(self.store.store_number, self.get_issue_display(), self.down_since)
this would show like <QuerySet ['2942 - Comms - 11:30am', '2942 - Comms - 11:30am', '2942 - Comms - 11:30am',]>
Anish Shrestha
@annshress
Jul 02 2017 16:08
No @flyboy1565 , You didn't get my question
John
@flyboy1565
Jul 02 2017 16:08
... ok?
oh some items are missing?
Anish Shrestha
@annshress
Jul 02 2017 16:10
I annotated a field to the queryset. And then i normalized the annotated values. And exchanged those annotated values with normalized ones, externally. But when I access those values later. They are non-normalized ones.
was i clear?
John
@flyboy1565
Jul 02 2017 16:12
weird... sorry outside my knowledge.. hopefully someone can help you out..
Anish Shrestha
@annshress
Jul 02 2017 16:12
I hope so.
John
@flyboy1565
Jul 02 2017 16:12
i've been trying all morning to serialize the model above so i get all related data
Anish Shrestha
@annshress
Jul 02 2017 16:14
related data, you mean?
John
@flyboy1565
Jul 02 2017 16:18
the field store (FK), and then another model where CommuncationsIssue is a FK.
Anish Shrestha
@annshress
Jul 02 2017 16:21
So you mean serializing foreignkey as well?
John
@flyboy1565
Jul 02 2017 16:22
ya...
here
class CommunicationsIssue(models.Model):
    store = models.ForeignKey(Store)
    issue = models.CharField(max_length=5, choices=issues_choices())
    ticket = models.CharField(max_length=100, null=True, blank=True)
    confirmed = models.BooleanField(default=False)
    down_since = models.DateTimeField(null=True, blank=True)
    last_checked = models.DateTimeField(auto_now=True)
    resolved = models.BooleanField(default=False)
    resolved_time = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return "{} - {} - {}".format(self.store.store_number, self.get_issue_display(), self.down_since)

    def total_time_down(self):
        if self.resolved is False:
            return (timezone.now() - self.down_since).total_seconds()
        return (self.resolved_time - self.down_since).total_seconds()


class WorkOn(models.Model):
    issue_id = models.ForeignKey('CommunicationsIssue')
    work_on_by = models.ForeignKey(User)
    work_on_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '{0} working on {1}-{2} for store {3} at {4}'.format(
            self.work_on_by,
            self.issue_id.pk,
            self.issue_id.get_issue_display(),
            self.issue_id.store.store_number, 
            self.work_on_at
            )
I'm trying to send all the data about the CommunictionsIssue via a post_save over Channels
my Store model , has a Longitude and Latitude as i'm going to map these on a Gmaps
Anish Shrestha
@annshress
Jul 02 2017 16:29
So, you want to create a store when you are creating your commicationissue?
John
@flyboy1565
Jul 02 2017 16:31

no, all of this is get only..

so When i create/update a CommunicationsIssue... it will send information about that comm issue to the user via Channels.

#signals.py

class CommunicationsIssue(models.Model):
    store = models.ForeignKey(Store)
    issue = models.CharField(max_length=5, choices=issues_choices())
    ticket = models.CharField(max_length=100, null=True, blank=True)
    confirmed = models.BooleanField(default=False)
    down_since = models.DateTimeField(null=True, blank=True)
    last_checked = models.DateTimeField(auto_now=True)
    resolved = models.BooleanField(default=False)
    resolved_time = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return "{} - {} - {}".format(self.store.store_number, self.get_issue_display(), self.down_since)

    def total_time_down(self):
        if self.resolved is False:
            return (timezone.now() - self.down_since).total_seconds()
        return (self.resolved_time - self.down_since).total_seconds()


class WorkOn(models.Model):
    issue_id = models.ForeignKey('CommunicationsIssue')
    work_on_by = models.ForeignKey(User)
    work_on_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '{0} working on {1}-{2} for store {3} at {4}'.format(
            self.work_on_by,
            self.issue_id.pk,
            self.issue_id.get_issue_display(),
            self.issue_id.store.store_number, 
            self.work_on_at
            )

    def __jdict__(self):
        return {
            'work_on_by': self.work_on_by.get_full_name(),
            'work_on_at': '{}'.format(self.work_on_at.strftime('%Y-%m-%d %H:%M:%S')),
            'work_on_id': str(self.pk),
        }
opps... sorry old data in my clip board
#signals.py
def send_notification(notification):
    logging.debug('send_notification. notification = %s', notification)
    Group("users").send({'text': dumps(notification)})


@receiver(post_save, sender=CommunicationsIssue)
def incident_post_save(sender, **kwargs):
    logging.debug('Sender = %s', sender)
    obj = CommunicationsIssue.objects.get(pk=kwargs['instance'].pk)
    instance = IssueSerializer(obj)
    send_notification({
        'type': 'post_save',
        'created': kwargs['created'],
        'feature': instance,
    })
Anish Shrestha
@annshress
Jul 02 2017 16:34
obj = CommunicationsIssue.objects.get(pk=kwargs['instance'].pk)
this is redundant
John
@flyboy1565
Jul 02 2017 16:35
how so?
Anish Shrestha
@annshress
Jul 02 2017 16:35
obj = kwargs['instance'] ?
John
@flyboy1565
Jul 02 2017 16:35
oh wait, yes it is.. i used it when i was trying to use the .related() or .all()
so if i return the kwargs]
kwarg['instance'], its ok, I get the data about only the CommuncationsIssue, but not about the WorkOn or the Store...
Anish Shrestha
@annshress
Jul 02 2017 16:38
what does sample instance.data look like
John
@flyboy1565
Jul 02 2017 16:38
idk.. hold on
Anish Shrestha
@annshress
Jul 02 2017 16:43
Thats weird that you dont get the related fields though, despite you are in the post_save handler.
http://www.django-rest-framework.org/api-guide/relations/ hope you have checked out related field serializer.
John
@flyboy1565
Jul 02 2017 16:44

```Exception Value:

<CommunicationsIssue: 2942 - Linux Down - 2017-07-01 22:43:23+00:00> is not JSON serializable```

I tried creating a serializer using REST as I have an API .
Anish Shrestha
@annshress
Jul 02 2017 16:47
it says not serializable?
John
@flyboy1565
Jul 02 2017 16:47
well thats what happens when i try instance.data
I have tried sooooo many things
Anish Shrestha
@annshress
Jul 02 2017 16:48
def incident_post_save(sender, **kwargs):
    logging.debug('Sender = %s', sender)
    obj = CommunicationsIssue.objects.get(pk=kwargs['instance'].pk)
    instance = IssueSerializer(obj).data  # <<<< this
    send_notification({
        'type': 'post_save',
        'created': kwargs['created'],
        'feature': instance,
    })
John
@flyboy1565
Jul 02 2017 16:48
ya
Anish Shrestha
@annshress
Jul 02 2017 16:48
are you sure you are doing this???
John
@flyboy1565
Jul 02 2017 16:49
I was earlier.. let me show you the output of that
{"type":"post_save","feature":{"id":3,"issue":"L","ticket":"12344","confirmed":true,"down_since":"2017-07-01T22:43:23Z","last_checked":"2017-07-02T16:49:22.995168Z","resolved":true,"resolved_time":"2017-07-02T16:47:00Z","store":2942},"created":false}
Anish Shrestha
@annshress
Jul 02 2017 16:50
I dont see anything wrong with it... now
John
@flyboy1565
Jul 02 2017 16:51
thats w'
my issue is that i wanted to get the Store and the WorkOn models in this response as well
Anish Shrestha
@annshress
Jul 02 2017 16:52
to get store,
modify your IssuerSerializer
class StoreSerializer(...)
  class Meta:
    ...

class IssueSerializer(...):
  store = StoreSerializer()
  class Meta:
     ...
John
@flyboy1565
Jul 02 2017 16:53
Lol
Anish Shrestha
@annshress
Jul 02 2017 16:53
What?
John
@flyboy1565
Jul 02 2017 16:54
I have a storedetailserializer.. but kept having problems becuase I was expecting to have to put in the object..
Read this.
John
@flyboy1565
Jul 02 2017 16:56
Ok... reading
John
@flyboy1565
Jul 02 2017 17:10
@annshress , thanks for the help. This now working
Anish Shrestha
@annshress
Jul 02 2017 17:11
you are welcome
Dennis Gathagu
@gathagu354
Jul 02 2017 22:54
hey everyone can anyone please help me solve this problem? ive been struggling for 2 days now and i just dont understand why im getting 403 forbidden
Capture.JPG
Hammad
@hammadzz
Jul 02 2017 23:25
I created a custom user model with a custom user manager. My username field is called member_code and it is also the primary key. When I run ./manage.py createsuperuser it first prompts for "member_code" when I enter the integer value and press enter it does not take the input. Instead it starts inserting strange characters.
What could cause this?
@gathagu354 are you serving it with nginx or dev server?
Dennis Gathagu
@gathagu354
Jul 02 2017 23:29
@hammadzz running it with nginx on a ubuntu 14.04 instance.