Re: Fetching next and/or prior objects given an arbitrary ordering

2018-03-01 Thread Mike Dewhirst

On 1/03/2018 5:44 PM, Bernd Wechner wrote:

Mike,

Yep, adding pk as a final tie breaker is trivial, but not the issue 
;-). Alas adding a sequencing field is not an option because I am 
looking for a generic solution, akin to what the admin site on Django 
offers, I have a model browser that I want to browse any of my models 
with.  And I was in fact using a date_time sequencer, only found that 
it broke in the generic sense for any ordering and with ties.


Moreover, without understanding the full context in your example you 
seem be fetching a pile of questions and then walking them to find the 
prior (I prefer the term "prior" as "last" has unfortunate ambiguity) 
and next questions, your set defined by 
"instruction_id=question.instruction.pk". My guess is that in your 
scenario that list is likely to be small (<1000 objects ;-)


actually < 20 but usually < 5 ie., human scale

and this strategy becomes unappealing again if that list could be 
arbitrarily large (millions, or more) which is true for a generic 
scenario which makes no assumptions about the model other than what is 
provided by its ordering and known about the current object.


Well something in the mix has to keep track of things. Maybe you need a 
query which fetches a handy bucket of objects guaranteed to contain the 
one you are interested in, single it out then 'next' or 'prior' until no 
more before fetching another bucket.


If it wasn't for people like you there'd be no progress ;)

Cheers

Mike



Regards,

Bernd.

Mike Dewhirst wrote:

On 1/03/2018 10:50 AM, Bernd Wechner wrote:
> Julio,
>
> Thanks for giving it some though. But I think you misread me a little. 
> I am using the get() only to illustrate that the precondition is, I 
> have a single object. The goal then is find a neighboring object (as 
> defined by the ordering in the model).

>
> Yes indeed, a filter is the first and primary candidate for achieving 
> that, but can you write one that respects an abritrary ordering 
> involving multiple fields, as I exemplified with:

>
> |
> classThing(models.Model):
>      field1 =...
>      field2 =...
>      field2 =...
> classMeta:
>          ordering =['field1','-field2','field3']
> |
>
> Also consider that the ordering thus specified does not stipulate 
> uniqueness in any way, that is many neighboring things in an ordered 
> list may have identical values of field1, field2 and field3.


Nothing to stop you adding 'pk' or '-pk' to the ordering list.

I have done something similar recently where an online training course
leads the user with next and previous links to the next or previous
questions. At the first and last question for each set of instruction,
the links morph into previous and next instruction.

My approach relies on there being only a few questions per instruction.
It isn't very elegant because it tramples over the 'last' values until
the last man standing is correct and it bails out as soon as it finds a
greater 'next' value.

I did need/want a separate numeric ordering field because a trainer
writing up a course needs a sequence to force instruction items and
questions into adjustable arbitrary orders. Hence, the model save()
method updates a num_sequence float field from the user entered sequence
char field.

I haven't thought about < or > in the context of your ['field1',
'-field2', 'field3'] ordering but I went for a num_sequence float field
because '11' < '2' but 2.0 < 11.0 and so on.

The view code goes like this ...

def get_last_next_question_links(question, instruction, course, user):
  lastlink = 'No previous question'
  nextlink = 'No more questions'
  questions = 
Question.objects.filter(instruction_id=question.instruction.pk)
  for obj in questions:
  if obj.num_sequence < question.num_sequence:
  lasturl = '/question/%s/' % obj.pk
  lastname = 'Previous Question %s' % obj.sequence
  lastlink = '%s' % (lasturl, lastname)
  elif obj.num_sequence > question.num_sequence:
  nexturl = '/question/%s/' % obj.pk
  nextname = 'Next Question %s' % obj.sequence
  nextlink = '%s' % (nexturl, nextname)
  break
  if lastlink.startswith('No'):
  lastlink = get_instruction_link(
  course, instruction, user, next=False
  )
  if nextlink.startswith('No'):
  nextlink = get_instruction_link(
  course, instruction, user, next=True
  )
  return lastlink, nextlink


hth

>
> I'm not sure how Django sorts those ties, but imagine it either defers 
> to the underlying database engine (i.e. uses the sort simply to 
> generate an ORDER BY clause in the SQL for example in the above case:

>
> |
> ORDER BY field1 ASC,field2 DESC,field3 ASC
> |
>
> and lets the underlying database engine define how ties are ordered. 
> Or it could add a pk tie breaker to the end. Matters little, the 
> problem remains: how to find neighbors given an arbitrar

Re: When do I need a new app within the site?

2018-03-01 Thread Derek

Mike Dewhirst wrote:
*I also have a "common" app to contain bits and pieces like utilities ...*

I don't keep these under apps; my project-wide utility-type code (code 
without Django Models) sits under a "utils" module (with further namespaces 
as needed), at the same level as "apps"  This means it can be equally 
accessed by other utility code or apps themselves.  In terms of the project 
"design space" that makes more sense to me, and also allows utility code to 
be used across projects as I know there is no dependancy on 
projects-specific apps.

My 2c!

On Thursday, 1 March 2018 00:36:24 UTC+2, Mike Dewhirst wrote:
>
> On 1/03/2018 4:46 AM, Karol Bujaček wrote: 
> > 
> > 
> > On 02/22/2018 09:44 AM, Cictani wrote: 
> >> Hi, 
> >> 
> >> I'm just beginning developing a new app(s) and I'm wondering when I 
> >> need to add a new app. if one app uses models from another app is 
> >> that a hint that these two apps are acutally one app or is this still 
> >> ok in terms of good design? 
> >> 
> >> Let's say I have a customer app (with customer models, admins etc) 
> >> and a booking app which of course uses the customer model. Would it 
> >> be good to have two apps or would it be actually only a booking app 
> >> which includes all the models, logic etc from the customer app? 
> >> 
> >> Thanks in advance 
> >> 
> >> Andreas 
> >> 
> > 
> > Hello Andreas, 
> > 
> > This issue bothers me too. For me, at the beginning it looks 
> > reasonable to create two (or more) different apps, but sooner or 
> > later, I’ve created a huge mess with too many dependencies between 
> > these apps. So, sometimes I feel that separating whole application is 
> > not the best idea. Obviously, there should be many lines of code which 
> > can/may/should be shared (= reusable app), but I think that almost 
> > always I need to make some customizations, add some ‘custom logic’ 
> > into views inside these apps... I don’t know how to grasp Django’s 
> > architecture, I feel that I’m missing something, that there should be 
> > something different than model & view & template. 
> > 
> > I've recently tried to read mentioned Two scoops of Django book, but 
> > it doesn't help me with this. (Or I didn't spend too much time reading 
> > it). 
> > 
> > 
> > Best regards, 
> > Karol 
> > 
> > 
>
> For me, it is relatively easy. When you think of an entire project and 
> draw it out on paper with boxes and lines you can see where the separate 
> portions naturally fall. 
>
> Some things (nearly) always exist in (nearly) all projects. For example, 
> users and user related items like profiles. For me, that means a 
> separate app. Likewise (for me) I keep companies in a separate app. 
> Licensed relationships between companies (for me) also go in the company 
> app. 
>
> I don't necessarily try to make them re-usable right away. Working on my 
> second project I just copied portions of the first and tweaked them as 
> necessary. If that starts to bother me in future I might rework one or 
> two apps so they become re-usable and supremely elegant. Maybe. 
>
> The idea is to become comfortable putting "from company 
> importAddress,Company, Division, Phone" and just use them without 
> thinking in your views, unit tests or other portions of your project 
> where they might be needed. At least I don't have to scratch my head and 
> try to remember where Address is defined. Of course it belongs in the 
> company app alongside Phone and Division. 
>
> One of my projects has an enormous app with 40 models. I tried to 
> separate them into two apps but my inexperience caused circular import 
> problems. That forced me to keep them all together. In hindsight keeping 
> them together was the right thing to do because those 40 models are all 
> in the same brainspace. 
>
> I also have a "common" app to contain bits and pieces like utilities, 
> generic template tags, exceptions imported from various places so I can 
> always say in my code everywhere "from common.exceptions import 
> ThisErrorOrThat". My common app doesn't have any models. 
>
> The bottom line is that you need to be comfortable in your own 
> brainspace. If you can think about slicing off the easy bits into 
> separate small apps it will leave the main game slightly more simple. 
> And that is always good! 
>
> Cheers 
>
> Mike 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e185a523-9661-4fe9-8038-275b56460bcd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: django-channels: WebSocketBridge options

