Re: Implementing a basic search for my website

2017-02-21 Thread Carlo Ascani
Thank you for all the answers!

Given that I am implementing this for a demo purpose, I do not care about 
performances.
I think I am going to do the 2 queries approach for the demo, then I would 
use a FTS engine in the future.

Thanks a lot

Carlo


Il giorno martedì 21 febbraio 2017 02:09:46 UTC+1, Shawn Milochik ha 
scritto:
>
> If you want a pre-rolled solution, just use Django-haystack. It'll do 
> exactly what you want.
>
> If you want to create your own to avoid the dependency on additional 
> libraries and backend (you'll need something like Elasticsearch), that's 
> easy also. Let me know if you do. I have some sample code lying around and 
> will dig it up and document it a bit if you're interested in implementing 
> it. You'll still need to have to store your own indexed data in some kind 
> of backend, but you can use whatever you like.
>
>
>

-- 
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/c1e0b295-4008-4cc3-8ca9-63bebe2395f5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Django-channels disconnects right after sending a message

2017-02-21 Thread Nikoleta Misheva
When I send message the websocket disconnects. I am able to get the 
message, but I can't proceed further since disconnect is supposed to delete 
the room. I tested it with basic prints after every statement and it 
disconnects right after the receiver gets the message because everything 
that is in ws_receive is printed after it disconnects

My consumer:

@channel_session_user
def ws_receive(message):
 username = message.user.username
 text = json.loads(message['text']).get('text')
 # Use my algorithm here
 score = score_argument.get_rating(text)
 # find the room with our users
 # print(type(username))
 # print(username)
 current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
Q(username_b=username))

 # current_room = PairUsers.objects.filter(Q(username_a=username) | 
Q(username_b=username)).first()

 # check which user you got and send the message to the other
 if current_room.username_b == username:
 current_room.score_b = score
 other_channel = Channel(current_room.reply_channel_a)
 message.reply_channel.send({'text': json.dumps({
 "message": text,
 "user": username, }),
 })
 message.reply_channel.send({'text': json.dumps({
 "score": score,
 "user": username, }),
 })
 other_channel.send({'text': json.dumps({
 "message": text,
 "user": username, }),
 })
 other_channel.send({'text': json.dumps({
 "score": score,
 "user": username, }),
 })
 else:
 current_room.score_a = score
 other_channel = Channel(current_room.reply_channel_b)
 message.reply_channel.send({'text': json.dumps({
 "message": text,
 "user": username, }),
 })
 message.reply_channel.send({'text': json.dumps({
 "score": score,
 "user": username, }),
 })
 other_channel.send({'text': json.dumps({
 "message": text,
 "user": username, }),
 })
 other_channel.send({'text': json.dumps({
 "score": score,
 "user": username, }),
 })
The JS:

$(function () {
 // Correctly decide between ws:// and wss://
 var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
 var ws_path = ws_scheme + '://' + window.location.host + 
window.location.pathname;
 console.log("Connecting to " + ws_path);
 var socket = new ReconnectingWebSocket(ws_path);

 socket.onmessage = function(message){
 var data = JSON.parse(message.data);
 if(!data.score){
 var element = $([
 "",
 "" + data.message + "",
 "",
 "" + data.user + "",
 "",
 ""
 ].join("\n"));
 $("#chat_table tbody").append(element);
 }
 else {
 var element = $([
 "",
 "" + data.user + "'s score is:" + data.score + "",
 ""
 ].join("\n"));
 $("#chat_table tbody").append(element);

 }
 }

 $('#arg_form').on('submit',function () {
 socket.send(JSON.stringify({
 "text": $('#argument').val()
 }))})

 });
What might be the cause?



-- 
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/301c0b6a-822b-46b5-b7b6-72263786361f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Timeout when saving model in django admin page

2017-02-21 Thread John, Steffen
Hi!

When saving the model over the admin page of Django, a lot of processing is 
done (in pre_save function) which takes several minutes. After a while I get a 
timeout, although the process is still running in the background.

How can I avoid to get this timeout?

Another nice thing would be to show the progress of the saving process, may be 
with a progress bar. Do you have any ideas/hints/links on how to do that?

Thank you in advance!

Steffen

-- 
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/1487670629.2604.6.camel%40atenekom.eu.
For more options, visit https://groups.google.com/d/optout.


authenticate function is always returning none in views.py

2017-02-21 Thread rocky101
I'm trying to sign in with an account that already exists in the system, i 
checked the admin django page of my project to make sure it was there, but 
everytime i enter the username and password it always redirects me to the 
invalid webpage when I know the username and password is the exact same as 
stored in my django login database that is already provided. The login 
worked well with my previous html login page so I know it can work properly 
but with this new html login page it is not working. What may be the 
problem as to why my authenticate function is always returning none? Thanks


Here is my views.py file :

def login(request):
c={}
c.update(csrf(request))
return render_to_response('templates/login3.html',c)
def auth_view(request):
username=request.POST.get('username','')
password=request.POST.get('password','')
user = auth.authenticate(username=username, password=password)

if user is not None:
auth.login(request,user)
return HttpResponseRedirect('/Source.html')
else:
return HttpResponseRedirect('/accounts/invalid/')

This is my html templates with my login form:










{% csrf_token %}

  
LOGIN

  Username
  

  


  Password
  




  
Cancel
Submit
  

  












-- 
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/1336f837-cb3f-4803-bb16-eb2fccf95ed8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Timeout when saving model in django admin page

2017-02-21 Thread Jani Tiainen

Hi,

You probably want to switch to asynchronous handling of your job.

Celery is one excellent tool to handle background jobs.


On 21.02.2017 11:50, John, Steffen wrote:

Hi!

When saving the model over the admin page of Django, a lot of 
processing is done (in pre_save function) which takes several minutes. 
After a while I get a timeout, although the process is still running 
in the background.


How can I avoid to get this timeout?

Another nice thing would be to show the progress of the saving 
process, may be with a progress bar. Do you have any ideas/hints/links 
on how to do that?


Thank you in advance!

Steffen
--
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/1487670629.2604.6.camel%40atenekom.eu 
.

For more options, visit https://groups.google.com/d/optout.


--
Jani Tiainen

--
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/890d0125-2267-e296-92dd-7378201b6b11%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Subquery has too many columns

2017-02-21 Thread Melvyn Sopacua
On Monday 20 February 2017 17:09:40 eltonplima wrote:
> Base class is abstract.
> 
> class Base(models.Model):
> plano = models.ForeignKey(Plano)
> 
> 
> class Meta:
> abstract = True
> 
> 
> base_manager_name
>  er-name>

Ack, my brain kept reading "default_manager_name".
Still - without a ForeignKey this shouldn't break anything. It seems it 
warrents a new 
bug report, but I'm curious *where* things break. It looks like this model is 
used as an 
inline in the admin. Is that correct?

I cannot reproduce this with a simple test case:

models:
*class CartEntryManager(*models.Manager*):def get_queryset(*self*):
*qs *= 
/super/(*CartEntryManager, self*)*.get_queryset*()*expression *= 
*models.F*('quantity') * *models.F*('price')*wrapped *= 
*models.ExpressionWrapper*(*expression, 
  
output_field*=*models.DecimalField*(
   *max_digits*=*20, 
decimal_places*=*2*))return *qs.annotate*(*amount*=*wrapped*)



class Cart(*models.Model*):*created *= 
*models.DateTimeField*(*auto_now_add*=True)



class CartEntry(*models.Model*):*item *= 
*models.CharField*(*max_length*=*32, 
primary_key*=True)*quantity *= *models.PositiveSmallIntegerField*()
*price *= 
*models.DecimalField*(*max_digits*=*20, decimal_places*=*2*)*cart *= 
*models.ForeignKey*(*Cart, on_delete*=*models.CASCADE,  
   
related_name*='items')*is_shipped *= *models.BooleanField*(*default*=False) 
   
*objects *= *CartEntryManager*()

class Meta:*base_manager_name *= 'objects'


*
tests:
*class CartTest(*TestCase*):/@/classmethoddef setUpTestData(*cls*): 
   *cart 
*= *models.Cart*()*cart.save*()*keyboard *= *models.CartEntry*( 
   
*item*='Komplete Kontrol S88'*,quantity*=*2,
price*='999.00'*,
cart*=*cart*)*mixer *= *models.CartEntry*(
*item*='Traktor Kontrol 
S8'*,quantity*=*1,price*='1199.00'*,
cart*=*cart*)
*keyboard.save*()*mixer.save*()*cls.cart *= *cart
cls.keyboard *= 
*keyboardcls.mixer *= *mixer

