Friday, March 31, 2017

Returning unique values from a foreign key in a ListView

Hi everyone,

Goal
- I have a ListView built around ModelA. 
- ModelA has a foreign key to ModelB. 
- I want to return a list with all unique entries of a required field (i.e. 'foo') from ModelB.

Context
I have a table of clients (ModelA) and a table of jobs I do (ModelB), connected via foreign key - I want to retrieve a distinct list of all the jobs I do for the clients so I can render that into the template and make a user-facing filter.

Problem 1
Can't access values in ModelB using get_queryset()  as using this for ModelA and I don't know how to query multiple tables in such a statement:

views.py


from .models import ModelA
from django.views.generic import ListView, DetailView


# Create your views here.
class IndexView(ListView):
    context_object_name
= 'modela_list'
    template_name
= 'modela/index.html'


   
def get_queryset(self):
       
return ModelA.objects.order_by('title')


Outcome 1
Couldn't work out how to return the data from ModelA *AND* a unique list of 'foo' values. Can return ALL values of 'foo' including duplicates (i.e. 'Hello', 'Hello', 'World', 'World', 'Hello', rather than the desired 'Hello', 'World')

Problem 2
Tried to do get_context_data though my understanding of this is very weak:

views.py



[code from Problem 1]
   
[...]
   
def get_context_data(self, **kwargs):
        context
= super(IndexView, self).get_context_data(**kwargs)
        qs
= context['modela_list']
        list_of_values
= qs.order_by().values('foo').distinct()
        context
.update(
           
{
               
'list_of_values': list_of_values,
           
}
       
)
       
return context


Outcome 2
Could return the unique values for the FOREIGN KEY values as they are in ModelA, could not return the assigned values from ModelB (i.e. '1', '2' returned, instead of 'Hello', 'World')

Overall Outcome
So I've managed to either get ALL the values of the required field from ModelB OR I can get the distinct values of the foreign key field from ModelA - but not the distinct values of the required field from ModelB!

Any help would be greatly appreciated!

Rich

--
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+unsubscribe@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/10f50536-b5cc-4e30-8d28-a8ca1e0dce29%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Would it be a good idea to build a IM app using django channels?

Hi Vic,

Channels would be a suitable building block for such an app, certainly, but you'd need to do a lot more work on top of it. Online presence management, chat history, login, authentication, and the protocol would all be the things you need to solve - Channels just gives you a basic eventing framework and webhooks support to start building on (in the same way Django doesn't come with, say, a built-in blog solution but the tools to build one instead).

Consulting on how to build an entire app like this would be several days of paid work for a good technical consultant, and they would be better placed to work out the context and your requirements and recommend solutions, but I would recommend using a relational database (PostgreSQL, MySQL) as a primary message store, always. Channels would then use Redis as the messaging transport; I wouldn't do caching initially as individual messages is not a very cacheable problem (everyone's view is different).

Andrew

On Fri, Mar 31, 2017 at 4:05 PM, Vic Wei <q532201960@gmail.com> wrote:
I'm trying to build a django Instant Massage app, but I have some confusions,
My app should the following needs:
1.be able to communicate in real time with browser, iOS, and Android native apps.
2.one user can send messages to another user in private
3.users can chat in serval chat room at a time
4.once a message is sent, it should be push to target user in realtime.
5.has a retry mechanism to guarantee delivery and messages should store in db like mysql
Is django channels suite my requirements? Is there a limit amout of channel or is that what I need to do is create a group for each online user including ios and android ones?
What my thought is using redis to cache the messages and store in MySQL, use celery to handle message store and distribute.
Anyone could give some advices?


--
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+unsubscribe@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/228be88c-4ca8-4b52-875c-eb361e534e57%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+unsubscribe@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/CAFwN1ur9iUyPmgE_XP8CTskEkg5waK%2BshHkLDguhR%3DqDxZupcg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: Adding fields in model, migrating a sqlite.db in production...good idea?

super thanks! i hoped for that answer!