2018-03-01 Thread nferrari
Understood! Thank you

On Wednesday, February 28, 2018 at 6:30:45 PM UTC+1, nferrari wrote:
>
> Hello,
>
> It seems that it is not possible to pass options to ReconnectingWebsocket 
> through WebSocketBridge. I'd like to do able to do so, like it's possible 
> with ReconnectingWebsocket 
> :
>
> var webSocketBridge = new channels.WebSocketBridge({maxRetries: 5});
>
> or
>
> var webSocketBridge = new channels.WebSocketBridge();
> webSocketBridge.maxRetries = 5;
>
> Did I miss something or is it a conception choice?
>
> Nicolas
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/45e53cae-5b81-458a-a58e-f5aca80b25b9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


GSOC WITH DJANGO

2018-03-01 Thread tola temitope
hey, good day guys i am a Django developer thats been building for almost a 
year now and i am participating with gsoc this year with django, I want to 
improve my skills, solve problems and build the community too.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5ab71783-19bf-479d-8f22-5eacf1d21b5b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Help needed - new very first django App

2018-03-01 Thread Jayaram Namburaj
Hi Kasper,

Thanks for your findings.
It is working now as per your suggestion.

Regards
JayaramN

On Wednesday, February 28, 2018 at 11:41:27 PM UTC+5:30, Kasper Laudrup 
wrote:
>
> Hi Jayaram, 
>
> On 2018-02-28 15:45, Jayaram Namburaj wrote: 
> > 
> > When running the url http://127.0.0.1:8000/myapp/exRenderDict/ output 
> > doesn't display the values which is from the for loop. 
>
> You named your list 'MyListArg' not 'mylist' in the dictionary you 
> passed to the render function. 
>
> Try changing this: 
>
> {% for val in mylist %} 
>
> To: 
>
> {% for val in MyListArg %} 
>
> That should hopefully fix it. I haven't tested it though. 
>
> Kind regards, 
>
> Kasper Laudrup 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/db812e3d-6d34-4907-97ee-a4ad98a41fec%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: OuterRef not being treated as an F Expression

2018-03-01 Thread Michael Barr
For what it is worth, it has been confirmed as a bug and 
fixed: https://code.djangoproject.com/ticket/29142

On Friday, February 9, 2018 at 7:52:50 AM UTC-5, Michael Barr wrote:
>
> According to the documentation on models.OuterRef 
> 
> :
>
> It acts like an F 
>> 
>>  expression 
>> except that the check to see if it refers to a valid field isn’t made until 
>> the outer queryset is resolved.
>
>
> I am experiencing an issue with this using the following example:
>
> class ExampleModel(models.Model):
> date = models.DateField()
> value = models.IntegerField()
>
>
> subquery = ExampleModel.objects.filter(
> date__gte=models.OuterRef('date') - timedelta(days=2),
> date__lte=models.OuterRef('date') + timedelta(days=2),
> value__lte=5
> )
> queryset = ExampleModel.objects.annotate(
> value_is_less_than_five=models.Exists(subquery)
> )
>
>  
> The result that I am getting is:
>
> AttributeError: 'ResolvedOuterRef' object has no attribute 
>> 'relabeled_clone'
>
>
> From my understanding, if this is similar to an F Expression, you should 
> be able to perform the timedelta on the OuterRef. I also found someone else 
> on StackOverflow 
> with
>  
> the same issue. 
>
> What I would like to know is if this is a bug (e.g. should it be 
> supported), or a documentation issue. 
>
> Thanks in advance for your assistance!
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4125b377-489a-4875-a233-567137d6ec35%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Is there a way to make a field both foreignKey or allow user to fill it in themself?

2018-03-01 Thread Alexander Joseph
I think the solution is above my head at the moment. I'll have to look back 
into it once I get better at Django. Thanks for your help though



On Tuesday, February 27, 2018 at 7:26:22 AM UTC-7, Alexander Joseph wrote:
>
> Is there a way to make a form field or model field either a foreign key 
> reference or allow the user to fill in something themselves? I'm making a 
> fixed assets app and each fixed asset has an owner field, which I would 
> like to assign to an app user if possible, and if not possible be able to 
> fill in a name myself.
>
> Thanks
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/11d20f64-4d3e-46c6-8919-ea88a6e7894d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Trying to create a CBV that allows user to copy a record

2018-03-01 Thread Alexander Joseph
Thanks!


On Wednesday, February 28, 2018 at 11:53:01 AM UTC-7, Dylan Reinhold wrote:
>
> Use the get_inital method.
>
> def get_initial(self):
> initial = super(MyCreateView, self).get_initial()
> initial['name'] = 'Testing'
> return initial
>
> Dylan
>
>
>
> On Wed, Feb 28, 2018 at 9:42 AM, Alexander Joseph  > wrote:
>
>> I'd like to create a CBV to allow users to copy a record, except for item 
>> specific information. - I'm making a fixed assets app and if there are 2 of 
>> the same laptop I'd like the user to be able to make one record in the 
>> database, then copy it minus the serial number and asset tag number which 
>> would be the only info the user would have to fill in to copy that laptop.
>>
>> Is there a way to do this by modifying the CreateView somehow? Thanks
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/e4c25ff6-9e6e-4e5d-898a-f6d977f9badc%40googlegroups.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d9dd8e57-7b2a-451b-8c88-bfcb4626e0d4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Fetching next and/or prior objects given an arbitrary ordering

2018-03-01 Thread C. Kirby
I'm having a hard time envisioning the SQL statement that could do what you 
are asking, without a sub select or something like that. If you can write 
the expression in sql you _might_ be able to get back to the ORM that would 
create that. Can you provide an sql  statement that does what you want for 
us to help you think about it?