*def test_entry_annotation(*self*):
*self.assertEqual*(*self.keyboard.amount, 
1998*)

def test_base_manager(*self*):from *decimal *import *Decimal
total *= 
*Decimal*('0.00')for *item *in *self.cart.items.all*():
*total *+= 
*item.amount

total *= *total.quantize*(*Decimal*('0.01'))*expect *= 
*Decimal*('3197.00')*.quantize*(*Decimal*('0.01'))
*self.assertEqual*(*total, 
expect*)

def test_base_manager_update(*self*):
*self.cart.items.update*(*is_shipped*=True)*shipped *= 
*self.cart.items.filter*(*is_shipped*=True)*.count*()
*self.assertEqual*(*shipped, 
2*)

*
> On Saturday, February 18, 2017 at 9:20:03 PM UTC-3, Melvyn Sopacua wrote:
> > On Saturday 18 February 2017 22:27:46 Elton Pereira wrote:
> > > class ProdutoServicoManager(models.Manager):
> > > 
> > > def get_queryset(self):
> > > 
> > > expression = models.Sum(models.F('custounitario__valor') *
> > > 
> > > models.F('custounitario__quantidade'))
> > > 
> > > total_expr = models.ExpressionWrapper(expression,
> > > 
> > > output_field=models.DecimalField())
> > > 
> > > return
> > > 
> > > super().get_queryset().annotate(custo_producao=total_expr)
> > 
> > > class ProdutoServico(Base):
> > What's the manager on Base?
> > 
> > > produto = models.BooleanField(default=True)
> > > 
> > > descricao = models.TextField()
> > > 
> > > objects = ProdutoServicoManager()
> > > 
> > > 
> > > 
> > > class Meta:
> > > 
> > > base_manager_name = 'objects'
> > 
> > Cause this doesn't actually do anything, beside being explicit.
> > 
> > 
> > 
> > 
> > Melvyn Sopacua

-- 
Melvyn Sopacua

-- 
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/7674223.eRDJ6MCrYX%40devstation.
For more options, visit https://groups.google.com/d/optout.


Re: authenticate function is always returning none in views.py

2017-02-21 Thread Melvyn Sopacua
Your inputs don't have a "name" attribute, so I suspect your username and 
password are always empty.

On Monday 20 February 2017 22:11:56 rocky101 wrote:

> username=request.POST.get('username','')
> password=request.POST.get('password','')
> user = auth.authenticate(username=username, password=password)

>   placeholder="Password">

-- 
Melvyn Sopacua

-- 
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/6153210.3ZSgJhhTe8%40devstation.
For more options, visit https://groups.google.com/d/optout.


Re: Timeout when saving model in django admin page

2017-02-21 Thread John, Steffen
Hi,
Thanks for the hint. I was already thinking about using celery, but if the 
process runs in background it may get some problems with other actions the user 
executes parallely.

Using celery, is it possible to prevent the user from doing other things in the 
admin tool until the celery task is done?

thanks,
Steffen

Am Dienstag, den 21.02.2017, 13:54 +0200 schrieb Jani Tiainen:

Hi,

You probably want to switch to asynchronous handling of your job.

Celery is one excellent tool to handle background jobs.

On 21.02.2017 11:50, John, Steffen wrote:
Hi!

When saving the model over the admin page of Django, a lot of processing is 
done (in pre_save function) which takes several minutes. After a while I get a 
timeout, although the process is still running in the background.

How can I avoid to get this timeout?

Another nice thing would be to show the progress of the saving process, may be 
with a progress bar. Do you have any ideas/hints/links on how to do that?

Thank you in advance!

Steffen
--
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/1487670629.2604.6.camel%40atenekom.eu.
For more options, visit https://groups.google.com/d/optout.


--
Jani Tiainen

-- 
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/1487682679.2604.11.camel%40atenekom.eu.
For more options, visit https://groups.google.com/d/optout.


Re: Timeout when saving model in django admin page

2017-02-21 Thread Melvyn Sopacua
On Tuesday 21 February 2017 13:11:19 John, Steffen wrote:

> Using celery, is it possible to prevent the user from doing other
> things in the admin tool until the celery task is done?

Sorta kinda.
But the django admin can facilitate part of it. Look into the 
ModelAdmin.has_FOO_permission() methods. These get passed the request. So you 
could implement something like:

- set has_job_running on User profile model
- for possibly dangerous actions, return false for the has_FOO_permission() 
method 
if request.user.profile.has_job_running is True.
- on job end, reset the user's has_job_running flag.

You can refine this to a tee, with different completion stages for the job 
opening up 
otherwise denied actions, etc etc.

The timeout however, is something with your webserver / wsgi implementation and 
you should look there. For example, nginx has several timeouts for handling a 
WSGI 
request that come into play. Increasing those, also means you tie up resources 
and 
are more succeptable to denial of service, so if celery is an option, take it.

-- 
Melvyn Sopacua

-- 
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/4611612.S1g8pcmQCG%40devstation.
For more options, visit https://groups.google.com/d/optout.


RE: combining ORM and raw SQL in same query

2017-02-21 Thread Matthew Pava
I would use Case and When and other Func objects.
https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions/
That way we don't have to depend on raw SQL.

-Original Message-
From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On 
Behalf Of Larry Martell
Sent: Monday, February 20, 2017 3:00 PM
To: django-users@googlegroups.com
Subject: Re: combining ORM and raw SQL in same query

Thanks!


On Mon, Feb 20, 2017 at 10:52 AM, m1chael  wrote:
> i did something like this recently using .extra / select
>
> https://docs.djangoproject.com/en/1.10/ref/models/querysets/#extra
>
>
>
> On Mon, Feb 20, 2017 at 10:49 AM, Larry Martell 
> 
> wrote:
>>
>> Is there any way to use both the ORM and raw SQL in the same query?
>>
>> I have an existing app that uses the ORM and now I have a need to add 
>> SQL like this to the select:
>>
>> (CASE
>>   WHEN TRIM(IFNULL(roiname, '')) IN ('', 'None') THEN CONCAT_WS('.', 
>> roi_type_id, roi_id)
>>   WHEN CONCAT_WS('.', roi_type_id, roi_id) = roiname THEN roiname
>>   ELSE CONCAT_WS('.', roi_type_id, roi_id, roiname)
>> END) as roiname
>>
>> and SQL like this to the where:
>>
>> AND (CASE
>>   WHEN TRIM(IFNULL(roiname, '')) IN ('', 'None') THEN CONCAT_WS('.', 
>> roi_type_id, roi_id)
>>   WHEN CONCAT_WS('.', roi_type_id, roi_id) = roiname THEN roiname
>>   ELSE CONCAT_WS('.', roi_type_id, roi_id, roiname)
>> END) REGEXP 'foo'
>>
>> As far as I know I cannot do anything like that with the ORM. I don't 
>> want to have to rewrite everything with raw SQL. Is there a way to 
>> mix them?

--
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/CACwCsY7xjBPYK17Vp2H-uV2c0aH3p-%2BG_Ya5n9dBjifE0Nk6ag%40mail.gmail.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/15817ffef8024d219cc336ec235fb529%40ISS1.ISS.LOCAL.
For more options, visit https://groups.google.com/d/optout.


Re: combining ORM and raw SQL in same query

2017-02-21 Thread Larry Martell
Thanks. I did not know about those.


On Tue, Feb 21, 2017 at 9:24 AM, Matthew Pava  wrote:
> I would use Case and When and other Func objects.
> https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions/
> That way we don't have to depend on raw SQL.
>
> -Original Message-
> From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On 
> Behalf Of Larry Martell
> Sent: Monday, February 20, 2017 3:00 PM
> To: django-users@googlegroups.com
> Subject: Re: combining ORM and raw SQL in same query
>
> Thanks!
>
>
> On Mon, Feb 20, 2017 at 10:52 AM, m1chael  wrote:
>> i did something like this recently using .extra / select
>>
>> https://docs.djangoproject.com/en/1.10/ref/models/querysets/#extra
>>
>>
>>
>> On Mon, Feb 20, 2017 at 10:49 AM, Larry Martell
>> 
>> wrote:
>>>
>>> Is there any way to use both the ORM and raw SQL in the same query?
>>>
>>> I have an existing app that uses the ORM and now I have a need to add
>>> SQL like this to the select:
>>>
>>> (CASE
>>>   WHEN TRIM(IFNULL(roiname, '')) IN ('', 'None') THEN CONCAT_WS('.',
>>> roi_type_id, roi_id)
>>>   WHEN CONCAT_WS('.', roi_type_id, roi_id) = roiname THEN roiname
>>>   ELSE CONCAT_WS('.', roi_type_id, roi_id, roiname)
>>> END) as roiname
>>>
>>> and SQL like this to the where:
>>>
>>> AND (CASE
>>>   WHEN TRIM(IFNULL(roiname, '')) IN ('', 'None') THEN CONCAT_WS('.',
>>> roi_type_id, roi_id)
>>>   WHEN CONCAT_WS('.', roi_type_id, roi_id) = roiname THEN roiname
>>>   ELSE CONCAT_WS('.', roi_type_id, roi_id, roiname)
>>> END) REGEXP 'foo'
>>>
>>> As far as I know I cannot do anything like that with the ORM. I don't
>>> want to have to rewrite everything with raw SQL. Is there a way to
>>> mix them?