--
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+unsubscribe@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/0c3f0264-751d-486a-9079-bd512d7f6ee9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Adding fields in model, migrating a sqlite.db in production...good idea?

Make a copy of your sqlite file and try makemigration on your copy.
Everything should go smoothly. If that's the case, you can now use
your copy as your new production database.

As a side note, I don't think using an sqlite database is bad
practice. It make it super easy to backup your data.

2017-03-31 19:19 GMT+02:00 kalinski <kalinski@amei.se>:
> Hello,
> I have a sqlite db that already holds important production data.
> Well same time I am developing that application adding functions while I need them.
> Well I know not exactly best practice.
> Now I need to add two fields to a model (boolean and char),
> I want to makemigrations, git add, git commit, git push
> Is there any risk of loosing part of the sqlite database here?
> Or can I just backup the sqlite file, try to migrate and all the data plus the new empty fields will be there?
> If someone with better knowledge can just say "yes should be working"?
> Many thanks!
> Martin
>
> --
> 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+unsubscribe@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/d67d940b-b6ce-49f5-902a-aae14ed174d3%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--

Cordialement, Coues Ludovic
+336 148 743 42

--
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+unsubscribe@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/CAEuG%2BTZzS6BEhsw4WQtdMc8gY-Lt27xGWyPTDmMO2WxMAC6Y8g%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Adding fields in model, migrating a sqlite.db in production...good idea?

Hello,
I have a sqlite db that already holds important production data.
Well same time I am developing that application adding functions while I need them.
Well I know not exactly best practice.
Now I need to add two fields to a model (boolean and char),
I want to makemigrations, git add, git commit, git push
Is there any risk of loosing part of the sqlite database here?
Or can I just backup the sqlite file, try to migrate and all the data plus the new empty fields will be there?
If someone with better knowledge can just say "yes should be working"?
Many thanks!
Martin

--
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+unsubscribe@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/d67d940b-b6ce-49f5-902a-aae14ed174d3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Django 10.6 throws 'mbcs codec error' on Windows 10 machine in autoload.py

I study Django too and my first lesson was be here https://tutorial.djangogirls.org/en/
use virtualenv

С уважением, Владислав Котвицкий
г.Краснодар, +7(988)4112077

2017-03-29 12:28 GMT+03:00 Paul Rusu-Tibreanu <paulrusu29@gmail.com>:
Hi to all,

I am trying to get started with Django. So  installing Django through pip and following the tutorial on the project's website, I first created a "mysite" project and now try to run "
python manage.py runserver". However, this gives me following error:

C:\mysite>python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
utility.execute()
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 58, in execute
super(Command, self).execute(*args, **options)
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\base.py", line 345, in execute
output = self.handle(*args, **options)
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 97, in handle
self.run(**options)
File "C:\Users\User\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 106, in run
autoreload.main(self.inner_run, None, options)
File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 333, in main
reloader(wrapped_main_func, args, kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 304, in python_reloader
exit_code = restart_with_reloader()
File "C:\Users\User\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 290, in restart_with_reloader
exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ)
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character


Does anyone know th ereason for this error and how to fix it?

Thanks a lot.

--
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+unsubscribe@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/2269a709-c132-4935-85cb-6a59e2907a9d%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+unsubscribe@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/CAGVCDGQJaPznhoicQBZbNXs0GGYfF3HH8xWyMugr52z1fAethw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Would it be a good idea to build a IM app using django channels?

I'm trying to build a django Instant Massage app, but I have some confusions,
My app should the following needs:
1.be able to communicate in real time with browser, iOS, and Android native apps.
2.one user can send messages to another user in private
3.users can chat in serval chat room at a time
4.once a message is sent, it should be push to target user in realtime.
5.has a retry mechanism to guarantee delivery and messages should store in db like mysql
Is django channels suite my requirements? Is there a limit amout of channel or is that what I need to do is create a group for each online user including ios and android ones?
What my thought is using redis to cache the messages and store in MySQL, use celery to handle message store and distribute.
Anyone could give some advices?