On Wednesday, February 28, 2018 at 6:50:56 PM UTC-5, Bernd Wechner wrote:
>
> Julio,
>
> Thanks for giving it some though. But I think you misread me a little. I 
> am using the get() only to illustrate that the precondition is, I have a 
> single object. The goal then is find a neighboring object (as defined by 
> the ordering in the model).
>
> Yes indeed, a filter is the first and primary candidate for achieving 
> that, but can you write one that respects an abritrary ordering involving 
> multiple fields, as I exemplified with:
>
> class Thing(models.Model):
>  field1 = ...
>  field2 = ...
>  field2 = ...
>  class Meta:
>  ordering = ['field1', '-field2', 'field3']
>
> Also consider that the ordering thus specified does not stipulate 
> uniqueness in any way, that is many neighboring things in an ordered list 
> may have identical values of field1, field2 and field3. 
>
> I'm not sure how Django sorts those ties, but imagine it either defers to 
> the underlying database engine (i.e. uses the sort simply to generate an 
> ORDER BY clause in the SQL for example in the above case:
>
> ORDER BY field1 ASC, field2 DESC, field3 ASC
>
> and lets the underlying database engine define how ties are ordered. Or it 
> could add a pk tie breaker to the end. Matters little, the problem remains: 
> how to find neighbors given an arbitrary ordering and ties.
>
> Can you write a filter clause to do that? I'm curious on that front. 
>
> It's easy of course with one sort field with unique values collapsing to 
> an __gt or __lt filter folllowed by first() or last() respectively (not 
> sure that injects a LIMIT clause into the SQL or collects a list and then 
> creams one element from it - I'll test a little I think). 
>
> In the mean time, I still feel this has to be a fairly standard use case. 
> It's about browsing objects in a table one by one, with a next and previous 
> button given an ordering specified in the model and no guarantee of 
> uniqueness on the (sort keys).
>
> Regards,
>
> Bernd.
>
> On Thursday, 1 March 2018 00:58:58 UTC+11, Julio Biason wrote:
>>
>> Hi Bernd,
>>
>> Well, the thing with `get()` is that it will return only one object. What 
>> you're looking for is `filter()`.
>>
>> Say, you want all the things that have an ID after a certain value. So 
>> you get `list_of_things = Things.objects.filter(pk__gte=...)`. Now it'll 
>> return the list, with all elements after the one you asked.
>>
>> If you want the previous and next, you can do `list_of_previous = 
>> Things.objects.filter(pk__lt=...).limit(1)` and `list_of_next = 
>> Things.objects.filter(pk__gt).limit(1)`.
>>
>> Or something like that ;P
>>
>> On Wed, Feb 28, 2018 at 8:56 AM, Bernd Wechner  
>> wrote:
>>
>>> I'm a bit stumped on this. Given an arbitrary ordering as specified by 
>>> the ordering meta option:
>>>
>>> https://docs.djangoproject.com/en/2.0/ref/models/options/#ordering
>>>
>>> for example:
>>>
>>> class Thing(models.Model):
>>> field1 = ...
>>> field2 = ...
>>> field2 = ...
>>> class Meta:
>>> ordering = ['field1', '-field2', 'field3']
>>>
>>> given an instant of Thing:
>>>
>>> thing = Thing.objects.get(pk=...)
>>>
>>> how can I get the next Thing after that one, and/or the prior Thing 
>>> before that one as they appear on the sorted list of Things.
>>>
>>> It's got me stumped as I can't think of an easy way to build a filter 
>>> even with Q object for an arbitrary ordering given there can be multiple 
>>> fields in ordering and multiple Things can have the same ordering list 
>>> (i.e. there can be ties - that Django must resolve either arbitrarily or 
>>> with an implicit pk tie breaker on ordering).
>>>
>>> It's got me stumped. I can solve any number of simpler problems just not 
>>> his generic one (yet). 
>>>
>>> Ideally I'd not build a list of all objects (waste of memory with large 
>>> collections), and look for my thing in the list and then pick out the next 
>>> or prior. 
>>>
>>> I'd ideally like to fetch it in one query returning the one Thing, or if 
>>> not possible no worse than returning all Things on side of it and picking 
>>> off the first or last respectively (even that's kludgy IMHO).
>>>
>>> I'm using postgresql and I found a related question here:
>>>
>>> 
>>> https://dba.stackexchange.com/questions/53862/select-next-and-previous-rows
>>>
>>> but would rather stick with the ORM and not even explore SQL (just took 
>>> a peak to see SQL can be constructed to do it I guess, as if not, the ORM 
>>> sure won't have a good way of doing it methinks).
>>>
>>> I'd have thought this a sufficiently common use case but am

Re: UUIDs eventually choke as primary key

2018-03-01 Thread M Mackey
I added some debug support, and there are only two classes called UUID when 
this fails:
uuid   UUID: 
psycopg2.extensions   UUID: 

The psycopg extension is a converter, and it seems highly unlikely that it 
was put into place as the value, and I doubt it would report it's __str__ 
as the UUID string, so it does not appear to be a case of mistaken 
identity. Which makes the failure of "not instance" to catch the UUID after 
a while all the more weird...

I'm pretty baffled on this one. Am I really the only one running into this?

M

On Friday, February 23, 2018 at 1:17:34 PM UTC-8, M Mackey wrote:
>
> Not to belabor the point, but this is the part that I find weird. This is 
> down in the "During handling of the above exception ('UUID' object has no 
> attribute 'replace'), another exception occurred" section.
>
> /usr/local/venvs/attrack/lib/python3.6/site-packages/django/db/models/fields/__init__.py
>  
> in to_python
> if value is not None and not isinstance(value, uuid.UUID): << 
> 1) CHECKS FOR NOT UUID
> try:
> return uuid.UUID(value)  <<- 2) Pretty sure first 
> exception is in here
> except (AttributeError, ValueError):
> raise exceptions.ValidationError(
> self.error_messages['invalid'],
> code='invalid',
> params={'value': value}, <<--  Traceback says new 
> exception here
> )
> return value
>
> Local vars
> Variable Value
> self 
> value UUID('338fa43f-3e07-4e83-8525-d195d2fc64d4')  << 3) REPORTS 
> AS UUID
>
> So, if 3) is right and 'value' is a UUID, 1) should keep us from getting 
> to 2). But we get there.
>
> On Friday, February 23, 2018 at 12:59:28 PM UTC-8, M Mackey wrote:
>>
>> Adding details I seem to have left out. The id is defined like this:
>> id = models.UUIDField(primary_key=True, default=uuid.uuid1, 
>> editable=False)
>> and I'm running on PostgreSQL.
>> I'm pretty sure I never create a row without already having the key.
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/fd5fb988-78ae-40b7-ab5f-ca2d361b7d56%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


ChoiceField avec valeur cochée par défaut

2018-03-01 Thread Niche
Bonjour! comment faire pour avoir un radiobox (ChoiceField) coché avec une 
valeur par defaut ? 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f7879a8d-a17c-4d91-bbbf-8a3f73163438%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: 'ModelFormOptions' object has no attribute 'label'

2018-03-01 Thread Anup Yadav
Could you solve this issue? May I know what was the issue? I'm facing this 
issue right now.

On Monday, August 21, 2017 at 11:41:29 AM UTC+5:30, Lachlan Musicman wrote:
>
> Hi All,
>
> I'm seeing this error when I start my uwsgi
>
>
>
> > Exception Type: AttributeError Exception Value:
> >
> > 'ModelFormOptions' object has no attribute 'label'
>
> > Exception Location: 
> /opt/virtualenvs/traceback/lib/python3.4/site-packages/django/forms/models.py 
> in _get_foreign_key, line 1023
>
>
>
>
> But I can't find anything in the documents that might suggest what's 
> causing it, and my google fu is failing me. Running Centos 7, py 3.4 from 
> EPEL. Everything in a virtualenv
>
> Was working until I implemented inlineformset_factory with:
>
> ChemoRegimeFormSet = inlineformset_factory(Patient, ChemoRegime, extra=1)
>
> Patient has a m2m connection to ChemoType, which is through ChemoRegime.
>
> (ie, ChemoRegime has the FK to Patient, and an FK to ChemoType)
>
> What am I doing wrong, how can I fix it?
>
> cheers
> L.
>
>
> --
> "The antidote to apocalypticism is *apocalyptic civics*. Apocalyptic 
> civics is the insistence that we cannot ignore the truth, nor should we 
> panic about it. It is a shared consciousness that our institutions have 
> failed and our ecosystem is collapsing, yet we are still here — and we are 
> creative agents who can shape our destinies. Apocalyptic civics is the 
> conviction that the only way out is through, and the only way through is 
> together. "
>
> *Greg Bloom* @greggish 
> https://twitter.com/greggish/status/873177525903609857
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/bf4d29e4-6ae6-4fd7-8748-7e9c106233ac%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Channels: channel_layer appears to time out