-- 
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/CACwCsY4N2HTf9g4Ayed_pKWaNQ94pv0q1HpoFH3p7kD0h4au5A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


KeyError on Form using datePicker

2017-02-21 Thread Baktha Muralidharan
Hello,

I am new to Django framework and have run into the following issue.  Any 
help to resolve the issue will be much appreciated.

Background:

I am using the jQuery datePicker to gather date input. I am able to see the 
calendar show on the Appointment form and am able to select a date from the 
calendar. However, once submitted, I am not able to extract the selected 
date, in the post processing function.


I have read somewhere about form field not being extractable if user did 
not enter a value. In my scenario, I don't manually enter "perfDate", but 
rather made a selection on the calendar. I get KeyError on trying to read 
the field value. The Django debugs show that the POST data as shown here-

POST

VariableValue
csrfmiddlewaretoken 

'C4fvNKcVLaFpSCGHcukNhEIFkqLyCPqkgXCc64R8JNjQwq5EST3KCPRkMOZpAslT'

perfDate 

'02/25/2017'


 


Following are my form, template and views files:

*forms.py:*

class DateInput(forms.DateInput):
input_type = 'date'

class AppointmentForm(forms.Form):

class Meta:

model = Appointment

widgets = {

'perfDate': forms.DateInput(attrs={'class':'datepicker'}),

}


*datePicker.html:*





... JS code...



   {% csrf_token %}

Desired date:








*views.py:*


def makeReservation(request):
if request.method == 'POST':
aptForm = AppointmentForm(request.POST)
# Have we been provided with a valid form?
if aptForm.is_valid():
aptDate = aptForm.cleaned_data['perfDate'])
...
else:
# The supplied form contained errors - just print them to the 
terminal.
print(form.errors)
else:
aptForm = AppointmentForm(request.POST)
return render(request, 'datePicker.html', {'form' : aptForm})



Thanks,
/Baktha Muralidharan

-- 
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/86157664-4140-4304-a9ab-f5bae56848d5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django-channels disconnects right after sending a message

2017-02-21 Thread Andrew Godwin
How does it disconnect? What WebSocket close code do you get? (You'll need
to add JS to log it) What prints on the Python console?

Andrew

On Tue, Feb 21, 2017 at 12:27 AM, Nikoleta Misheva 
wrote:

> When I send message the websocket disconnects. I am able to get the
> message, but I can't proceed further since disconnect is supposed to delete
> the room. I tested it with basic prints after every statement and it
> disconnects right after the receiver gets the message because everything
> that is in ws_receive is printed after it disconnects
>
> My consumer:
>
> @channel_session_user
> def ws_receive(message):
>  username = message.user.username
>  text = json.loads(message['text']).get('text')
>  # Use my algorithm here
>  score = score_argument.get_rating(text)
>  # find the room with our users
>  # print(type(username))
>  # print(username)
>  current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
> Q(username_b=username))
>
>  # current_room = PairUsers.objects.filter(Q(username_a=username) | 
> Q(username_b=username)).first()
>
>  # check which user you got and send the message to the other
>  if current_room.username_b == username:
>  current_room.score_b = score
>  other_channel = Channel(current_room.reply_channel_a)
>  message.reply_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  message.reply_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
>  else:
>  current_room.score_a = score
>  other_channel = Channel(current_room.reply_channel_b)
>  message.reply_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  message.reply_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
> The JS:
>
> $(function () {
>  // Correctly decide between ws:// and wss://
>  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
>  var ws_path = ws_scheme + '://' + window.location.host + 
> window.location.pathname;
>  console.log("Connecting to " + ws_path);
>  var socket = new ReconnectingWebSocket(ws_path);
>
>  socket.onmessage = function(message){
>  var data = JSON.parse(message.data);
>  if(!data.score){
>  var element = $([
>  "",
>  "" + data.message + "",
>  "",
>  "" + data.user + "",
>  "",
>  ""
>  ].join("\n"));
>  $("#chat_table tbody").append(element);
>  }
>  else {
>  var element = $([
>  "",
>  "" + data.user + "'s score is:" + data.score + "",
>  ""
>  ].join("\n"));
>  $("#chat_table tbody").append(element);
>
>  }
>  }
>
>  $('#arg_form').on('submit',function () {
>  socket.send(JSON.stringify({
>  "text": $('#argument').val()
>  }))})
>
>  });
> What might be the cause?
>
>
>
> --
> 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/301c0b6a-822b-46b5-b7b6-72263786361f%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/CAFwN1upV9895yFThNVyzuGPT0KA3OYMhkXSZbVZwQ1GwCeP%3DsQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Initial data, tests and migrations

2017-02-21 Thread 'Tom Evans' via Django users
Hi all

I'm having some difficulty working out how I am supposed to provide
initial data for testing purposes, particularly when the initial data
is not immediately pertinent to the test.

For instance, our project uses django_otp, which has some simple
tests. However, these tests create user objects, which then calls in
to other parts of the project code. This code adds users to various
auth.Group, depending upon the user attributes. This code fails after
the first test has been run, because all the auth.Group model
instances are flushed from the database.

Previously, these instances were loaded from a JSON fixtures file,
which used to be the recommended way. For our own tests, we simply
load these fixtures in the setUp portion of the test; obviously we
can't go around modifying tests in third party libraries.
I tried taking them out of the fixtures, and adding them instead in a
data migration, but this also had the same effect - the instances were
there for the first test ran, and then missing for all the subsequent
ones.


What is the "correct" way of ensuring that these instances exist in
the test database before any test is run?

How can I stop them getting wiped out after any test has run?

Cheers

Tom

-- 
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/CAFHbX1JKCugKaijhD6_wX-M-2nN04eTqDuFG08%3D%2BtUNBW3o5hA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Flattening model relationships (in APIs)

2017-02-21 Thread Ankush Thakur
I'm using DRF for an API. My problem is that I defined my postal address
like this (breaking it up into City, State, Country):

class Country(models.Model):
class Meta:
db_table = 'countries'

name = models.TextField()
code = models.TextField(unique=True)

class State(models.Model):
class Meta:
db_table = 'states'

name = models.TextField()
code = models.TextField(unique=True)
country = models.ForeignKey('Country', on_delete=models.CASCADE)


class City(models.Model):
class Meta:
db_table = 'cities'

name = models.TextField()
code = models.TextField(unique=True)
state = models.ForeignKey('State', on_delete=models.CASCADE)

class Address(models.Model):
class Meta:
db_table = 'addresses'

building_no = models.TextField()
street = models.TextField(null=True)
locality = models.TextField(null=True)
landmark = models.TextField(null=True)
pincode = models.TextField(null=True)
latitude = models.DecimalField(max_digits=9, decimal_places=6,
null=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6,
null=True)
city = models.ForeignKey('City', on_delete=models.CASCADE)

Now, in my system, a venue has an address, and so the serializes are
defined like this:

class VenueSerializer(serializers.ModelSerializer):
address = AddressSerializer()
offerings = OfferingSerializer(many=True)

class Meta:
model = Venue
fields = ['id', 'name', 'price_per_day', 'status', 'offerings',
'address', 'photos']

which leads us to:

class AddressSerializer(serializers.ModelSerializer):
city = CitySerializer()

class Meta:
model = Address
fields = ['id', 'building_no', 'street', 'locality', 'landmark',
'pincode', 'latitude', 'longitude', 'city']

which leads us to:

class CitySerializer(serializers.ModelSerializer):
state = StateSerializer()

class Meta:
model = City
fields = ['id', 'name', 'code', 'state']

which leads us to:

class StateSerializer(serializers.ModelSerializer):
country = CountrySerializer()

class Meta:
model = State
fields = ['id', 'name', 'code', 'country']

which finally leads to:

class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ['id', 'name', 'code']