--
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+unsubscribe@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/228be88c-4ca8-4b52-875c-eb361e534e57%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ajax Call is sending empty request.POST or request.body

Hi.

The difference is explained here:
https://docs.djangoproject.com/en/1.10/ref/request-response/

You are sending the data in the ajax call as Jason (I suppose, from the content type), then in your view you should probably use request.body to read the json document.

I also noticed you are using a django form. In that case you can change your ajax call to send a form encoding content type and serialize the html form as the data. In your view you can then use your django form to process the data from request.POST.

--
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+unsubscribe@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/d30946f0-6403-4549-91e9-43536c129df1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Thursday, March 30, 2017

Re: django admin datepicker

On 31/03/2017 7:55 AM, sum abiut wrote:
>
>
> Hi,
> i am trying to use django admin datepicker on my custom form to have
> it show on two fields but when i run the app it only showing on one
> field, the start_date but not showing on end_date. can some please
> point me to the right direction.

What happens if you leave the widget option out altogether?

>
> here is my quote.
>
> models.py
>
> class stafleave(models.Model):
> first_name=models.CharField(max_length=45)
> last_name=models.CharField(max_length=45)
> leave_type=models.CharField(max_length=45,choices=leave)
> start_date=models.DateField()
> end_date=models.DateField()
> Total_working_Hours=models.IntegerField()
> username =models.ForeignKey(User
>
>
> forms.py
>
> class leaveform(forms.ModelForm):
> start_date = forms.DateField(widget=widgets.AdminDateWidget)
> end_date = forms.DateField(widget=widgets.AdminDateWidget)
>
> class Meta:
> model=stafleave
>
>
>
>
> template.html
>
> <html>
>
>
> <head>
>
>
> <!-- Datepicker-->
>
>
> <script type="text/javascript" src="/admin/jsi18n/"></script>
>
> <script type="text/javascript" src="/static/admin/js/core.js"></script>
>
> <script type="text/javascript"
> src="/admin_media/js/admin/RelatedObjectLookups.js"></script>
> {{ form.media }}
>
>
> <!--End Datepicker--
>
>
> </head>
>
> <body>
>
>
> <form action="" method="post">{%csrf_token%}
> <table>
> {{form.as_table}}
>
> </table>
> <br>
> <input type="submit" name="submit" value="Apply for Leave" >
>
>
> </form>
> </div>
>
>
>
> </body>
>
> </html>
>
> --
> 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+unsubscribe@googlegroups.com
> <mailto:django-users+unsubscribe@googlegroups.com>.
> To post to this group, send email to django-users@googlegroups.com
> <mailto: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/CAPCf-y7PRbbmbM%2BuSSWS7hjBqziDBWRusv7GsmikjqU%2B5hzMuw%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CAPCf-y7PRbbmbM%2BuSSWS7hjBqziDBWRusv7GsmikjqU%2B5hzMuw%40mail.gmail.com?utm_medium=email&utm_source=footer>.
> 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+unsubscribe@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/360739fe-879f-8763-d000-ef77ac7ee141%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.

django admin datepicker



Hi,
i am trying to use django admin datepicker on my custom form to have it show on two fields  but when i run the app it only showing on one field, the start_date but not showing on end_date. can some please point me to the right direction.

here is my quote.

models.py

class stafleave(models.Model):
    first_name=models.CharField(max_length=45)
    last_name=models.CharField(max_length=45)
   leave_type=models.CharField(max_length=45,choices=leave)
    start_date=models.DateField()
    end_date=models.DateField()
    Total_working_Hours=models.IntegerField()
    username =models.ForeignKey(User


forms.py

class leaveform(forms.ModelForm):
    start_date = forms.DateField(widget=widgets.AdminDateWidget)
    end_date = forms.DateField(widget=widgets.AdminDateWidget)

    class Meta:
        model=stafleave




template.html

<html>


<head>


<!-- Datepicker-->


<script type="text/javascript" src="/admin/jsi18n/"></script>

<script type="text/javascript" src="/static/admin/js/core.js"></script>

<script type="text/javascript" src="/admin_media/js/admin/RelatedObjectLookups.js"></script>
{{ form.media }}

  
    <!--End Datepicker--


</head>

<body>
 

<form action="" method="post">{%csrf_token%}
<table>
{{form.as_table}}

</table>
<br>
<input type="submit" name="submit" value="Apply for Leave" >
 

</form>
</div>



</body>

</html>

--
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+unsubscribe@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/CAPCf-y7PRbbmbM%2BuSSWS7hjBqziDBWRusv7GsmikjqU%2B5hzMuw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: NoReverseMatch when trying to use get_absolute_url with custom template tag

Oh yeah i see.

Brilliant sorted it! Thanks for your help Melvyn.

--
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+unsubscribe@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/7a2b33ac-7424-4a24-9888-148c11db5d7a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ajax Call is sending empty request.POST or request.body

Hi i am still not clear when using request.POST or request.body.

Anyway this ajax call is sending emprty request.POST, or empty  request.body:

    <script type="text/javascript">
    $(document).ready(function(){

        $(".captcha_form").submit(function(event){
            var check = $('#id_check').val();
            alert(check);
            $.ajax({
                type: "POST", 
                url: "./captcha",
                contentType: "application/json",
                data:check,
                dataType: "json",
                success: function(data) {
                    alert("passa");
                    alert(data.status);
                   
                  },
                error: function(data) {
                    alert("NOT_OK");
                  }         
            });
       
    });
    });
   
    </script>


<form id ="captcha_form" class="captcha_form" action="./captcha" method="post">{% csrf_token %}
    {{form}}
<input type="submit" id="button" class="button" value="Invio"/>
</form>


class check_box_form(forms.Form):
    scelte = [('Yes','Yes'),('No','No')]
    check = forms.ChoiceField(label='I am a Robot       ',choices=scelte)

--
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+unsubscribe@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/c600a8c8-486b-4359-862e-068ca471d5e2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Wednesday, March 29, 2017

Re: TransactionManagementError from inside atomic block

Hey Simon,

Thank you for your response, we were able to resolve the problem soon after I posted the query.

And yes, you are correct, it was an issue with having multiple DB connections and the `auto-commit` being turned off for one, but then another connection being used for querying.

We earlier had a master-slave configuration for our DB and were using a DB router to route all reads to the slave. That is still in use and that is why the `deafualt` connection was used as we entered the `atomic` block, but `slave` when we made the read.

Thank you again.

On Thu, Mar 30, 2017 at 4:39 AM Simon Charette <charette.s@gmail.com> wrote:
Hi Ketan,

I'm afraid this will be really hard to solve without the code that is raising this exception.

Some details that could help debug the issue:

1. Are your workers multi-threaded?
2. Are you sure you are not calling functions performing manual transaction management?
3. Is your atomic() block using the same database involved in the select_for_update() call?

e.g. Are you using transaction.atomic() (which will use the default database)
but have database routers that could route reads/writes to another db?

Cheers,
Simon

Le samedi 25 mars 2017 15:08:19 UTC-4, Ketan Bhatt a écrit :
I have a method that updates a row in the table.
To avoid race condition, I locked the row using `select_for_update` inside an `atomic` block and doing the update.
This method is called from a celery task.

This works well on my local machine. But when this gets called on my production server (two tasks being picked up by two workers at the same time and therefore trying to access the same row at once), I get: 
`TransactionManagementError('select_for_update cannot be used outside of a transaction.',)`

I checked that to use `select_for_update`, autocommit should be False.
Inside the atomic block `get_autocommit` returns False.

Now on production this must be returning `TRUE`.


What could be the reason?

--
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+unsubscribe@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/91f6b088-e255-4ff9-a9c5-f033ffdf4211%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+unsubscribe@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/CACyRkBVpKO1Khuf4Z%3D_PggA3TPcFa92anCgC_p_tzw92kwbQVw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Re: TransactionManagementError from inside atomic block

Hi Ketan,

I'm afraid this will be really hard to solve without the code that is raising this exception.

Some details that could help debug the issue:

1. Are your workers multi-threaded?
2. Are you sure you are not calling functions performing manual transaction management?
3. Is your atomic() block using the same database involved in the select_for_update() call?

e.g. Are you using transaction.atomic() (which will use the default database)
but have database routers that could route reads/writes to another db?

Cheers,
Simon

Le samedi 25 mars 2017 15:08:19 UTC-4, Ketan Bhatt a écrit :
I have a method that updates a row in the table.
To avoid race condition, I locked the row using `select_for_update` inside an `atomic` block and doing the update.
This method is called from a celery task.

This works well on my local machine. But when this gets called on my production server (two tasks being picked up by two workers at the same time and therefore trying to access the same row at once), I get: 
`TransactionManagementError('select_for_update cannot be used outside of a transaction.',)`

I checked that to use `select_for_update`, autocommit should be False.
Inside the atomic block `get_autocommit` returns False.

Now on production this must be returning `TRUE`.


What could be the reason?

--
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+unsubscribe@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/91f6b088-e255-4ff9-a9c5-f033ffdf4211%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Executing DB-Queries during import

> Is it advisable to execute db queries in my AppConfig ready signal handler?

AppConfig.ready() is still at module-level.

> Use case: I want to add URL patterns which get collected from db rows.

It might be more appropriate to define an URL resolver (an object like django.conf.url)
that performs queries at resolve()/reverse() time instead.

A simpler solution could be to define a catch all view like django-cms does and
perform the routing inside the view.

Cheers,
Simon

Le mercredi 29 mars 2017 08:39:52 UTC-4, guettli a écrit :


Am Mittwoch, 22. März 2017 19:20:43 UTC+1 schrieb Tim Graham:
Correct, module level queries should be avoided. Django might try to add some detection to warn about or prohibit that, see https://groups.google.com/d/topic/django-developers/7JwWatLfP44/discussion.


I understand db queries at module-level (aka "import time") should not happen.

When I am allowed to do db queries.

Is it advisable to execute db queries in my AppConfig ready signal handler?

Use case: I want to add URL patterns which get collected from db rows.


--
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+unsubscribe@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/1687811b-b779-4031-a127-d9549bc0bdf3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: From SQL to Django Queryset API

Hello Mauro,

The following should do

from django.db.models import F

Movimento.objects.values(
    'anno','impianto'
).annotate(
    dare=Sum('dare),
    avere=Sum('avere),
    diff=Sum(F('dare') - F('avere)),
)

Cheers,
Simon

Le mercredi 29 mars 2017 16:19:37 UTC-4, Mauro Ziliani a écrit :
Hi all.
My name's Mauro and I working on a DB (SQLite3 now and Postgres in the future).

I have a table Movimento with the fields
anno integer,impianto integer,dare decimal(10,2),avere decimal(10,2)

BY hands I can run

SELECT anno,impianto, sum(dare), sum(avere) FROM movimento 
GROUP BY anno,impianto
ORDER BY anno,impianto 

With django Api I write

Movimento.objects.values('anno','impianto').annotate(dare=Sum('dare), avere=Sum('avere))

And I get the same beaviour.

Now I need to translate the following SQL script

SELECT anno,impianto, sum(dare), sum(avere), sum(dare-avere)
FROM movimento 
GROUP BY anno,impianto
ORDER BY anno,impianto 

into django API queryset.

Is it possible todo this in one row?

Cna you give me some idea to solve this translaion?

Finally I'll render the results into a table.

Best regards,
   MZ

--
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+unsubscribe@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/9c8f43e7-6d84-4190-9dbc-beb25b3e1a95%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: NoReverseMatch when trying to use get_absolute_url with custom template tag

On Wednesday 29 March 2017 09:16:17 Will Holmes wrote:

 

> url(r'^(?P<id>\d+)$/', views.viewEvent, name='viewevent'),

 

name = viewevent

 

> def get_absolute_url(self):

> return reverse('cal:viewEvent', args=[str(self.id)],

> current_app='cal')

 

name = viewEvent

 

> Sorry about the load of code posted. Any chance anyone knows what

> might have caused this issue?

 

Do you see it now?

--

Melvyn Sopacua

NoReverseMatch when trying to use get_absolute_url with custom template tag

I am making a calendar app which has a custom template tag that takes the python HTML template function and overlays objects from the Events model on the correct days. I am trying to get the displayed objects to have a link directly to an object detail/edit view and am trying to use get_absolute_url and to reverse render this view. This is necessary as the custom template tag doesn't load correctly if I try to hardcode {% url %} template tags into it for each event via a for loop. I have spent some hours looking through stack overflow questions with no luck and have even changed my reverse to the object ID rather than the title of the event. I am hoping this is just a small thing that I have overlooked but no sure.


view:

def home(request, month=None, year=None):      if month == None:          _date = datetime.now()      else:          _date = date(int(year), int(month), 1)      title = "%s, %s" % (_date.strftime("%B"), _date.strftime("%Y"))        return render(request, 'calendar.html', calendar(_date, title))


url:

app_name = 'cal'  urlpatterns = [      url(r'^$', views.home, name='home'),      url(r'^newevent/$', views.newEvent, name='newevent'),      url(r'^(?P<id>\d+)$/', views.viewEvent, name='viewevent'),      url(r'^(?P<month>\d+)/(?P<year>\d+)$', views.home, name='another-month')  ]


HTML:

    <div>        {% load calendarify %}        <span id="calendarify">{% calendarify year month event_list %}</span>      </div>


Template tag relevant function:

    def formatday(self, day, weekday):          if day != 0:              cssid = self.cssclasses[weekday]              cssclass = "daybox"              if date.today() == date(self.year, self.month, day):                  cssid += ' today'              if day in self.events:                  cssid += ' filled'                  body = ['<ul>']                  for event in self.events[day]:                      body.append('<li>')                      body.append('<a href="%s">' % event.get_absolute_url())                      body.append(esc(event.title))                      body.append('</a></li>')                  body.append('</ul>')                  return self.day_cell(                      cssclass, cssid, '<span class="dayNumber">%d</span> %s' % (                          day, ''.join(body)))              return self.day_cell(                  cssclass, cssid, '<span class="dayNumberNoReadings">%d</span>' % (day))          return self.day_cell('nodaybox', 'noday', '&nbsp;')


Model:

class Events(models.Model):      ...        def get_absolute_url(self):          return reverse('cal:viewEvent', args=[str(self.id)], current_app='cal')


Sorry about the load of code posted. Any chance anyone knows what might have caused this issue?

--
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+unsubscribe@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/aae357a0-84a7-46bd-a93d-4aac61f352c9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Meta class completely missing.

Done. No change.

What is also very bizarre is that *not* having a Meta class would make the "Restaurant" test (tests/model_inheritance/models.py : Line 107) break badly; class Restaurant has a Meta that subclasses the Meta of class Rating. So if Meta does not exist... well you see the problem. In fact this *exact* thing occurs in my situation. 

I have a "class Case(models.Model)" with a "class Meta:" and a "class MDxCase(Case):" if I try to do "class Meta(Case.Meta):" for class MDxCase an AttributeError error is thrown "Case has no attribute 'Meta'". 

This is very very odd.
Can anyone explain this behavior or have any other ideas to try?

--Brandon

On Mon, Mar 20, 2017 at 4:55 AM, chris rose <chris.rose.one@gmail.com> wrote:
hi brandon

try removing (object) from your meta class declaration

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/gGfLmihCilI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users+unsubscribe@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/30d054d7-8150-4eeb-bc3b-cf8a762078ae%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+unsubscribe@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/CAFfc3713xmobr7-VH%2BdTDyGdN2fAyw_KgmmRmw1GZovcTA%3DgpA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.