2018-03-01 Thread operator
Hello,

I have a project that uses Channels as a worker queue, with a SyncConsumer 
that runs a heavy computation task. This works great.

I transitioned the project to have a 'task in process' page that opens a 
websocket and through the magic of channel's groups it gets pushed the 
computation updates as they happen. This works great.

I'm now transitioning the project to be a single-page-app that communicates 
via a websocket. Using `runserver`, this works great, the websocket stays 
open. However, the messages from the SyncConsumer stop after a few seconds. 
I've established that time is whatever the value of 
`websocket_handshake_timeout` is, but this doesn't make sense to me AFAIK 
as the channel_layer is independent from the JsonWebsocketConsumer 
instance, and the websocket is happily connected and still passing messages.

Any ideas? Is this a bug or am I doing something wrong? 

Thanks,

Toby

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a329b26e-89f5-42d1-86b2-28ad1c85bb90%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Channels 2: Consumer running twice when two users simultaneously share socket

2018-03-01 Thread lakeshow
I am running into an issue using Channels where if two users are connected 
to the same socket, the consumer will run twice. When a single user is 
connected, only once.  
So in practice: when I have two users chatting with each other over 
channels, a single sent message will be run through the consumer twice, 
causing it to save twice to the database. However, if there is only one 
participant in the channel, the message will run through the consumer once 
and save once as expected.  

What might be the issue?  

Here is the consumer:  

class ChatConsumer(AsyncJsonWebsocketConsumer):  
...
async def receive_json(self, content):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Messages will have a "command" key we can switch on
command = content.get("command", None)
recipient = content.get("recipient", None)
sender = self.scope["user"]
try:
if command == "join":
# Make them join the room
await self.join_room(content["room"])
previous_message_list = await get_saved_messages(recipient, 
sender)
for msg in previous_message_list:
await self.send_json({
"msg_type": MSG_TYPE_MESSAGE,
"room": content["room"],
"username": msg.sender.user.username,
"message": msg.message,
},)
elif command == "leave":
# Leave the room
await self.leave_room(content["room"])
elif command == "send":
await self.send_room(
content["room"],
content["message"],
content["recipient"]
)
except ClientError as e:
# Catch any errors and send it back
await self.send_json({"error": e.code})  
...
async def send_room(self, room_id, message, recipient):
"""
Called by receive_json when someone sends a message to a room.
"""
# Check they are in this room
if room_id not in self.rooms:
raise ClientError("ROOM_ACCESS_DENIED")
# Get the room and send to the group about it
room = await get_room_or_error(room_id, self.scope["user"])
await self.channel_layer.group_send(
room.group_name,
{
"type": "chat.message",
"room_id": room_id,
"username": self.scope["user"].username,
"message": message,
"recipient": recipient,
}
)  
...
async def chat_message(self, event):
"""
Called when someone has messaged our chat.
"""
# Send a message down to the client
# Save message object
await save_message_object(
sender=event["username"],
message=event["message"],
recipient=event["recipient"]
)
await self.send_json(
{
"msg_type": MSG_TYPE_MESSAGE,
"room": event["room_id"],
"username": event["username"],
"message": event["message"],
},
)  


So something is causing the last function--def chat_message() to run twice 
and I think it's in the consumer and not related to the client because sent 
messages will log to the console only once--as soon as the messages are 
sent over socket.send, there will be two of the same Message objects saved 
onto the db.

Here is code relating to the actual save. It is in utils.py and is 
decorated using sync_to_async in order to call the sync func from an async 
consumer:  

@database_sync_to_asyncdef save_message_object(sender, message, recipient):
recipient = Profile.objects.get(user__username=recipient)
sender = Profile.objects.get(user__username=sender)
m = Message(sender=sender, message=message, recipient=recipient)
m.save()
print(datetime.datetime.now())

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1a8b04b5-088e-41bd-a0f1-53d326f5f8e9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Channels: channel_layer appears to time out

2018-03-01 Thread Andrew Godwin
Hi Toby,

Do you have the latest versions of daphne, channels, asgiref and
channels_redis? This sounds supiciously like a bug I fixed a couple weeks
ago.

Andrew

On Thu, Mar 1, 2018 at 5:45 AM,  wrote:

> Hello,
>
> I have a project that uses Channels as a worker queue, with a SyncConsumer
> that runs a heavy computation task. This works great.
>
> I transitioned the project to have a 'task in process' page that opens a
> websocket and through the magic of channel's groups it gets pushed the
> computation updates as they happen. This works great.
>
> I'm now transitioning the project to be a single-page-app that
> communicates via a websocket. Using `runserver`, this works great, the
> websocket stays open. However, the messages from the SyncConsumer stop
> after a few seconds. I've established that time is whatever the value of
> `websocket_handshake_timeout` is, but this doesn't make sense to me AFAIK
> as the channel_layer is independent from the JsonWebsocketConsumer
> instance, and the websocket is happily connected and still passing messages.
>
> Any ideas? Is this a bug or am I doing something wrong?
>
> Thanks,
>
> Toby
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/a329b26e-89f5-42d1-86b2-28ad1c85bb90%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAFwN1upW8q-vLWMpZ7-sMoj1b61uyrPMgV7V8PS2AX0zjqSO4g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Channels 2: Consumer running twice when two users simultaneously share socket

2018-03-01 Thread Andrew Godwin
Can you clarify what you mean by "two users connected to the same socket"?
If you have two websockets connected, you'll have two copies of your
consumer running, one for each socket.

Andrew

On Thu, Mar 1, 2018 at 7:52 AM, lakeshow  wrote:

> I am running into an issue using Channels where if two users are connected
> to the same socket, the consumer will run twice. When a single user is
> connected, only once.
> So in practice: when I have two users chatting with each other over
> channels, a single sent message will be run through the consumer twice,
> causing it to save twice to the database. However, if there is only one
> participant in the channel, the message will run through the consumer once
> and save once as expected.
>
> What might be the issue?
>
> Here is the consumer:
>
> class ChatConsumer(AsyncJsonWebsocketConsumer):
> ...
> async def receive_json(self, content):
> """
> Called when we get a text frame. Channels will JSON-decode the payload
> for us and pass it as the first argument.
> """
> # Messages will have a "command" key we can switch on
> command = content.get("command", None)
> recipient = content.get("recipient", None)
> sender = self.scope["user"]
> try:
> if command == "join":
> # Make them join the room
> await self.join_room(content["room"])
> previous_message_list = await get_saved_messages(recipient, 
> sender)
> for msg in previous_message_list:
> await self.send_json({
> "msg_type": MSG_TYPE_MESSAGE,
> "room": content["room"],
> "username": msg.sender.user.username,
> "message": msg.message,
> },)
> elif command == "leave":
> # Leave the room
> await self.leave_room(content["room"])
> elif command == "send":
> await self.send_room(
> content["room"],
> content["message"],
> content["recipient"]
> )
> except ClientError as e:
> # Catch any errors and send it back
> await self.send_json({"error": e.code})
> ...
> async def send_room(self, room_id, message, recipient):
> """
> Called by receive_json when someone sends a message to a room.
> """
> # Check they are in this room
> if room_id not in self.rooms:
> raise ClientError("ROOM_ACCESS_DENIED")
> # Get the room and send to the group about it
> room = await get_room_or_error(room_id, self.scope["user"])
> await self.channel_layer.group_send(
> room.group_name,
> {
> "type": "chat.message",
> "room_id": room_id,
> "username": self.scope["user"].username,
> "message": message,
> "recipient": recipient,
> }
> )
> ...
> async def chat_message(self, event):
> """
> Called when someone has messaged our chat.
> """
> # Send a message down to the client
> # Save message object
> await save_message_object(
> sender=event["username"],
> message=event["message"],
> recipient=event["recipient"]
> )
> await self.send_json(
> {
> "msg_type": MSG_TYPE_MESSAGE,
> "room": event["room_id"],
> "username": event["username"],
> "message": event["message"],
> },
> )
>
>
> So something is causing the last function--def chat_message() to run twice
> and I think it's in the consumer and not related to the client because sent
> messages will log to the console only once--as soon as the messages are
> sent over socket.send, there will be two of the same Message objects saved
> onto the db.
>
> Here is code relating to the actual save. It is in utils.py and is
> decorated using sync_to_async in order to call the sync func from an async
> consumer:
>
> @database_sync_to_asyncdef save_message_object(sender, message, recipient):
> recipient = Profile.objects.get(user__username=recipient)
> sender = Profile.objects.get(user__username=sender)
> m = Message(sender=sender, message=message, recipient=recipient)
> m.save()
> print(datetime.datetime.now())
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https

How to access the key attributes of a model

2018-03-01 Thread Alberto Sanmartin
This is mi code:

models.py:

@autoconnect
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.CharField(max_length=100, blank=True)
description = models.CharField(max_length=200)
creation_date = models.DateTimeField(auto_now_add=True)

def __unicode__(self):
return self.name

def pre_save(self):
"""metodo de la clase Category para calcular el slug de una 
categoria"""
self.slug = self.name.replace(" ", "_").lower()
print(self.slug)


@autoconnect
class Post(models.Model):
Status = ((1, "Publicado"), (2, "Borrador"), (3, "Eliminado"))
status = models.IntegerField(choices=Status, default=2, blank=False)
title = models.CharField(max_length=100, blank=False)
slug = models.CharField(max_length=100, default=' ', blank=True)
description = models.CharField(max_length=200, blank=False)
content = models.TextField(default=" ", blank=False)
category = models.ForeignKey(Category, default=1, blank=False)
creation_date = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to="photos", default='/image.jpg', 
blank=False)
author = models.ForeignKey(User, default=1)

views.py:

def blog(request):
posts = models.Post.objects.filter(status=1).order_by("-creation_date")
print(posts)
categories = models.Category.objects.order_by("name")
context = {
"posts":posts,
"categories":categories
}
return render(request, "blog.html", context)

urls.py:

url(r'^blog/categorias/(?P\w+)/$', views.blog_category_posts, 
name='blog_category_posts'),

blog.html:

{% for post in posts %}
{{ post.title }}
{{ post.description }}
{{ 
post.category.name }}
{{ post.author.username }}
{{ post.creation_date }}
{% endfor %}

When I click on the link of the category in the blog.html, I want to be 
able to pass the attribute slug to url, but it does not work.
Please help
Thanks in advance. 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/dccfe67f-c6cc-4239-91ef-2c9a85b43099%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Fetching next and/or prior objects given an arbitrary ordering

2018-03-01 Thread Bernd Wechner
I too have a hard time envisioning the SQL, so yes, I tried that. 
Haven't got past the one I cited in first post yet:


   https://dba.stackexchange.com/questions/53862/select-next-and-previous-rows
   

but it contains some very specific function LAG and LEAD which I can see 
Postgresql, MySQL, MS-SQL supports these by SQLlite does not (perhaps 
not a crisis as I expect we could ignore SQLlite in what I implement).


LAG and LEAD are analytic functions that provide access to precisely 
what I want, the prior and next tuple(s).


But you can using them write something like this (in pro forma):

   SELECT  *,  LAG(id) over (order by ...) as prior, LEAD(id) over
   (order by ...) as next
   FROM table
   WHERE id = myid

This will produce one tuple which has two new columns, prior and next, 
which contain the id of the prior and next tuples to that with myid 
following the specified order by.


Alas it uses two analytic functions I'm not sure the ORM supports. I 
think if not there's a fair case to put to Django to implement this as 
it's a fairly ordinary use case (finding neighboring objects in the 
models ordering).


There may be a way to replicate LAG and LEAD using self joins, with even 
better performance:


   
https://dba.stackexchange.com/questions/158374/performance-comparison-between-using-join-and-window-function-to-get-lead-and-la/158429

   http://sqlblog.com/blogs/michael_zilberstein/archive/2012/03/14/42332.aspx

Regards,

Bernd.

On 2/03/2018 3:48 AM, C. Kirby wrote:
I'm having a hard time envisioning the SQL statement that could do 
what you are asking, without a sub select or something like that. If 
you can write the expression in sql you _might_ be able to get back to 
the ORM that would create that. Can you provide an sql  statement that 
does what you want for us to help you think about it?


On Wednesday, February 28, 2018 at 6:50:56 PM UTC-5, Bernd Wechner wrote:

Julio,

Thanks for giving it some though. But I think you misread me a
little. I am using the get() only to illustrate that the
precondition is, I have a single object. The goal then is find a
neighboring object (as defined by the ordering in the model).

Yes indeed, a filter is the first and primary candidate for
achieving that, but can you write one that respects an abritrary
ordering involving multiple fields, as I exemplified with:

|
classThing(models.Model):
     field1 =...
     field2 =...
     field2 =...
classMeta:
         ordering =['field1','-field2','field3']
|

Also consider that the ordering thus specified does not stipulate
uniqueness in any way, that is many neighboring things in an
ordered list may have identical values of field1, field2 and field3.