and when this gets serialized, the address is given in the following format:

 "address": {
  "id": 2,
  "building_no": "11",
  "street": "Another Street",
  "locality": "",
  "landmark": "Fortis Hospital",
  "pincode": "201003",
  "latitude": "28.632778",
  "longitude": "77.219722",
  "city": {
"id": 1,
"name": "Delhi",
"code": "DEL",
"state": {
  "id": 1,
  "name": "Delhi",
  "code": "DEL",
  "country": {
"id": 1,
"name": "India",
"code": "IN"
  }
}
  }
}

So there's a hell lot of nesting from city to state to country. If the
relationship chain was even deeper, there would be even more nesting, which
I feel isn't great for API consumers. What is the best practice here to put
state and country at the same level as the city? I think this will also
complicate the logic while POSTing data, so I'm interested in knowing about
that as well.

I'm sorry if there is too much code, but I couldn't think of a better way
to convey the situation than actually post everything.


Regards,
Ankush Thakur

-- 
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/CALX%3DrK%2Bgbbro%2BkFYsq%3DFDCSu2kw6KRmsfKRamKLA%2Bisrgj%3DboQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django-channels disconnects right after sending a message

2017-02-21 Thread Nikoleta Misheva
I don't know how to get the close code. It disconnects right after you hit 
the send button but it manages to send the message, I had prints and the 
message was right and etc but was always after disconnect. My disconnect 
function basically deletes the room. And python's console logs:
[2017/02/21 21:42:50] WebSocket DISCONNECT /play [127.0.0.1:65273]
[2017/02/21 21:42:50] WebSocket HANDSHAKING /play [127.0.0.1:65282]
It reconnects.


вторник, 21 февруари 2017 г., 20:45:13 UTC+2, Andrew Godwin написа:
>
> How does it disconnect? What WebSocket close code do you get? (You'll need 
> to add JS to log it) What prints on the Python console?
>
> Andrew
>
> On Tue, Feb 21, 2017 at 12:27 AM, Nikoleta Misheva  > wrote:
>
>> When I send message the websocket disconnects. I am able to get the 
>> message, but I can't proceed further since disconnect is supposed to delete 
>> the room. I tested it with basic prints after every statement and it 
>> disconnects right after the receiver gets the message because everything 
>> that is in ws_receive is printed after it disconnects
>>
>> My consumer:
>>
>> @channel_session_user
>> def ws_receive(message):
>>  username = message.user.username
>>  text = json.loads(message['text']).get('text')
>>  # Use my algorithm here
>>  score = score_argument.get_rating(text)
>>  # find the room with our users
>>  # print(type(username))
>>  # print(username)
>>  current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
>> Q(username_b=username))
>>
>>  # current_room = PairUsers.objects.filter(Q(username_a=username) | 
>> Q(username_b=username)).first()
>>
>>  # check which user you got and send the message to the other
>>  if current_room.username_b == username:
>>  current_room.score_b = score
>>  other_channel = Channel(current_room.reply_channel_a)
>>  message.reply_channel.send({'text': json.dumps({
>>  "message": text,
>>  "user": username, }),
>>  })
>>  message.reply_channel.send({'text': json.dumps({
>>  "score": score,
>>  "user": username, }),
>>  })
>>  other_channel.send({'text': json.dumps({
>>  "message": text,
>>  "user": username, }),
>>  })
>>  other_channel.send({'text': json.dumps({
>>  "score": score,
>>  "user": username, }),
>>  })
>>  else:
>>  current_room.score_a = score
>>  other_channel = Channel(current_room.reply_channel_b)
>>  message.reply_channel.send({'text': json.dumps({
>>  "message": text,
>>  "user": username, }),
>>  })
>>  message.reply_channel.send({'text': json.dumps({
>>  "score": score,
>>  "user": username, }),
>>  })
>>  other_channel.send({'text': json.dumps({
>>  "message": text,
>>  "user": username, }),
>>  })
>>  other_channel.send({'text': json.dumps({
>>  "score": score,
>>  "user": username, }),
>>  })
>> The JS:
>>
>> $(function () {
>>  // Correctly decide between ws:// and wss://
>>  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
>>  var ws_path = ws_scheme + '://' + window.location.host + 
>> window.location.pathname;
>>  console.log("Connecting to " + ws_path);
>>  var socket = new ReconnectingWebSocket(ws_path);
>>
>>  socket.onmessage = function(message){
>>  var data = JSON.parse(message.data);
>>  if(!data.score){
>>  var element = $([
>>  "",
>>  "" + data.message + "",
>>  "",
>>  "" + data.user + "",
>>  "",
>>  ""
>>  ].join("\n"));
>>  $("#chat_table tbody").append(element);
>>  }
>>  else {
>>  var element = $([
>>  "",
>>  "" + data.user + "'s score is:" + data.score + "",
>>  ""
>>  ].join("\n"));
>>  $("#chat_table tbody").append(element);
>>
>>  }
>>  }
>>
>>  $('#arg_form').on('submit',function () {
>>  socket.send(JSON.stringify({
>>  "text": $('#argument').val()
>>  }))})
>>
>>  });
>> What might be the cause?
>>
>>
>>
>> -- 
>> 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/301c0b6a-822b-46b5-b7b6-72263786361f%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/9b7feff4-4f60-48bc-a6bf-b2ab6891658a%40googlegroups.com.
For more options, visi

Re: Subquery has too many columns

2017-02-21 Thread eltonplima
This is part of my real code but demonstrate the issue in pratice:

from django.db import models

class ProdutoServicoManager(models.Manager):
def get_queryset(self):
custo_unitario = models.F('custounitario__valor')
quantidade = models.F('custounitario__quantidade')
expression = models.Sum(custo_unitario * quantidade)
custo_producao_expr = models.ExpressionWrapper(expression,
  
 output_field=models.DecimalField())
return 
super().get_queryset().annotate(custo_producao=custo_producao_expr)


class ProdutoServico(models.Model):
produto = models.BooleanField(default=True)
descricao = models.TextField()
objects = ProdutoServicoManager()

class Meta:
#
# Comment the line below and the test pass.
#
base_manager_name = 'objects'


class CustoUnitario(models.Model):
produto_servico = models.ForeignKey(ProdutoServico)
item = models.CharField(max_length=128)
quantidade = models.PositiveIntegerField()
valor = models.DecimalField(max_digits=10,
decimal_places=4,
verbose_name='Valor unitário')


class Faturamento(models.Model):
produto_servico = models.OneToOneField(ProdutoServico)
quantidade = models.PositiveIntegerField()
preco_unitario = models.DecimalField(max_digits=10, decimal_places=2)

# We need only a single simple test to demonstrate this issue.

from django.test import TestCase
from django.db import utils

from model_mommy import mommy

from core import models

class FaturamentoTest(TestCase):

def test(self):
faturamento = mommy.make(models.Faturamento)
produto = faturamento.produto_servico
try:
produto.save()
except utils.OperationalError:
self.fail("Whats wrong?")




On Tuesday, February 21, 2017 at 9:01:50 AM UTC-3, Melvyn Sopacua wrote:
>
> On Monday 20 February 2017 17:09:40 eltonplima wrote:
>
> > Base class is abstract.
>
> > 
>
> > class Base(models.Model):
>
> > plano = models.ForeignKey(Plano)
>
> > 
>
> > 
>
> > class Meta:
>
> > abstract = True
>
> > 
>
> > 
>
> > base_manager_name
>
> > 
> > er-name>
>
>  
>
> Ack, my brain kept reading "default_manager_name".
>
> Still - without a ForeignKey this shouldn't break anything. It seems it 
> warrents a new bug report, but I'm curious where things break. It looks 
> like this model is used as an inline in the admin. Is that correct?
>
>  
>
> I cannot reproduce this with a simple test case:
>
>  
>
> models:
>
> class CartEntryManager(models.Manager):
> def get_queryset(self):
> qs = super(CartEntryManager, self).get_queryset()
> expression = models.F('quantity') * models.F('price')
> wrapped = models.ExpressionWrapper(expression,
> output_field=models.DecimalField(
> max_digits=20, decimal_places=2))
> return qs.annotate(amount=wrapped)
>
>
> class Cart(models.Model):
> created = models.DateTimeField(auto_now_add=True)
>
>
> class CartEntry(models.Model):
> item = models.CharField(max_length=32, primary_key=True)
> quantity = models.PositiveSmallIntegerField()
> price = models.DecimalField(max_digits=20, decimal_places=2)
> cart = models.ForeignKey(Cart, on_delete=models.CASCADE,
> related_name='items')
> is_shipped = models.BooleanField(default=False)
> objects = CartEntryManager()
>
> class Meta:
> base_manager_name = 'objects'
>
> tests:
>
> class CartTest(TestCase):
> @classmethod
> def setUpTestData(cls):
> cart = models.Cart()
> cart.save()
> keyboard = models.CartEntry(
> item='Komplete Kontrol S88',
> quantity=2,
> price='999.00',
> cart=cart
> )
> mixer = models.CartEntry(
> item='Traktor Kontrol S8',
> quantity=1,
> price='1199.00',
> cart=cart
> )
> keyboard.save()
> mixer.save()
> cls.cart = cart
> cls.keyboard = keyboard
> cls.mixer = mixer
>
> def test_entry_annotation(self):
> self.assertEqual(self.keyboard.amount, 1998)
>
> def test_base_manager(self):
> from decimal import Decimal
> total = Decimal('0.00')
> for item in self.cart.items.all():
> total += item.amount
>
> total = total.quantize(Decimal('0.01'))
> expect = Decimal('3197.00').quantize(Decimal('0.01'))
> self.assertEqual(total, expect)
>
> def test_base_manager_update(self):
> self.cart.items.update(is_shipped=True)
> shipped = self.cart.items.filter(is_shipped=True).count()
> self.assertEqual(shipped, 2)
>
> > On Saturday, February 18, 2017 at 9:20:03 PM UTC-3, Melvyn Sopacua wrote:
>
> > > On Saturday 18 February 2017 22:27:46 Elton Pereira wrote:
>
> > > > class ProdutoServicoManager(models.Manager):
>
> > > > 
>
> > > > def get_queryset(self):
>
> > > > 
>
> > > > expression = models.Sum(models.F('custounitario__valor') *
>
> > > > 
>
> > > > models.F('custounitario__quantidade'))
>
> > > > 
>
> > > > total_e

Re: Initial data, tests and migrations

2017-02-21 Thread Melvyn Sopacua
On Tuesday 21 February 2017 19:00:42 'Tom Evans' via Django users wrote:

> Previously, these instances were loaded from a JSON fixtures file,

And you can still do that.

> which used to be the recommended way. For our own tests, we simply
> load these fixtures in the setUp portion of the test; obviously we
> can't go around modifying tests in third party libraries.
> I tried taking them out of the fixtures, and adding them instead in a
> data migration, but this also had the same effect - the instances were
> there for the first test ran, and then missing for all the subsequent
> ones.

setUp is run between test methods of a test case. setupTestData is a class 
method on 
the testcase run once per test case.
> 
> 
> What is the "correct" way of ensuring that these instances exist in
> the test database before any test is run?

All explained in the docs[1].
Either redeclare the same fixtures for different test cases or reorganize your 
testcases to share the same fixture(s).
-- 
Melvyn Sopacua


[1] 
https://docs.djangoproject.com/en/1.10/topics/testing/tools/#django.test.TransactionTe
stCase.fixtures

-- 
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/3888092.mWS3N5nSI1%40devstation.
For more options, visit https://groups.google.com/d/optout.


Re: Django-channels disconnects right after sending a message

2017-02-21 Thread Andrew Godwin
I'm afraid I don't really know what's going on then - the logs don't reveal
very much. I'd try reducing it down to simpler code until you can replicate
it in only a few lines and work from there.

Andrew

On Tue, Feb 21, 2017 at 11:46 AM, Nikoleta Misheva 
wrote:

> I don't know how to get the close code. It disconnects right after you hit
> the send button but it manages to send the message, I had prints and the
> message was right and etc but was always after disconnect. My disconnect
> function basically deletes the room. And python's console logs:
> [2017/02/21 21:42:50] WebSocket DISCONNECT /play [127.0.0.1:65273]
> [2017/02/21 21:42:50] WebSocket HANDSHAKING /play [127.0.0.1:65282]
> It reconnects.
>
>
> вторник, 21 февруари 2017 г., 20:45:13 UTC+2, Andrew Godwin написа:
>>
>> How does it disconnect? What WebSocket close code do you get? (You'll
>> need to add JS to log it) What prints on the Python console?
>>
>> Andrew
>>
>> On Tue, Feb 21, 2017 at 12:27 AM, Nikoleta Misheva 
>> wrote:
>>
>>> When I send message the websocket disconnects. I am able to get the
>>> message, but I can't proceed further since disconnect is supposed to delete
>>> the room. I tested it with basic prints after every statement and it
>>> disconnects right after the receiver gets the message because everything
>>> that is in ws_receive is printed after it disconnects
>>>
>>> My consumer:
>>>
>>> @channel_session_user
>>> def ws_receive(message):
>>>  username = message.user.username
>>>  text = json.loads(message['text']).get('text')
>>>  # Use my algorithm here
>>>  score = score_argument.get_rating(text)
>>>  # find the room with our users
>>>  # print(type(username))
>>>  # print(username)
>>>  current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
>>> Q(username_b=username))
>>>
>>>  # current_room = PairUsers.objects.filter(Q(username_a=username) | 
>>> Q(username_b=username)).first()
>>>
>>>  # check which user you got and send the message to the other
>>>  if current_room.username_b == username:
>>>  current_room.score_b = score
>>>  other_channel = Channel(current_room.reply_channel_a)
>>>  message.reply_channel.send({'text': json.dumps({
>>>  "message": text,
>>>  "user": username, }),
>>>  })
>>>  message.reply_channel.send({'text': json.dumps({
>>>  "score": score,
>>>  "user": username, }),
>>>  })
>>>  other_channel.send({'text': json.dumps({
>>>  "message": text,
>>>  "user": username, }),
>>>  })
>>>  other_channel.send({'text': json.dumps({
>>>  "score": score,
>>>  "user": username, }),
>>>  })
>>>  else:
>>>  current_room.score_a = score
>>>  other_channel = Channel(current_room.reply_channel_b)
>>>  message.reply_channel.send({'text': json.dumps({
>>>  "message": text,
>>>  "user": username, }),
>>>  })
>>>  message.reply_channel.send({'text': json.dumps({
>>>  "score": score,
>>>  "user": username, }),
>>>  })
>>>  other_channel.send({'text': json.dumps({
>>>  "message": text,
>>>  "user": username, }),
>>>  })
>>>  other_channel.send({'text': json.dumps({
>>>  "score": score,
>>>  "user": username, }),
>>>  })
>>> The JS:
>>>
>>> $(function () {
>>>  // Correctly decide between ws:// and wss://
>>>  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
>>>  var ws_path = ws_scheme + '://' + window.location.host + 
>>> window.location.pathname;
>>>  console.log("Connecting to " + ws_path);
>>>  var socket = new ReconnectingWebSocket(ws_path);
>>>
>>>  socket.onmessage = function(message){
>>>  var data = JSON.parse(message.data);
>>>  if(!data.score){
>>>  var element = $([
>>>  "",
>>>  "" + data.message + "",
>>>  "",
>>>  "" + data.user + "",
>>>  "",
>>>  ""
>>>  ].join("\n"));
>>>  $("#chat_table tbody").append(element);
>>>  }
>>>  else {
>>>  var element = $([
>>>  "",
>>>  "" + data.user + "'s score is:" + data.score + "",
>>>  ""
>>>  ].join("\n"));
>>>  $("#chat_table tbody").append(element);
>>>
>>>  }
>>>  }
>>>
>>>  $('#arg_form').on('submit',function () {
>>>  socket.send(JSON.stringify({
>>>  "text": $('#argument').val()
>>>  }))})
>>>
>>>  });
>>> What might be the cause?
>>>
>>>
>>>
>>> --
>>> 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/ms
>>> gid/django-users/301c0b6a-822b-46b5-b7b6-72263786361f%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 

Re: Subquery has too many columns

2017-02-21 Thread Melvyn Sopacua
While the testcase is simple, it is not the simplest test :)

Two things come to mind:
 1. If you get rid of the Sum(), does it work then?
 2. Saving the model with the base_manager_name should not use that manager 
as related manager. It is only used when a model with a foreign key to 
ProdutoServico 
is saved.
In your original exception, it looks like ProdutoServico extends a model in 
sumario.models and both override the save method:

/home/eltonplima/ssd/repository/planonegocios/marketing/models.py in save
   super().save(*args, **kwargs) ...
▶ Local vars
/home/eltonplima/ssd/repository/planonegocios/sumario/models.py in save
   super().save(*args, **kwargs) ...

Is it possible your problem is in one of those two?