I'm not sure how Django sorts those ties, but imagine it either
defers to the underlying database engine (i.e. uses the sort
simply to generate an ORDER BY clause in the SQL for example in
the above case:

|
ORDER BY field1 ASC,field2 DESC,field3 ASC
|

and lets the underlying database engine define how ties are
ordered. Or it could add a pk tie breaker to the end. Matters
little, the problem remains: how to find neighbors given an
arbitrary ordering and ties.

Can you write a filter clause to do that? I'm curious on that front.

It's easy of course with one sort field with unique values
collapsing to an __gt or __lt filter folllowed by first() or
last() respectively (not sure that injects a LIMIT clause into the
SQL or collects a list and then creams one element from it - I'll
test a little I think).

In the mean time, I still feel this has to be a fairly standard
use case. It's about browsing objects in a table one by one, with
a next and previous button given an ordering specified in the
model and no guarantee of uniqueness on the (sort keys).

Regards,

Bernd.

On Thursday, 1 March 2018 00:58:58 UTC+11, Julio Biason wrote:

Hi Bernd,

Well, the thing with `get()` is that it will return only one
object. What you're looking for is `filter()`.

Say, you want all the things that have an ID after a certain
value. So you get `list_of_things =
Things.objects.filter(pk__gte=...)`. Now it'll return the
list, with all elements after the one you asked.

If you want the previous and next, you can do
`list_of_previous =
Things.objects.filter(pk__lt=...).limit(1)` and `list_of_next
= Things.objects.filter(pk__gt).limit(1)`.

Or something like that ;P

On Wed, Feb 28, 2018 at 8:56 AM, Bernd Wechner
 wrote:

I'm a bit stumped on this. Given an arbitrary ordering as
specified by the ordering meta option:

https://docs.djangoproject.com/en/2.0/ref/models/options/#ordering
 

Re: ChoiceField avec valeur cochée par défaut

2018-03-01 Thread Simon Charette
Bonsoir Niche,

Tu devrais être en mesure d'y arriver en t'assurant que le formulaire 
(Form) comprenant
ce champ ait ta valeur ta valeur par défaut comme initial data.

exemple

class MyForm(forms.Form):
field = ChoiceField(widget=widgets.RadioSelect, choices=['un', 'deux', 
'trois'])

form = MyForm(initial={'field': 'deux'})

Au plaisir,
Simon

Le jeudi 1 mars 2018 16:46:58 UTC-5, Niche a écrit :
>
> Bonjour! comment faire pour avoir un radiobox (ChoiceField) coché avec une 
> valeur par defaut ? 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6d0131a1-897b-4596-ba91-af229ee72df9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Fetching next and/or prior objects given an arbitrary ordering

2018-03-01 Thread Bernd Wechner

Good news is that Django 2.0 is out and does support the Window functions:

https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#lag

Though it will mean a) upgrading on my dev box, c) working out how to 
use it and if happy, c) upgrading on my production box and rolling it out.


Great to see Django evolving though and the hope this SQL solution I 
just shared may be implementable in the ORM.


There's also a fine tutorial here:

https://agiliq.com/blog/2017/12/django-20-window-expressions-tutorial/

and it looks like a filter can be annotated with such window functions 
and all migth work neatly in Django 2.0 ORM.


Regards,

Bernd.

On 2/03/2018 3:48 AM, C. Kirby wrote:
I'm having a hard time envisioning the SQL statement that could do 
what you are asking, without a sub select or something like that. If 
you can write the expression in sql you _might_ be able to get back to 
the ORM that would create that. Can you provide an sql  statement that 
does what you want for us to help you think about it?


On Wednesday, February 28, 2018 at 6:50:56 PM UTC-5, Bernd Wechner wrote:

Julio,

Thanks for giving it some though. But I think you misread me a
little. I am using the get() only to illustrate that the
precondition is, I have a single object. The goal then is find a
neighboring object (as defined by the ordering in the model).

Yes indeed, a filter is the first and primary candidate for
achieving that, but can you write one that respects an abritrary
ordering involving multiple fields, as I exemplified with:

|
classThing(models.Model):
     field1 =...
     field2 =...
     field2 =...
classMeta:
         ordering =['field1','-field2','field3']
|

Also consider that the ordering thus specified does not stipulate
uniqueness in any way, that is many neighboring things in an
ordered list may have identical values of field1, field2 and field3.