On Tuesday 21 February 2017 16:37:12 eltonplima wrote:
> This is part of my real code but demonstrate the issue in pratice:
> 
> from django.db import models
> 
> class ProdutoServicoManager(models.Manager):
> def get_queryset(self):
> custo_unitario = models.F('custounitario__valor')
> quantidade = models.F('custounitario__quantidade')
> expression = models.Sum(custo_unitario * quantidade)
> custo_producao_expr = models.ExpressionWrapper(expression,
> 
>  output_field=models.DecimalField())
> return
> super().get_queryset().annotate(custo_producao=custo_producao_expr)
> 
> 
> class ProdutoServico(models.Model):
> produto = models.BooleanField(default=True)
> descricao = models.TextField()
> objects = ProdutoServicoManager()
> 
> class Meta:
> 
#
> # Comment the line below and the test pass.
> 
#
> base_manager_name = 'objects'
> 
> 
> class CustoUnitario(models.Model):
> produto_servico = models.ForeignKey(ProdutoServico)
> item = models.CharField(max_length=128)
> quantidade = models.PositiveIntegerField()
> valor = models.DecimalField(max_digits=10,
> decimal_places=4,
> verbose_name='Valor unitário')
> 
> 
> class Faturamento(models.Model):
> produto_servico = models.OneToOneField(ProdutoServico)
> quantidade = models.PositiveIntegerField()
> preco_unitario = models.DecimalField(max_digits=10,
> decimal_places=2)
> 
> # We need only a single simple test to demonstrate this issue.
> 
> from django.test import TestCase
> from django.db import utils
> 
> from model_mommy import mommy
> 
> from core import models
> 
> class FaturamentoTest(TestCase):
> 
> def test(self):
> faturamento = mommy.make(models.Faturamento)
> produto = faturamento.produto_servico
> try:
> produto.save()
> except utils.OperationalError:
> self.fail("Whats wrong?")
> 
> On Tuesday, February 21, 2017 at 9:01:50 AM UTC-3, Melvyn Sopacua wrote:
> > On Monday 20 February 2017 17:09:40 eltonplima wrote:
> > > Base class is abstract.
> > > 
> > > 
> > > 
> > > class Base(models.Model):
> > > 
> > > plano = models.ForeignKey(Plano)
> > > 
> > > 
> > > 
> > > 
> > > 
> > > class Meta:
> > > 
> > > abstract = True
> > > 
> > > 
> > > 
> > > 
> > > 
> > > base_manager_name
> > > 
> > >  > > anag
> > > 
> > > er-name>
> > 
> > Ack, my brain kept reading "default_manager_name".
> > 
> > Still - without a ForeignKey this shouldn't break anything. It seems
> > it warrents a new bug report, but I'm curious where things break.
> > It looks like this model is used as an inline in the admin. Is that
> > correct?
> > 
> > 
> > 
> > I cannot reproduce this with a simple test case:
> > 
> > 
> > 
> > models:
> > 
> > class CartEntryManager(models.Manager):
> > def get_queryset(self):
> > qs = super(CartEntryManager, self).get_queryset()
> > expression = models.F('quantity') * models.F('price')
> > wrapped = models.ExpressionWrapper(expression,
> > output_field=models.DecimalField(
> > max_digits=20, decimal_places=2))

-- 
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/186009608.yBrPArMdij%40devstation.
For more options, visit https://groups.google.com/d/optout.


Re: Looking for Django tutorial that illustrates master/detail data models

2017-02-21 Thread Axil-Mar Imam
Hi. I wondering if you have found a way about your problem? Im actually 
researching on this problem as well, unfortunately, haven't found a 
solution to this. If you have, I would really appreciate if you share it. 
Thanks.

On Wednesday, December 31, 2008 at 10:44:57 AM UTC+8, ldm999 wrote:
>
> Thanks for your response. 
>
> I should have been more clear. I'm looking for examples of views/forms 
> to manage the children of a parent child model. Eg how to add/change/ 
> delete a book on a book list. 
>
> I don't recall the Django tutorial covering this and I just looked 
> again. It appears to focus more on the Django Admin than on custom 
> forms. And what it does cover wrt forms seems mostly focused on a form 
> for a stand-alone model rather than the child of a prent model where 
> you need the context of the parent to make sure you add a new item to 
> the right parent, and edit/delete the correct item based on its 
> parent. 
>
> I'll take another detailed look at the official tutorial to see if 
> this is covered. 
>
> On Dec 30, 6:02 pm, Daniel Roseman  
> wrote: 
> > On Dec 30, 8:22 pm, ldm999  wrote: 
> > 
> > > Eg: 
> > > Lists (books, movies, restaurants) and multiple items per list. 
> > 
> > > Web forms would allow user to: 
> > > - Add/change/delete lists 
> > > - Add/change/delete list items 
> > 
> > > TIA 
> > 
> > Have you actually read the tutorial on the Django site? The Poll 
> > application covers exactly this. 
> > -- 
> > DR.

-- 
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/9e3e6e5a-729c-46ab-aa12-b73207a0d88b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Subquery has too many columns

2017-02-21 Thread eltonplima
I tried many things, only work if I remove the annotate or 
remove base_manager_name. But I need both!

The save method is not the problem, I removed.

If the last code I posted work, then, my production code works.

PS: Sorry if my English is not very good, I'm trying to improve it.

On Tuesday, February 21, 2017 at 10:16:04 PM UTC-3, Melvyn Sopacua wrote:
>
> While the testcase is simple, it is not the simplest test :)
>
>  
>
> Two things come to mind:
>
>1. If you get rid of the Sum(), does it work then? 
>2. Saving the model with the base_manager_name should not use that 
>manager as related manager. It is only used when a model with a foreign 
> key 
>to ProdutoServico is saved.
>
> In your original exception, it looks like ProdutoServico extends a model 
> in sumario.models and both override the save method:
>
>  
>
> /home/eltonplima/ssd/repository/planonegocios/marketing/models.py in save
>
>super().save(*args, **kwargs) ...
>
> ▶ Local vars
>
> /home/eltonplima/ssd/repository/planonegocios/sumario/models.py in save
>
>super().save(*args, **kwargs) ...
>
>  
>
> Is it possible your problem is in one of those two?
>
>  
>
> On Tuesday 21 February 2017 16:37:12 eltonplima wrote:
>
> > This is part of my real code but demonstrate the issue in pratice:
>
> > 
>
> > from django.db import models
>
> > 
>
> > class ProdutoServicoManager(models.Manager):
>
> > def get_queryset(self):
>
> > custo_unitario = models.F('custounitario__valor')
>
> > quantidade = models.F('custounitario__quantidade')
>
> > expression = models.Sum(custo_unitario * quantidade)
>
> > custo_producao_expr = models.ExpressionWrapper(expression,
>
> > 
>
> > output_field=models.DecimalField())
>
> > return
>
> > super().get_queryset().annotate(custo_producao=custo_producao_expr)
>
> > 
>
> > 
>
> > class ProdutoServico(models.Model):
>
> > produto = models.BooleanField(default=True)
>
> > descricao = models.TextField()
>
> > objects = ProdutoServicoManager()
>
> > 
>
> > class Meta:
>
> > #
>
> > # Comment the line below and the test pass.
>
> > #
>
> > base_manager_name = 'objects'
>
> > 
>
> > 
>
> > class CustoUnitario(models.Model):
>
> > produto_servico = models.ForeignKey(ProdutoServico)
>
> > item = models.CharField(max_length=128)
>
> > quantidade = models.PositiveIntegerField()
>
> > valor = models.DecimalField(max_digits=10,
>
> > decimal_places=4,
>
> > verbose_name='Valor unitário')
>
> > 
>
> > 
>
> > class Faturamento(models.Model):
>
> > produto_servico = models.OneToOneField(ProdutoServico)
>
> > quantidade = models.PositiveIntegerField()
>
> > preco_unitario = models.DecimalField(max_digits=10,
>
> > decimal_places=2)
>
> > 
>
> > # We need only a single simple test to demonstrate this issue.
>
> > 
>
> > from django.test import TestCase
>
> > from django.db import utils
>
> > 
>
> > from model_mommy import mommy
>
> > 
>
> > from core import models
>
> > 
>
> > class FaturamentoTest(TestCase):
>
> > 
>
> > def test(self):
>
> > faturamento = mommy.make(models.Faturamento)
>
> > produto = faturamento.produto_servico
>
> > try:
>
> > produto.save()
>
> > except utils.OperationalError:
>
> > self.fail("Whats wrong?")
>
> > 
>
> > On Tuesday, February 21, 2017 at 9:01:50 AM UTC-3, Melvyn Sopacua wrote:
>
> > > On Monday 20 February 2017 17:09:40 eltonplima wrote:
>
> > > > Base class is abstract.
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > class Base(models.Model):
>
> > > > 
>
> > > > plano = models.ForeignKey(Plano)
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > class Meta:
>
> > > > 
>
> > > > abstract = True
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > 
>
> > > > base_manager_name
>
> > > > 
>
> > > > 
> > > > anag
>
> > > > 
>
> > > > er-name>
>
> > > 
>
> > > Ack, my brain kept reading "default_manager_name".
>
> > > 
>
> > > Still - without a ForeignKey this shouldn't break anything. It seems
>
> > > it warrents a new bug report, but I'm curious where things break.
>
> > > It looks like this model is used as an inline in the admin. Is that
>
> > > correct?
>
> > > 
>
> > > 
>
> > > 
>
> > > I cannot reproduce this with a simple test case:
>
> > > 
>
> > > 
>
> > > 
>
> > > models:
>
> > > 
>
> > > class CartEntryManager(models.Manager):
>
> > > def get_queryset(self):
>
> > > qs = super(CartEntryManager, self).get_queryset()
>
> > > expression = models.F('quantity') * models.F('price')
>
> > > wrapped = models.ExpressionWrapper(expression,
>
> > > output_field=models.DecimalField(
>
> > > max_digits=20, decimal_places=2))
>
> > > return qs.annotate(amount=wrapped)
>
> > > 
>
> > > 
>
> > > class Cart(models.Model):
>
> > > created = models.DateTimeField(auto_now_add=True)
>
> > > 
>
> > > 
>
> > > class CartEntry(models.Model):
>
> > > item = models.CharField(max_length=32, primary_key=True)
>
> 

Re: Flattening model relationships (in APIs)

2017-02-21 Thread Mike Dewhirst

Ankush

I think you might have to provide more than one method for retrieving an 
address so applications can request particular subsets. Perhaps a 
local-postal address, international-postal address, geo-location, 
what-three-words address and of course the full bucket as required.


I think it is always best to normalize as much as possible in the 
beginning and de-normalize only if performance becomes an issue.


Also ...

https://hackernoon.com/10-things-i-learned-making-the-fastest-site-in-the-world-18a0e1cdf4a7#.3l8n34dvk

Mike

On 22/02/2017 6:09 AM, Ankush Thakur wrote:
I'm using DRF for an API. My problem is that I defined my postal 
address like this (breaking it up into City, State, Country):


class Country(models.Model):
class Meta:
db_table = 'countries'

name = models.TextField()
code = models.TextField(unique=True)

class State(models.Model):
class Meta:
db_table = 'states'

name = models.TextField()
code = models.TextField(unique=True)
country = models.ForeignKey('Country', on_delete=models.CASCADE)


class City(models.Model):
class Meta:
db_table = 'cities'

name = models.TextField()
code = models.TextField(unique=True)
state = models.ForeignKey('State', on_delete=models.CASCADE)

class Address(models.Model):
class Meta:
db_table = 'addresses'
building_no = models.TextField()
street = models.TextField(null=True)
locality = models.TextField(null=True)
landmark = models.TextField(null=True)
pincode = models.TextField(null=True)
latitude = models.DecimalField(max_digits=9, decimal_places=6, 
null=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6, 
null=True)

city = models.ForeignKey('City', on_delete=models.CASCADE)

Now, in my system, a venue has an address, and so the serializes are 
defined like this:


class VenueSerializer(serializers.ModelSerializer):
address = AddressSerializer()
offerings = OfferingSerializer(many=True)

class Meta:
model = Venue
fields = ['id', 'name', 'price_per_day', 'status', 
'offerings', 'address', 'photos']


which leads us to:

class AddressSerializer(serializers.ModelSerializer):
city = CitySerializer()

class Meta:
model = Address
fields = ['id', 'building_no', 'street', 'locality', 
'landmark', 'pincode', 'latitude', 'longitude', 'city']


which leads us to:

class CitySerializer(serializers.ModelSerializer):
state = StateSerializer()

class Meta:
model = City
fields = ['id', 'name', 'code', 'state']

which leads us to:

class StateSerializer(serializers.ModelSerializer):
country = CountrySerializer()

class Meta:
model = State
fields = ['id', 'name', 'code', 'country']

which finally leads to:

class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ['id', 'name', 'code']

and when this gets serialized, the address is given in the following 
format:


 "address": {
  "id": 2,
  "building_no": "11",
  "street": "Another Street",
  "locality": "",
  "landmark": "Fortis Hospital",
  "pincode": "201003",
  "latitude": "28.632778",
  "longitude": "77.219722",
  "city": {
"id": 1,
"name": "Delhi",
"code": "DEL",
"state": {
  "id": 1,
  "name": "Delhi",
  "code": "DEL",
  "country": {
"id": 1,
"name": "India",
"code": "IN"
  }
}
  }
}

So there's a hell lot of nesting from city to state to country. If the 
relationship chain was even deeper, there would be even more nesting, 
which I feel isn't great for API consumers. What is the best practice 
here to put state and country at the same level as the city? I think 
this will also complicate the logic while POSTing data, so I'm 
interested in knowing about that as well.


I'm sorry if there is too much code, but I couldn't think of a better 
way to convey the situation than actually post everything.



Regards,
Ankush Thakur
--
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/CALX%3DrK%2Bgbbro%2BkFYsq%3DFDCSu2kw6KRmsfKRamKLA%2Bisrgj%3DboQ%40mail.gmail.com 
.

For more options, visit https://groups.google.com/d/optout.


--
You recei

Re: Django-channels disconnects right after sending a message

2017-02-21 Thread Nikoleta Misheva
How do I log an WebsocketCloseExeption it might deliver more useful 
information?

сряда, 22 февруари 2017 г., 3:08:09 UTC+2, Andrew Godwin написа:
>
> I'm afraid I don't really know what's going on then - the logs don't 
> reveal very much. I'd try reducing it down to simpler code until you can 
> replicate it in only a few lines and work from there.
>
> Andrew
>
> On Tue, Feb 21, 2017 at 11:46 AM, Nikoleta Misheva  > wrote:
>
>> I don't know how to get the close code. It disconnects right after you 
>> hit the send button but it manages to send the message, I had prints and 
>> the message was right and etc but was always after disconnect. My 
>> disconnect function basically deletes the room. And python's console logs:
>> [2017/02/21 21:42:50] WebSocket DISCONNECT /play [127.0.0.1:65273]
>> [2017/02/21 21:42:50] WebSocket HANDSHAKING /play [127.0.0.1:65282]
>> It reconnects.
>>
>>
>> вторник, 21 февруари 2017 г., 20:45:13 UTC+2, Andrew Godwin написа:
>>>
>>> How does it disconnect? What WebSocket close code do you get? (You'll 
>>> need to add JS to log it) What prints on the Python console?
>>>
>>> Andrew
>>>
>>> On Tue, Feb 21, 2017 at 12:27 AM, Nikoleta Misheva  
>>> wrote:
>>>
 When I send message the websocket disconnects. I am able to get the 
 message, but I can't proceed further since disconnect is supposed to 
 delete 
 the room. I tested it with basic prints after every statement and it 
 disconnects right after the receiver gets the message because everything 
 that is in ws_receive is printed after it disconnects

 My consumer:

 @channel_session_user
 def ws_receive(message):
  username = message.user.username
  text = json.loads(message['text']).get('text')
  # Use my algorithm here
  score = score_argument.get_rating(text)
  # find the room with our users
  # print(type(username))
  # print(username)
  current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
 Q(username_b=username))

  # current_room = PairUsers.objects.filter(Q(username_a=username) | 
 Q(username_b=username)).first()

  # check which user you got and send the message to the other
  if current_room.username_b == username:
  current_room.score_b = score
  other_channel = Channel(current_room.reply_channel_a)
  message.reply_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  message.reply_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
  else:
  current_room.score_a = score
  other_channel = Channel(current_room.reply_channel_b)
  message.reply_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  message.reply_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
 The JS:

 $(function () {
  // Correctly decide between ws:// and wss://
  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
  var ws_path = ws_scheme + '://' + window.location.host + 
 window.location.pathname;
  console.log("Connecting to " + ws_path);
  var socket = new ReconnectingWebSocket(ws_path);

  socket.onmessage = function(message){
  var data = JSON.parse(message.data);
  if(!data.score){
  var element = $([
  "",
  "" + data.message + "",
  "",
  "" + data.user + "",
  "",
  ""
  ].join("\n"));
  $("#chat_table tbody").append(element);
  }
  else {
  var element = $([
  "",
  "" + data.user + "'s score is:" + data.score + "",
  ""
  ].join("\n"));
  $("#chat_table tbody").append(element);

  }
  }

  $('#arg_form').on('submit',function () {
  socket.send(JSON.stringify({
  "text": $('#argument').val()
  }))})

  });
 What might be the cause?



 -- 
 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/301c0b6a-822b-46b5-b7b6-72263786361f%40googlegroups.com
  
 