I'm not sure how Django sorts those ties, but imagine it either
defers to the underlying database engine (i.e. uses the sort
simply to generate an ORDER BY clause in the SQL for example in
the above case:

|
ORDER BY field1 ASC,field2 DESC,field3 ASC
|

and lets the underlying database engine define how ties are
ordered. Or it could add a pk tie breaker to the end. Matters
little, the problem remains: how to find neighbors given an
arbitrary ordering and ties.

Can you write a filter clause to do that? I'm curious on that front.

It's easy of course with one sort field with unique values
collapsing to an __gt or __lt filter folllowed by first() or
last() respectively (not sure that injects a LIMIT clause into the
SQL or collects a list and then creams one element from it - I'll
test a little I think).

In the mean time, I still feel this has to be a fairly standard
use case. It's about browsing objects in a table one by one, with
a next and previous button given an ordering specified in the
model and no guarantee of uniqueness on the (sort keys).

Regards,

Bernd.

On Thursday, 1 March 2018 00:58:58 UTC+11, Julio Biason wrote:

Hi Bernd,

Well, the thing with `get()` is that it will return only one
object. What you're looking for is `filter()`.

Say, you want all the things that have an ID after a certain
value. So you get `list_of_things =
Things.objects.filter(pk__gte=...)`. Now it'll return the
list, with all elements after the one you asked.

If you want the previous and next, you can do
`list_of_previous =
Things.objects.filter(pk__lt=...).limit(1)` and `list_of_next
= Things.objects.filter(pk__gt).limit(1)`.

Or something like that ;P

On Wed, Feb 28, 2018 at 8:56 AM, Bernd Wechner
 wrote:

I'm a bit stumped on this. Given an arbitrary ordering as
specified by the ordering meta option:

https://docs.djangoproject.com/en/2.0/ref/models/options/#ordering


for example:

class Thing(models.Model):
    field1 = ...
    field2 = ...
    field2 = ...
    class Meta:
    ordering = ['field1', '-field2', 'field3']

given an instant of Thing:

thing = Thing.objects.get(pk=...)

how can I get the next Thing after that one, and/or the
prior Thing before that one as they appear on the sorted
list of Things.

It's got me stumped as I can't think of an easy way to
build a filter even with Q object for an arbitrary
ordering given there can be multiple fields in ordering
and multiple Things can have the same ordering list (i.e.
there can

Re: How to access the key attributes of a model

2018-03-01 Thread Dylan Reinhold
That seems right. Do you get an error, or just no data in the url?
You should also look into the slugify helper,
https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.text.slugify

Dylan

On Thu, Mar 1, 2018 at 2:37 PM, Alberto Sanmartin <
albertosanmartinmarti...@gmail.com> wrote:

> This is mi code:
>
> models.py:
>
> @autoconnect
> class Category(models.Model):
> name = models.CharField(max_length=100)
> slug = models.CharField(max_length=100, blank=True)
> description = models.CharField(max_length=200)
> creation_date = models.DateTimeField(auto_now_add=True)
>
> def __unicode__(self):
> return self.name
>
> def pre_save(self):
> """metodo de la clase Category para calcular el slug de una
> categoria"""
> self.slug = self.name.replace(" ", "_").lower()
> print(self.slug)
>
>
> @autoconnect
> class Post(models.Model):
> Status = ((1, "Publicado"), (2, "Borrador"), (3, "Eliminado"))
> status = models.IntegerField(choices=Status, default=2, blank=False)
> title = models.CharField(max_length=100, blank=False)
> slug = models.CharField(max_length=100, default=' ', blank=True)
> description = models.CharField(max_length=200, blank=False)
> content = models.TextField(default=" ", blank=False)
> category = models.ForeignKey(Category, default=1, blank=False)
> creation_date = models.DateTimeField(auto_now_add=True)
> image = models.ImageField(upload_to="photos", default='/image.jpg',
> blank=False)
> author = models.ForeignKey(User, default=1)
>
> views.py:
>
> def blog(request):
> posts = models.Post.objects.filter(status=1).order_by("-creation_
> date")
> print(posts)
> categories = models.Category.objects.order_by("name")
> context = {
> "posts":posts,
> "categories":categories
> }
> return render(request, "blog.html", context)
>
> urls.py:
>
> url(r'^blog/categorias/(?P\w+)/$', views.blog_category_posts,
> name='blog_category_posts'),
>
> blog.html:
>
> {% for post in posts %}
> {{ post.title }}
> {{ post.description }}
> {{ post.category.name }}
> {{ post.author.username }}
> {{ post.creation_date }}
> {% endfor %}
>
> When I click on the link of the category in the blog.html, I want to be
> able to pass the attribute slug to url, but it does not work.
> Please help
> Thanks in advance.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/dccfe67f-c6cc-4239-91ef-2c9a85b43099%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHtg44BxTh95oR6ctHt4E8DhO2SwShkiyA0t67jg_eFFoFbofA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Channels 2: Consumer running twice when two users simultaneously share socket

2018-03-01 Thread lakeshow
Sure. The JS code is essentially identical to your example. By "two users 
connected", I simply meant two users have clicked to join in a chatroom by 
way of `socket.send()`.   

I've tested it by using two different browsers and having users log in to 
join the same room. When they are both "connected"(in the same room) and 
chatting to each other, any message that either party sends will be 
broadcast only once to the chatroom(as it should be), but save twice into 
the database--two copies of a message will be saved.  

channels==2.0.2

channels-redis==2.1.0

Django==1.11.8

redis==2.10.6

asgi-redis==1.4.3

asgiref==2.1.6

daphne==2.0.4

I'm realizing now that I've a lot of left-over installs since upgrading 
from Channels 1.x. I'm no longer even sure which I need. Could this be the 
issue? 


On Friday, March 2, 2018 at 6:49:41 AM UTC+9, Andrew Godwin wrote:
>
> Can you clarify what you mean by "two users connected to the same socket"? 
> If you have two websockets connected, you'll have two copies of your 
> consumer running, one for each socket.
>
> Andrew
>
> On Thu, Mar 1, 2018 at 7:52 AM, lakeshow > 
> wrote:
>
>> I am running into an issue using Channels where if two users are 
>> connected to the same socket, the consumer will run twice. When a single 
>> user is connected, only once.  
>> So in practice: when I have two users chatting with each other over 
>> channels, a single sent message will be run through the consumer twice, 
>> causing it to save twice to the database. However, if there is only one 
>> participant in the channel, the message will run through the consumer once 
>> and save once as expected.  
>>
>> What might be the issue?  
>>
>> Here is the consumer:  
>>
>> class ChatConsumer(AsyncJsonWebsocketConsumer):  
>> ...
>> async def receive_json(self, content):
>> """
>> Called when we get a text frame. Channels will JSON-decode the 
>> payload
>> for us and pass it as the first argument.
>> """
>> # Messages will have a "command" key we can switch on
>> command = content.get("command", None)
>> recipient = content.get("recipient", None)
>> sender = self.scope["user"]
>> try:
>> if command == "join":
>> # Make them join the room
>> await self.join_room(content["room"])
>> previous_message_list = await get_saved_messages(recipient, 
>> sender)
>> for msg in previous_message_list:
>> await self.send_json({
>> "msg_type": MSG_TYPE_MESSAGE,
>> "room": content["room"],
>> "username": msg.sender.user.username,
>> "message": msg.message,
>> },)
>> elif command == "leave":
>> # Leave the room
>> await self.leave_room(content["room"])
>> elif command == "send":
>> await self.send_room(
>> content["room"],
>> content["message"],
>> content["recipient"]
>> )
>> except ClientError as e:
>> # Catch any errors and send it back
>> await self.send_json({"error": e.code})  
>> ...
>> async def send_room(self, room_id, message, recipient):
>> """
>> Called by receive_json when someone sends a message to a room.
>> """
>> # Check they are in this room
>> if room_id not in self.rooms:
>> raise ClientError("ROOM_ACCESS_DENIED")
>> # Get the room and send to the group about it
>> room = await get_room_or_error(room_id, self.scope["user"])
>> await self.channel_layer.group_send(
>> room.group_name,
>> {
>> "type": "chat.message",
>> "room_id": room_id,
>> "username": self.scope["user"].username,
>> "message": message,
>> "recipient": recipient,
>> }
>> )  
>> ...
>> async def chat_message(self, event):
>> """
>> Called when someone has messaged our chat.
>> """
>> # Send a message down to the client
>> # Save message object
>> await save_message_object(
>> sender=event["username"],
>> message=event["message"],
>> recipient=event["recipient"]
>> )
>> await self.send_json(
>> {
>> "msg_type": MSG_TYPE_MESSAGE,
>> "room": event["room_id"],
>> "username": event["username"],
>> "message": event["message"],
>> },
>> )  
>>
>>
>> So something is causing the last function--def chat_message() to run 
>> twice and I think it's in the consumer and not related to the client 
>> because sent messages will log to the console only once--as soon as

Re: Channels 2: Consumer running twice when two users simultaneously share socket

2018-03-01 Thread Andrew Godwin
The problem appears to be that you are saving to the database inside the
chat_message handler - since you're sending a message of type
"chat.message" to the group, that means everything in the group is going to
receive the message, run that handler, and save (so with 2 connected you
get 2 saves, etc.)

I'd recommend saving instead where you send to the group.

Andrew

On Thu, Mar 1, 2018 at 10:02 PM, lakeshow  wrote:

> Sure. The JS code is essentially identical to your example. By "two users
> connected", I simply meant two users have clicked to join in a chatroom by
> way of `socket.send()`.
>
> I've tested it by using two different browsers and having users log in to
> join the same room. When they are both "connected"(in the same room) and
> chatting to each other, any message that either party sends will be
> broadcast only once to the chatroom(as it should be), but save twice into
> the database--two copies of a message will be saved.
>
> channels==2.0.2
>
> channels-redis==2.1.0
>
> Django==1.11.8
>
> redis==2.10.6
>
> asgi-redis==1.4.3
>
> asgiref==2.1.6
>
> daphne==2.0.4
>
> I'm realizing now that I've a lot of left-over installs since upgrading
> from Channels 1.x. I'm no longer even sure which I need. Could this be the
> issue?
>
>
> On Friday, March 2, 2018 at 6:49:41 AM UTC+9, Andrew Godwin wrote:
>>
>> Can you clarify what you mean by "two users connected to the same
>> socket"? If you have two websockets connected, you'll have two copies of
>> your consumer running, one for each socket.
>>
>> Andrew
>>
>> On Thu, Mar 1, 2018 at 7:52 AM, lakeshow  wrote:
>>
>>> I am running into an issue using Channels where if two users are
>>> connected to the same socket, the consumer will run twice. When a single
>>> user is connected, only once.
>>> So in practice: when I have two users chatting with each other over
>>> channels, a single sent message will be run through the consumer twice,
>>> causing it to save twice to the database. However, if there is only one
>>> participant in the channel, the message will run through the consumer once
>>> and save once as expected.
>>>
>>> What might be the issue?
>>>
>>> Here is the consumer:
>>>
>>> class ChatConsumer(AsyncJsonWebsocketConsumer):
>>> ...
>>> async def receive_json(self, content):
>>> """
>>> Called when we get a text frame. Channels will JSON-decode the 
>>> payload
>>> for us and pass it as the first argument.
>>> """
>>> # Messages will have a "command" key we can switch on
>>> command = content.get("command", None)
>>> recipient = content.get("recipient", None)
>>> sender = self.scope["user"]
>>> try:
>>> if command == "join":
>>> # Make them join the room
>>> await self.join_room(content["room"])
>>> previous_message_list = await get_saved_messages(recipient, 
>>> sender)
>>> for msg in previous_message_list:
>>> await self.send_json({
>>> "msg_type": MSG_TYPE_MESSAGE,
>>> "room": content["room"],
>>> "username": msg.sender.user.username,
>>> "message": msg.message,
>>> },)
>>> elif command == "leave":
>>> # Leave the room
>>> await self.leave_room(content["room"])
>>> elif command == "send":
>>> await self.send_room(
>>> content["room"],
>>> content["message"],
>>> content["recipient"]
>>> )
>>> except ClientError as e:
>>> # Catch any errors and send it back
>>> await self.send_json({"error": e.code})
>>> ...
>>> async def send_room(self, room_id, message, recipient):
>>> """
>>> Called by receive_json when someone sends a message to a room.
>>> """
>>> # Check they are in this room
>>> if room_id not in self.rooms:
>>> raise ClientError("ROOM_ACCESS_DENIED")
>>> # Get the room and send to the group about it
>>> room = await get_room_or_error(room_id, self.scope["user"])
>>> await self.channel_layer.group_send(
>>> room.group_name,
>>> {
>>> "type": "chat.message",
>>> "room_id": room_id,
>>> "username": self.scope["user"].username,
>>> "message": message,
>>> "recipient": recipient,
>>> }
>>> )
>>> ...
>>> async def chat_message(self, event):
>>> """
>>> Called when someone has messaged our chat.
>>> """
>>> # Send a message down to the client
>>> # Save message object
>>> await save_message_object(
>>> sender=event["username"],
>>> message=event["message"],
>>> recipient=event["r

Re: Channels 2: Consumer running twice when two users simultaneously share socket

2018-03-01 Thread lakeshow
You're absolutely correct. 

Much appreciated, Andrew!

On Friday, March 2, 2018 at 3:08:37 PM UTC+9, Andrew Godwin wrote:
>
> The problem appears to be that you are saving to the database inside the 
> chat_message handler - since you're sending a message of type 
> "chat.message" to the group, that means everything in the group is going to 
> receive the message, run that handler, and save (so with 2 connected you 
> get 2 saves, etc.)
>
> I'd recommend saving instead where you send to the group.
>
> Andrew
>
> On Thu, Mar 1, 2018 at 10:02 PM, lakeshow 
> > wrote:
>
>> Sure. The JS code is essentially identical to your example. By "two users 
>> connected", I simply meant two users have clicked to join in a chatroom by 
>> way of `socket.send()`.   
>>
>> I've tested it by using two different browsers and having users log in to 
>> join the same room. When they are both "connected"(in the same room) and 
>> chatting to each other, any message that either party sends will be 
>> broadcast only once to the chatroom(as it should be), but save twice into 
>> the database--two copies of a message will be saved.  
>>
>> channels==2.0.2
>>
>> channels-redis==2.1.0
>>
>> Django==1.11.8
>>
>> redis==2.10.6
>>
>> asgi-redis==1.4.3
>>
>> asgiref==2.1.6
>>
>> daphne==2.0.4
>>
>> I'm realizing now that I've a lot of left-over installs since upgrading 
>> from Channels 1.x. I'm no longer even sure which I need. Could this be the 
>> issue? 
>>
>>
>> On Friday, March 2, 2018 at 6:49:41 AM UTC+9, Andrew Godwin wrote:
>>>
>>> Can you clarify what you mean by "two users connected to the same 
>>> socket"? If you have two websockets connected, you'll have two copies of 
>>> your consumer running, one for each socket.
>>>
>>> Andrew
>>>
>>> On Thu, Mar 1, 2018 at 7:52 AM, lakeshow  wrote:
>>>
 I am running into an issue using Channels where if two users are 
 connected to the same socket, the consumer will run twice. When a single 
 user is connected, only once.  
 So in practice: when I have two users chatting with each other over 
 channels, a single sent message will be run through the consumer twice, 
 causing it to save twice to the database. However, if there is only one 
 participant in the channel, the message will run through the consumer once 
 and save once as expected.  

 What might be the issue?  

 Here is the consumer:  

 class ChatConsumer(AsyncJsonWebsocketConsumer):  
 ...
 async def receive_json(self, content):
 """
 Called when we get a text frame. Channels will JSON-decode the 
 payload
 for us and pass it as the first argument.
 """
 # Messages will have a "command" key we can switch on
 command = content.get("command", None)
 recipient = content.get("recipient", None)
 sender = self.scope["user"]
 try:
 if command == "join":
 # Make them join the room
 await self.join_room(content["room"])
 previous_message_list = await 
 get_saved_messages(recipient, sender)
 for msg in previous_message_list:
 await self.send_json({
 "msg_type": MSG_TYPE_MESSAGE,
 "room": content["room"],
 "username": msg.sender.user.username,
 "message": msg.message,
 },)
 elif command == "leave":
 # Leave the room
 await self.leave_room(content["room"])
 elif command == "send":
 await self.send_room(
 content["room"],
 content["message"],
 content["recipient"]
 )
 except ClientError as e:
 # Catch any errors and send it back
 await self.send_json({"error": e.code})  
 ...
 async def send_room(self, room_id, message, recipient):
 """
 Called by receive_json when someone sends a message to a room.
 """
 # Check they are in this room
 if room_id not in self.rooms:
 raise ClientError("ROOM_ACCESS_DENIED")
 # Get the room and send to the group about it
 room = await get_room_or_error(room_id, self.scope["user"])
 await self.channel_layer.group_send(
 room.group_name,
 {
 "type": "chat.message",
 "room_id": room_id,
 "username": self.scope["user"].username,
 "message": message,
 "recipient": recipient,
 }
 )  
 ...
 async def chat_message(self, event):
 """
 

Django sending syntax errors on ES syntax of imported JS file

2018-03-01 Thread lakeshow
I'm attempting to use the script of a third party JS library:  

{% block javascript %}
  
...{% endblock javascript %}

Doing so will return an error: `Uncaught SyntaxError: Enexpected token {`  
And this error refers to line 1 of 'typed.js', more specifically, this line 
of JS code:  `import { initializer } from './initializer.js';`

What seems to be the problem? I have no trouble including the scripts of 
any other JS code. The only difference I see between this instance and my 
working JS files is that this library I'm attempting to use uses syntax 
particular to ES(?)  

Here is the specific library in question: 
https://github.com/mattboldt/typed.js/  

It's a relatively well known library so I don't think the code is a problem 
either.  




-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/044cef5d-7a71-4d62-8ff2-d55f3e13143c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django sending syntax errors on ES syntax of imported JS file

2018-03-01 Thread Jani Tiainen
Hi, looks like you're using original typed library which is written in ES
and it's not very well supported among the browsers. You should pick
transpiled version from lib-directory, that should work with all browsers
without problems.

On Fri, Mar 2, 2018 at 8:32 AM, lakeshow  wrote:

> I'm attempting to use the script of a third party JS library:
>
> {% block javascript %}
> 
> ...{% endblock javascript %}
>
> Doing so will return an error: `Uncaught SyntaxError: Enexpected token {`
> And this error refers to line 1 of 'typed.js', more specifically, this
> line of JS code:  `import { initializer } from './initializer.js';`
>
> What seems to be the problem? I have no trouble including the scripts of
> any other JS code. The only difference I see between this instance and my
> working JS files is that this library I'm attempting to use uses syntax
> particular to ES(?)
>
> Here is the specific library in question: https://github.com/mattboldt/
> typed.js/
>
> It's a relatively well known library so I don't think the code is a
> problem either.
>
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/044cef5d-7a71-4d62-8ff2-d55f3e13143c%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Jani Tiainen

- Well planned is half done, and a half done has been sufficient before...

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHn91oe86tdXywOwQ6S3ejT5aoW%2BssD0-JyFScinwirHqquaag%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.