Re: Django-channels disconnects right after sending a message

2017-02-21 Thread Nikoleta Misheva
I tried  the simplest example and it works fine and does not disconnect. 

def websocket_receive(message):
 text = message.content.get('text')
 if text:
 message.reply_channel.send({"text": "You said: {}".format(text)})

And using the JS console 
socket = new WebSocket("ws://" + window.location.host + "/chat/");
socket.onmessage = function(e) {
alert(e.data);
}
socket.onopen = function() {
socket.send("hello world");
}

сряда, 22 февруари 2017 г., 3:08:09 UTC+2, Andrew Godwin написа:
>
> I'm afraid I don't really know what's going on then - the logs don't 
> reveal very much. I'd try reducing it down to simpler code until you can 
> replicate it in only a few lines and work from there.
>
> Andrew
>
> On Tue, Feb 21, 2017 at 11:46 AM, Nikoleta Misheva  > wrote:
>
>> I don't know how to get the close code. It disconnects right after you 
>> hit the send button but it manages to send the message, I had prints and 
>> the message was right and etc but was always after disconnect. My 
>> disconnect function basically deletes the room. And python's console logs:
>> [2017/02/21 21:42:50] WebSocket DISCONNECT /play [127.0.0.1:65273]
>> [2017/02/21 21:42:50] WebSocket HANDSHAKING /play [127.0.0.1:65282]
>> It reconnects.
>>
>>
>> вторник, 21 февруари 2017 г., 20:45:13 UTC+2, Andrew Godwin написа:
>>>
>>> How does it disconnect? What WebSocket close code do you get? (You'll 
>>> need to add JS to log it) What prints on the Python console?
>>>
>>> Andrew
>>>
>>> On Tue, Feb 21, 2017 at 12:27 AM, Nikoleta Misheva  
>>> wrote:
>>>
 When I send message the websocket disconnects. I am able to get the 
 message, but I can't proceed further since disconnect is supposed to 
 delete 
 the room. I tested it with basic prints after every statement and it 
 disconnects right after the receiver gets the message because everything 
 that is in ws_receive is printed after it disconnects

 My consumer:

 @channel_session_user
 def ws_receive(message):
  username = message.user.username
  text = json.loads(message['text']).get('text')
  # Use my algorithm here
  score = score_argument.get_rating(text)
  # find the room with our users
  # print(type(username))
  # print(username)
  current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
 Q(username_b=username))

  # current_room = PairUsers.objects.filter(Q(username_a=username) | 
 Q(username_b=username)).first()

  # check which user you got and send the message to the other
  if current_room.username_b == username:
  current_room.score_b = score
  other_channel = Channel(current_room.reply_channel_a)
  message.reply_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  message.reply_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
  else:
  current_room.score_a = score
  other_channel = Channel(current_room.reply_channel_b)
  message.reply_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  message.reply_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "message": text,
  "user": username, }),
  })
  other_channel.send({'text': json.dumps({
  "score": score,
  "user": username, }),
  })
 The JS:

 $(function () {
  // Correctly decide between ws:// and wss://
  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
  var ws_path = ws_scheme + '://' + window.location.host + 
 window.location.pathname;
  console.log("Connecting to " + ws_path);
  var socket = new ReconnectingWebSocket(ws_path);

  socket.onmessage = function(message){
  var data = JSON.parse(message.data);
  if(!data.score){
  var element = $([
  "",
  "" + data.message + "",
  "",
  "" + data.user + "",
  "",
  ""
  ].join("\n"));
  $("#chat_table tbody").append(element);
  }
  else {
  var element = $([
  "",
  "" + data.user + "'s score is:" + data.score + "",
  ""
  ].join("\n"));
  $("#chat_table tbody").append(element);

  }
  }

  $('#arg_form').on('submit',function () {
  socket.send(JSON.stringify({
  "text": $('#argument').val()
  }))})

  });
 What might be the cause?



 -- 
 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...@googlegrou

Re: Django-channels disconnects right after sending a message

2017-02-21 Thread Andrew Godwin
Then you need to add more and more back until it does disconnect and you
should be able to find the line that's doing it!

Andrew

On Tue, Feb 21, 2017 at 11:03 PM, Nikoleta Misheva 
wrote:

> I tried  the simplest example and it works fine and does not disconnect.
>
> def websocket_receive(message):
>  text = message.content.get('text')
>  if text:
>  message.reply_channel.send({"text": "You said: {}".format(text)})
>
> And using the JS console
> socket = new WebSocket("ws://" + window.location.host + "/chat/");
> socket.onmessage = function(e) {
> alert(e.data);
> }
> socket.onopen = function() {
> socket.send("hello world");
> }
>
> сряда, 22 февруари 2017 г., 3:08:09 UTC+2, Andrew Godwin написа:
>>
>> I'm afraid I don't really know what's going on then - the logs don't
>> reveal very much. I'd try reducing it down to simpler code until you can
>> replicate it in only a few lines and work from there.
>>
>> Andrew
>>
>> On Tue, Feb 21, 2017 at 11:46 AM, Nikoleta Misheva 
>> wrote:
>>
>>> I don't know how to get the close code. It disconnects right after you
>>> hit the send button but it manages to send the message, I had prints and
>>> the message was right and etc but was always after disconnect. My
>>> disconnect function basically deletes the room. And python's console logs:
>>> [2017/02/21 21:42:50] WebSocket DISCONNECT /play [127.0.0.1:65273]
>>> [2017/02/21 21:42:50] WebSocket HANDSHAKING /play [127.0.0.1:65282]
>>> It reconnects.
>>>
>>>
>>> вторник, 21 февруари 2017 г., 20:45:13 UTC+2, Andrew Godwin написа:

 How does it disconnect? What WebSocket close code do you get? (You'll
 need to add JS to log it) What prints on the Python console?

 Andrew

 On Tue, Feb 21, 2017 at 12:27 AM, Nikoleta Misheva 
 wrote:

> When I send message the websocket disconnects. I am able to get the
> message, but I can't proceed further since disconnect is supposed to 
> delete
> the room. I tested it with basic prints after every statement and it
> disconnects right after the receiver gets the message because everything
> that is in ws_receive is printed after it disconnects
>
> My consumer:
>
> @channel_session_user
> def ws_receive(message):
>  username = message.user.username
>  text = json.loads(message['text']).get('text')
>  # Use my algorithm here
>  score = score_argument.get_rating(text)
>  # find the room with our users
>  # print(type(username))
>  # print(username)
>  current_room = get_object_or_404(PairUsers, Q(username_a=username) | 
> Q(username_b=username))
>
>  # current_room = PairUsers.objects.filter(Q(username_a=username) | 
> Q(username_b=username)).first()
>
>  # check which user you got and send the message to the other
>  if current_room.username_b == username:
>  current_room.score_b = score
>  other_channel = Channel(current_room.reply_channel_a)
>  message.reply_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  message.reply_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
>  else:
>  current_room.score_a = score
>  other_channel = Channel(current_room.reply_channel_b)
>  message.reply_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  message.reply_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "message": text,
>  "user": username, }),
>  })
>  other_channel.send({'text': json.dumps({
>  "score": score,
>  "user": username, }),
>  })
> The JS:
>
> $(function () {
>  // Correctly decide between ws:// and wss://
>  var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
>  var ws_path = ws_scheme + '://' + window.location.host + 
> window.location.pathname;
>  console.log("Connecting to " + ws_path);
>  var socket = new ReconnectingWebSocket(ws_path);
>
>  socket.onmessage = function(message){
>  var data = JSON.parse(message.data);
>  if(!data.score){
>  var element = $([
>  "",
>  "" + data.message + "",
>  "",
>  "" + data.user + "",
>  "",
>  ""
>  ].join("\n"));
>  $("#chat_table tbody").append(element);
>  }
>  else {
>  var element = $([
>  "",
>  "" + data.user + "'s score is:" + data.score + "",
>  ""
>  ].join("\n"));
>  $("#chat_table tbody").append(element);
>
>  }
>  }
>
>  $('#arg_form').on('submit',function () {
>  socket.send(JSON.stringify({
>