Re: Adding code when pressing one of admin's save buttons

2017-07-25 Thread Mike Dewhirst

On 25/07/2017 9:29 PM, ron_w_add via Django users wrote:


I am using Django’s admin interface to create new records. A record 
includes (amongst other fields) the date and time that a photo was 
taken. These fields will be filled into the database when either the 
‘Save and add another’, ‘Save and continue editing’ or the ‘Save’ 
buttons are pressed (i.e. these details will be read from the image 
file and entered into the database rather than the administrator doing 
this manually).


How can I added the extra code required to add the date and time when 
I press one of these buttons? Some example code would be appreciated.




class MyModel(models.Model):

...
photodatetime = models.DateTimeField()  
...

def save(self, *args, **kwargs):
photodatetime = self.getphotoinfo()
super(MyModel, self).save(*args, **kwargs)

def getphotoinfo(self):
...






Thanks

--
You received this message because you are subscribed to the Google 
Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send 
an email to django-users+unsubscr...@googlegroups.com 
.
To post to this group, send email to django-users@googlegroups.com 
.

Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/63559d9c-15c6-4ce1-b477-8e24b030ce0c%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/990bc5c5-a65d-d729-b895-6eaf0293d139%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Re: How can I auto-fill a field in the model without showing a form field to the user?

2017-07-25 Thread Mike Dewhirst

On 26/07/2017 3:15 AM, Alexander Joseph wrote:

How did you learn all the methods that are available


Django is very comprehensively documented and almost any question you 
can think up is only a google search away. Typically a search will 
reveal a Django doc reference and StackOverflow answers. I must say 
looking up the docs is very valuable because you learn so much else 
besides your original quest.


Books are another good source. My preferred one is Two Scoops of Django.

Welcome.


--
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/c8b126a7-4ff6-484a-1c57-c1e9fada7f21%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Re: TypeError: __init__() takes 2 positional arguments but 3 were given (django-material)

2017-07-25 Thread Tim Graham
Please give the exception traceback.

On Tuesday, July 25, 2017 at 3:35:41 PM UTC-4, Elias Coutinho wrote:
>
> Hello guys!
>
> I'm trying to recreate a form with Inline using django and django-stuff. I 
> already got it once, but this is not being easy!
>
> I want to create a form that can register a Client and its addresses, or 
> something similar to this link here.
>
> Example 1: Adding contacts.
>
> Example 2: Adding addresses.
>
> I'm trying like this:
>
> *Forms.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *from django import formsfrom material import Layout, Row, Fieldsetfrom 
> .models import Clientclass Address(forms.Form):# TA FEITOpublic_place = 
> forms.CharField(label='Logradouro')number = 
> forms.CharField(label='Número')city = forms.CharField(label='Cidade')  
>   state = forms.CharField(label='Estado')zipcode = 
> forms.CharField(label='Cep')country = forms.CharField(label='País')
> phone = forms.CharField(label='Fone')class Meta:
> verbose_name_plural = 'endereços'verbose_name = 'endereço'def 
> __str__(self):return self.profissaoclass 
> ClientModelForm(forms.ModelForm):class Meta:model = Client  
>   fields = '__all__'layout = Layout(Fieldset("Client",  
>Row('name', ), Row('birthday','purchase_limit'),
>  Row('address1', ), Row('compra_sempre', ),
>  ),)*
> *views.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *import extra_viewsfrom braces.views import LoginRequiredMixinfrom 
> extra_views import CreateWithInlinesView, NamedFormsetsMixinfrom material 
> import LayoutMixin, Fieldsetfrom material.admin.base import Inlinefrom 
> danibraz.persons.forms import *from .models import Addressclass 
> ItemInline(extra_views.InlineFormSet):model = Addressfields = 
> ['kynd', 
> 'public_place','number','city','state','zipcode','country','phone']#campos 
> do endereçoextra = 1# Define aquantidade de linhas a apresentar.class 
> NewClientsView(LoginRequiredMixin,LayoutMixin,
>  NamedFormsetsMixin, CreateWithInlinesView):title = 
> "Inclua um cliente"model = Client#print('Chegou na linha 334')
> layout = Layout(Fieldset("Inclua um cliente",
>  Row('name', ), Row('birthday','purchase_limit'),  
>Row('address1', ), Row('compra_sempre', ),  
>),Inline('Endereços', ItemInline),)#print('Chegou na 
> linha 340')def forms_valid(self, form, inlines):new = 
> form.save(commit=False)new.save()form.save_m2m()
> return super(NewClientsView, self).forms_valid(form, inlines)def 
> get_success_url(self):return 
> self.object.get_absolute_url()models.py*
>
> # from django.contrib.auth.models import User
> from django.db import models
>
>
> class Person(models.Model):
> # class Meta:
> # abstract = True
>
> name = models.CharField('Nome',max_length=100)
> birthday = models.DateField('Aniversário')
> address1 = models.CharField('Endereço 1',max_length=100)
> purchase_limit = models.DecimalField('Limite de compra',max_digits=15, 
> decimal_places=2)
>
>
> class Meta:
> verbose_name_plural = 'pessoas'
> verbose_name = 'pessoa'
>
> def __str__(self):
> return self.name
>
> def get_child(self):
> if hasattr(self, 'client'):
> return self.client
> elif hasattr(self, 'employee'):
> return self.employee
> else:
> return None
>
> def get_type(self):
> if hasattr(self, 'client'):
> return 'client'
> elif hasattr(self, 'employee'):
> return 'employee'
> else:
> return None
>
>
> class Address(models.Model):
> KINDS_CHOICES = (
> ('P', 'PRINCIPAL'),
> ('C', 'COBRANÇA'),
> ('E', 'ENTREGA'),
> )
>
> person = models.ForeignKey('Person')
> kynd = models.CharField('Tipo', max_length=1, choices=KINDS_CHOICES)
> public_place = models.CharField('Logradouro',max_length=150)
> number = models.CharField('Número',max_length=150)
> city = models.CharField('Cidade',max_length=150)
> state = models.CharField('Estado',max_length=150)
> zipcode = models.CharField('Cep',max_length=10)
> country = models.CharField('País',max_length=150, choices=COUNTRY_CHOICES)
> phone = models.CharField('Fone',max_length=50)
>
> class Meta:
> verbose_name_plural = 'endereços'
> verbose_name = 'endereço'
>
> def __str__(self):
> return self.public_place
>
>
>
> class Client(Person):
> compra_sempre = models.BooleanField('Compra Sempre',default=False)
>
> def save(self, *args, **kwargs):
> super(Client, self).save(*args, **kwargs)
>
> class Meta:
> 

TypeError: __init__() takes 2 positional arguments but 3 were given (django-material)

2017-07-25 Thread Elias Coutinho
Hello guys!

I'm trying to recreate a form with Inline using django and django-stuff. I 
already got it once, but this is not being easy!

I want to create a form that can register a Client and its addresses, or 
something similar to this link here.

Example 1: Adding contacts.

Example 2: Adding addresses.

I'm trying like this:

*Forms.py*






































*from django import formsfrom material import Layout, Row, Fieldsetfrom 
.models import Clientclass Address(forms.Form):# TA FEITOpublic_place = 
forms.CharField(label='Logradouro')number = 
forms.CharField(label='Número')city = forms.CharField(label='Cidade')  
  state = forms.CharField(label='Estado')zipcode = 
forms.CharField(label='Cep')country = forms.CharField(label='País')
phone = forms.CharField(label='Fone')class Meta:
verbose_name_plural = 'endereços'verbose_name = 'endereço'def 
__str__(self):return self.profissaoclass 
ClientModelForm(forms.ModelForm):class Meta:model = Client  
  fields = '__all__'layout = Layout(Fieldset("Client",  
   Row('name', ), Row('birthday','purchase_limit'),
 Row('address1', ), Row('compra_sempre', ),
 ),)*
*views.py*













































*import extra_viewsfrom braces.views import LoginRequiredMixinfrom 
extra_views import CreateWithInlinesView, NamedFormsetsMixinfrom material 
import LayoutMixin, Fieldsetfrom material.admin.base import Inlinefrom 
danibraz.persons.forms import *from .models import Addressclass 
ItemInline(extra_views.InlineFormSet):model = Addressfields = 
['kynd', 
'public_place','number','city','state','zipcode','country','phone']#campos 
do endereçoextra = 1# Define aquantidade de linhas a apresentar.class 
NewClientsView(LoginRequiredMixin,LayoutMixin,
 NamedFormsetsMixin, CreateWithInlinesView):title = 
"Inclua um cliente"model = Client#print('Chegou na linha 334')
layout = Layout(Fieldset("Inclua um cliente",
 Row('name', ), Row('birthday','purchase_limit'),  
   Row('address1', ), Row('compra_sempre', ),  
   ),Inline('Endereços', ItemInline),)#print('Chegou na 
linha 340')def forms_valid(self, form, inlines):new = 
form.save(commit=False)new.save()form.save_m2m()
return super(NewClientsView, self).forms_valid(form, inlines)def 
get_success_url(self):return 
self.object.get_absolute_url()models.py*

# from django.contrib.auth.models import User
from django.db import models


class Person(models.Model):
# class Meta:
# abstract = True

name = models.CharField('Nome',max_length=100)
birthday = models.DateField('Aniversário')
address1 = models.CharField('Endereço 1',max_length=100)
purchase_limit = models.DecimalField('Limite de compra',max_digits=15, 
decimal_places=2)


class Meta:
verbose_name_plural = 'pessoas'
verbose_name = 'pessoa'

def __str__(self):
return self.name

def get_child(self):
if hasattr(self, 'client'):
return self.client
elif hasattr(self, 'employee'):
return self.employee
else:
return None

def get_type(self):
if hasattr(self, 'client'):
return 'client'
elif hasattr(self, 'employee'):
return 'employee'
else:
return None


class Address(models.Model):
KINDS_CHOICES = (
('P', 'PRINCIPAL'),
('C', 'COBRANÇA'),
('E', 'ENTREGA'),
)

person = models.ForeignKey('Person')
kynd = models.CharField('Tipo', max_length=1, choices=KINDS_CHOICES)
public_place = models.CharField('Logradouro',max_length=150)
number = models.CharField('Número',max_length=150)
city = models.CharField('Cidade',max_length=150)
state = models.CharField('Estado',max_length=150)
zipcode = models.CharField('Cep',max_length=10)
country = models.CharField('País',max_length=150, choices=COUNTRY_CHOICES)
phone = models.CharField('Fone',max_length=50)

class Meta:
verbose_name_plural = 'endereços'
verbose_name = 'endereço'

def __str__(self):
return self.public_place



class Client(Person):
compra_sempre = models.BooleanField('Compra Sempre',default=False)

def save(self, *args, **kwargs):
super(Client, self).save(*args, **kwargs)

class Meta:
verbose_name = 'Cliente'
verbose_name_plural = 'Clientes'



class Employee(Person):
ctps = models.CharField('Carteira de Trabalho',max_length=25)
salary = models.DecimalField('Salário',max_digits=15, decimal_places=2)


def save(self, *args, **kwargs):
# self.operacao = CONTA_OPERACAO_DEBITO
super(Employee, self).save(*args, **kwargs)

class Meta:
verbose_name = 

Re: Django Forms HorizontalRadioSelect Renderer not working.

2017-07-25 Thread Tim Graham
Replace renderer=HorizontalRadioRenderer with attrs={'class': 'inline'} and 
then style radio elements using CSS. contrib.admin uses this approach. 
Here's the CSS:

https://github.com/django/django/blob/d17eaa868cd6911197dcd8b096c4f0418c47007e/django/contrib/admin/static/admin/css/forms.css#L42-L66

On Tuesday, July 25, 2017 at 8:10:58 AM UTC-4, Shazia Nusrat wrote:
>
> I am using Djnago 1.11.1. I've tried template approach but perhaps I've 
> missed out something. 
>
> If you can provide me some workable example I will be really really 
> thankful.
>
> Regards,
> Shazia
>
> On Tue, Jul 25, 2017 at 1:57 AM, ecas  
> wrote:
>
>> Which version of Django are you using? From 1.11 the widgets changed to a 
>> template mechanism.
>>
>> https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#radioselect
>>
>> Maybe this can help:
>>
>> https://stackoverflow.com/questions/44187640/django-1-11-horizontal-choice-field
>>
>> El dimarts, 25 juliol de 2017 9:53:13 UTC+2, Shazia Nusrat va escriure:
>>
>>> Hi,
>>>
>>> I need to select form values horizontally but couldn't get it work.
>>>
>>> Following is the code:
>>>
>>> class HorizontalRadioRenderer(forms.RadioSelect.renderer):
>>>   def render(self):
>>> return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
>>>
>>> class ResponseForm(models.ModelForm):
>>> class Meta:
>>> model = Response
>>> fields = ('interviewer', 'interviewee', 'conditions', 'comments')
>>> def __init__(self, *args, **kwargs):
>>> # expects a survey object to be passed in initially
>>> survey = kwargs.pop('survey')
>>> self.survey = survey
>>> super(ResponseForm, self).__init__(*args, **kwargs)
>>> self.uuid = random_uuid = uuid.uuid4().hex
>>> # add a field for each survey question, corresponding to the 
>>> question
>>> # type as appropriate.
>>> data = kwargs.get('data')
>>> for q in survey.questions():
>>> if q.question_type == Question.TEXT:
>>> self.fields["question_%d" % q.pk] = 
>>> forms.CharField(label=q.text,
>>> widget=forms.Textarea)
>>> elif q.question_type == Question.RADIO:
>>> question_choices = q.get_choices()
>>> self.fields["question_%d" % q.pk] = 
>>> forms.ChoiceField(label=q.text,
>>> 
>>> widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
>>> choices = question_choices)
>>>
>>> Error:
>>>
>>> class HorizontalRadioRenderer(forms.RadioSelect.renderer):
>>> AttributeError: type object 'RadioSelect' has no attribute 'renderer'
>>>
>>> Please advise
>>>
>>> -- 
>> 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/d7280ade-f0c0-4c31-813f-1747f1f3cd29%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/90e4c5c4-00a0-48d8-a662-9c6fd6a4818e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: upgrading django 1.11 warning list

2017-07-25 Thread Tim Graham
Yes, it's safe to add that to migrations.

https://docs.djangoproject.com/en/dev/releases/1.9/#foreignkey-and-onetoonefield-on-delete-argument

On Tuesday, July 25, 2017 at 8:55:24 AM UTC-4, pablochud wrote:
>
> Hi!
> It showed me warning related to 'on_delete' as required arg for ForeignKey 
> in migration files. is it safty to change migration file manually or is 
> there alternative way to bypass warning?
>

-- 
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/121339cd-75f1-44ae-91b1-2b9d62d1835c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: It's possible to cache entire model

2017-07-25 Thread Fellipe Henrique
Thanks Gideon,

I installed here and for now, it's ok!

T.·.F.·.A.·. S+F
*Fellipe Henrique P. Soares*

e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 's/(.)/chr(ord($1)-2*3)/ge'
*Fedora Ambassador: https://fedoraproject.org/wiki/User:Fellipeh
*
*Blog: *http:www.fellipeh.eti.br
*GitHub: https://github.com/fellipeh *
*Twitter: @fh_bash*

On Tue, Jul 25, 2017 at 8:55 AM, Gideon Boateng  wrote:

> Hi Fellipe,
>>
> if you want to cache an entire model. You can look at this package(Django
> Cachalot  - http://django-cachalot.readthedocs.io/en/latest/
> ).
>  I use it in production and its been amazing. It caches the entire ORM and
> does automatic invalidation.
> its very easy to use.
> you literally need two lines of code and you will be up and running.
> It has support for Redis and Mem cache.
>
> Cheers,
>
> --
> 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/e6009f69-b7fb-46f7-9d22-c693d23522c1%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/CAF1jwZHF--UDJn3ESi%3D%3Dobq9LHCCJ%2BGBeY_O8YZAzajwoR6%2BLw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How can I auto-fill a field in the model without showing a form field to the user?

2017-07-25 Thread Alexander Joseph
Thanks very much, that works great!

I'm still lost on what all the methods are that I am able to override. How 
did you learn all the methods that are available, like the save method, to 
override? I used some functions in the past with php but mostly I did 
procedural programming and used a low level MVC framework called 
CodeIgniter which was very simple to learn and start using. I'm having a 
harder time with django though, mostly because it seems to me like there is 
a lot of magic happening behind the scenes - like this save method

Thanks again for your help!





On Tuesday, July 25, 2017 at 4:45:12 AM UTC-6, ecas wrote:
>
> One way could be to overload the save method of the model. Maybe something 
> like this in your models.py:
>
> import datetime
>
> class Invoice(models.Model):
> 
> def save(self, *args, **kwargs):
> if not self.id:
> today = datetime.date.today()
> date_str = datetime.datetime.strftime(today, '%y%m%d')
> last_invoice = 
> Invoice.objects.filter(invoice_number__startswith=date_str).order_by('invoice_number').last()
> if last_invoice:
> last_invoice_num = last_invoice.invoice_number[-2:]
> new_invoice_num = int(last_invoice_num) + 1
> new_invoice_num = "%02d" % new_invoice_num
> else:
> new_invoice_num = '01'
> self.invoice_number = date_str + new_invoice_num
> super(Invoice, self).save(*args, **kwargs)
>
>
> El dimarts, 25 juliol de 2017 6:23:44 UTC+2, Alexander Joseph va escriure:
>>
>> I'm new to django, but coming from php I think its the greatest thing 
>> ever.
>>
>> I have a model for Invoices ...
>>
>> {{{
>> from django.conf import settings
>> from django.db import models
>> from django.core.urlresolvers import reverse
>> #from django.contrib.auth.models import User
>>
>> # Create your models here.
>> class Invoice(models.Model):
>> created_at = models.DateTimeField(auto_now_add=True)
>> their_company = models.CharField(max_length=255)
>> invoice_number = models.CharField(max_length=50, default='')
>> bill_to = models.CharField(max_length=255, default='')
>> created_by = models.ForeignKey(settings.AUTH_USER_MODEL)
>> 
>> class Meta:
>> ordering = ['invoice_number', ]
>> 
>> def __str__(self):
>> return self.invoice_number
>> 
>> def get_absolute_url(self):
>> return reverse("accounting:invoices:detail", kwargs={"pk": 
>> self.pk})
>> }}}
>>
>> right now the user has to put in the invoice number themselves. I want to 
>> not give the user that option though - I'd like to autofill that field in 
>> the database with a concatenation of the 2 digit year (17) plus 2 digit 
>> month (07) plus 2 digit day (24) and then a 2 digit auto increment for 
>> every invoice created on that specific date so the first invoice created 
>> today would be 17072401 and the second would be 17072402, etc. I'm guessing 
>> I need a field just for the date and another for the iteration of each 
>> invoice.
>>
>> Can anyone give me some direction on this? First I'm not sure how to 
>> autofill a field in the database without getting the input from the user, 
>> and I'm also not sure how I would do the concatenation with the right 
>> numbers. Thanks for your help
>>
>

-- 
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/e99393cf-0764-45e4-9fde-5e12dbf79bf6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Multiple User Types in Django 1.11

2017-07-25 Thread Gabriel - Iulian Dumbrava
You may go with Russ' solution or you may create two UserGroups, one for 
Students and one for Teachers, each having different access rights. This 
also allows for the edge case where a person may be a teacher and a student 
on the same time.

Different behavior at python level can be implemented by using to proxy 
models, one for Student and one for Teacher, but this solution works if you 
don't want to have different attributes on them.

More on proxy here 
.

marți, 25 iulie 2017, 04:02:09 UTC+3, Russell Keith-Magee a scris:
>
> Short version: You don’t.
>
> Your site may have 2 types of user - but that doesn’t mean you have 2 user 
> models. The user model is primarily for determining authentication; 
> authorisation can be handled separately. 
>
> So - set up a user model the way you normally would; then define a Teacher 
> model and and Student model, each with a OneToOneKey to User. The user logs 
> in, and you can determine what type of user they are by looking for the 
> existence of a “teacher” or “student” attribute. You can then perform 
> permission checks etc as appropriate by looking for user.student. property> or user.teacher..
>
> As a side effect, this also allows for the edge case where a student is 
> *also* a teacher - e.g., at a university, I might be studying business 
> while teaching computer science.
>
> Yours,
> Russ Magee %-)
>
> On 24 Jul 2017, at 7:09 PM, stan  
> wrote:
>
> What is the best way to create multiple user types in Django 1.11?
>
> For example, an e-learning platform will need 2 user models: Students and 
> Teachers, which have different permissions and different attributes/methods
>
> -- 
> 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/a5127741-73a1-4a34-8e4e-ab753c6aab7d%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/034f4c37-788c-4a81-8f6c-a0143397029e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Adding code when pressing one of admin's save buttons

2017-07-25 Thread Thiago Luiz Parolin
Try using 'def save(self):' on your models.
When you save a new record, this will be executed, so if you hit any
button, you are saving in anyway and the code will be executed.

Just my cents about your question.


2017-07-25 8:29 GMT-03:00 ron_w_add via Django users <
django-users@googlegroups.com>:

> I am using Django’s admin interface to create new records. A record
> includes (amongst other fields) the date and time that a photo was taken.
> These fields will be filled into the database when either the ‘Save and add
> another’, ‘Save and continue editing’ or the ‘Save’ buttons are pressed
> (i.e. these details will be read from the image file and entered into the
> database rather than the administrator doing this manually).
>
>
>
> How can I added the extra code required to add the date and time when I
> press one of these buttons? Some example code would be appreciated.
>
>
>
> Thanks
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/63559d9c-15c6-4ce1-b477-8e24b030ce0c%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/CACTnJ001etLw57wChAeEKJWVKqTVuQtcjgJoSDGAedjoEzXouQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


upgrading django 1.11 warning list

2017-07-25 Thread pablochud
Hi!
It showed me warning related to 'on_delete' as required arg for ForeignKey 
in migration files. is it safty to change migration file manually or is 
there alternative way to bypass warning?

-- 
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/9ee4a09e-f5b4-45c8-acd4-94ae961cbab6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


upgrading to Django 1.11 warning

2017-07-25 Thread pablochud
Hi, 
It showed me warning related to 'on_delete' as required arg for ForeignKey 
in migration files. Is it save to change migration file manually or is 
there alternative way to bypass this warning?

-- 
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/0f53dd78-2276-49ad-b93c-ae29297208d8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


django + GDAL - bus error

2017-07-25 Thread Grégory Bataille
Hi everyone,

I have the strangest issue and I don't know how to address it.
I'm running on a *mac*. I have *gdal 2.2.0* installed on the system.
I have a python 3.5.2 *virtualenv* (same behavior in 3.6.1)
inside I have a number of libraries, including *django 1.9.13* and the *GDAL 
bindings*.

If from this virtualenv I open a *ipython* console and try to gdal.Open a 
TIFF, *all works well*.
If I open a *django console* (django manage.py shell) in this virtualenv 
and try to perform the same operation, I get

> TIFFReadDirectory: Warning, Unknown field with tag 42112 (0xa480) 
> encountered.
> TIFFReadDirectory: Warning, Unknown field with tag 42113 (0xa481) 
> encountered.
> [1]15947 bus error  python manage.py shell

and the shell crashes

This* happens also* if I go through the *django.contrib.gis.gdal* module 
that django embarks

This *does not* seem to *happen on my production Linux* install.

I have no idea how to investigate this. I don't know what django could do 
at startup that could have this kind of adverse effect.
*Interesting note:* I get the *same error* when launching the code through 
*celery*

Any idea what I can try to do?

Thanks

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


Adding code when pressing one of admin's save buttons

2017-07-25 Thread ron_w_add via Django users
 

I am using Django’s admin interface to create new records. A record 
includes (amongst other fields) the date and time that a photo was taken. 
These fields will be filled into the database when either the ‘Save and add 
another’, ‘Save and continue editing’ or the ‘Save’ buttons are pressed 
(i.e. these details will be read from the image file and entered into the 
database rather than the administrator doing this manually). 

 

How can I added the extra code required to add the date and time when I 
press one of these buttons? Some example code would be appreciated.

 

Thanks

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


Re: It's possible to cache entire model

2017-07-25 Thread Gideon Boateng

>
> Hi Fellipe,
>
if you want to cache an entire model. You can look at this package(Django 
Cachalot  - http://django-cachalot.readthedocs.io/en/latest/ ).
 I use it in production and its been amazing. It caches the entire ORM and 
does automatic invalidation.
its very easy to use. 
you literally need two lines of code and you will be up and running.
It has support for Redis and Mem cache.

Cheers,

-- 
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/e6009f69-b7fb-46f7-9d22-c693d23522c1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Forms HorizontalRadioSelect Renderer not working.

2017-07-25 Thread Shazia Nusrat
I am using Djnago 1.11.1. I've tried template approach but perhaps I've
missed out something.

If you can provide me some workable example I will be really really
thankful.

Regards,
Shazia

On Tue, Jul 25, 2017 at 1:57 AM, ecas  wrote:

> Which version of Django are you using? From 1.11 the widgets changed to a
> template mechanism.
>
> https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#radioselect
>
> Maybe this can help:
> https://stackoverflow.com/questions/44187640/django-1-
> 11-horizontal-choice-field
>
> El dimarts, 25 juliol de 2017 9:53:13 UTC+2, Shazia Nusrat va escriure:
>
>> Hi,
>>
>> I need to select form values horizontally but couldn't get it work.
>>
>> Following is the code:
>>
>> class HorizontalRadioRenderer(forms.RadioSelect.renderer):
>>   def render(self):
>> return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
>>
>> class ResponseForm(models.ModelForm):
>> class Meta:
>> model = Response
>> fields = ('interviewer', 'interviewee', 'conditions', 'comments')
>> def __init__(self, *args, **kwargs):
>> # expects a survey object to be passed in initially
>> survey = kwargs.pop('survey')
>> self.survey = survey
>> super(ResponseForm, self).__init__(*args, **kwargs)
>> self.uuid = random_uuid = uuid.uuid4().hex
>> # add a field for each survey question, corresponding to the
>> question
>> # type as appropriate.
>> data = kwargs.get('data')
>> for q in survey.questions():
>> if q.question_type == Question.TEXT:
>> self.fields["question_%d" % q.pk] =
>> forms.CharField(label=q.text,
>> widget=forms.Textarea)
>> elif q.question_type == Question.RADIO:
>> question_choices = q.get_choices()
>> self.fields["question_%d" % q.pk] =
>> forms.ChoiceField(label=q.text,
>> widget=forms.RadioSelect(rende
>> rer=HorizontalRadioRenderer),
>> choices = question_choices)
>>
>> Error:
>>
>> class HorizontalRadioRenderer(forms.RadioSelect.renderer):
>> AttributeError: type object 'RadioSelect' has no attribute 'renderer'
>>
>> Please advise
>>
>> --
> 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/d7280ade-f0c0-4c31-813f-1747f1f3cd29%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/CAD83tOz%2BTEn1bB80vv--OTvygQNKC%3DOi_mz2vMCj9hHoMFR-Jw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: From old-school Post/Redirect/Get to modern web

2017-07-25 Thread guettli


Am Montag, 24. Juli 2017 12:58:20 UTC+2 schrieb Christian Ledermann:
>
> https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/ 
> could give you some insights 
>
>
Thank you. This brought me to this: 
https://github.com/drf-forms/drf-schema-adapter

Ember and Angular seem to be supported - nice.

thank you for sharing this link.

Regards,
  Thomas

 

> HTH 
>
> On 24 July 2017 at 11:36, guettli  
> wrote: 
> > I use Post/Redirect/Get since several years. I use simple HTML forms 
> (via 
> > ModelForm) with a plain old submit-button. 
> > 
> > Above pattern works. 
> > 
> > But I think the web of the future works different. 
> > 
> > Up to now my web application sends html to the web client. I think 
> modern 
> > web applications 
> > don't send html, they send data (in json format). 
> > 
> > I guess in the future web clients render the (json) data using a 
> > library/framework. 
> > 
> > For me this client-side rendering is completely new. I have no clue 
> where to 
> > start this adventure. 
> > 
> > I guess django-rest-framework could help on the server side 
> > 
> > Has anyone hints or practical experience? 
> > 
> > 
> > 
> > -- 
> > 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/9151365a-2497-4db4--90ea50a350eb%40googlegroups.com.
>  
>
> > For more options, visit https://groups.google.com/d/optout. 
>
>
>
> -- 
> Best Regards, 
>
> Christian Ledermann 
>
> Newark-on-Trent - UK 
> Mobile : +44 7474997517 
>
> https://uk.linkedin.com/in/christianledermann 
> https://github.com/cleder/ 
>
>
> <*)))>{ 
>
> If you save the living environment, the biodiversity that we have left, 
> you will also automatically save the physical environment, too. But If 
> you only save the physical environment, you will ultimately lose both. 
>
> 1) Don’t drive species to extinction 
>
> 2) Don’t destroy a habitat that species rely on. 
>
> 3) Don’t change the climate in ways that will result in the above. 
>
> }<(((*> 
>

-- 
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/8cc0ec5a-6bc8-4a28-a25c-4e65274d0ff3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How can I auto-fill a field in the model without showing a form field to the user?

2017-07-25 Thread ecas
One way could be to overload the save method of the model. Maybe something 
like this in your models.py:

import datetime

class Invoice(models.Model):

def save(self, *args, **kwargs):
if not self.id:
today = datetime.date.today()
date_str = datetime.datetime.strftime(today, '%y%m%d')
last_invoice = 
Invoice.objects.filter(invoice_number__startswith=date_str).order_by('invoice_number').last()
if last_invoice:
last_invoice_num = last_invoice.invoice_number[-2:]
new_invoice_num = int(last_invoice_num) + 1
new_invoice_num = "%02d" % new_invoice_num
else:
new_invoice_num = '01'
self.invoice_number = date_str + new_invoice_num
super(Invoice, self).save(*args, **kwargs)


El dimarts, 25 juliol de 2017 6:23:44 UTC+2, Alexander Joseph va escriure:
>
> I'm new to django, but coming from php I think its the greatest thing ever.
>
> I have a model for Invoices ...
>
> {{{
> from django.conf import settings
> from django.db import models
> from django.core.urlresolvers import reverse
> #from django.contrib.auth.models import User
>
> # Create your models here.
> class Invoice(models.Model):
> created_at = models.DateTimeField(auto_now_add=True)
> their_company = models.CharField(max_length=255)
> invoice_number = models.CharField(max_length=50, default='')
> bill_to = models.CharField(max_length=255, default='')
> created_by = models.ForeignKey(settings.AUTH_USER_MODEL)
> 
> class Meta:
> ordering = ['invoice_number', ]
> 
> def __str__(self):
> return self.invoice_number
> 
> def get_absolute_url(self):
> return reverse("accounting:invoices:detail", kwargs={"pk": self.pk
> })
> }}}
>
> right now the user has to put in the invoice number themselves. I want to 
> not give the user that option though - I'd like to autofill that field in 
> the database with a concatenation of the 2 digit year (17) plus 2 digit 
> month (07) plus 2 digit day (24) and then a 2 digit auto increment for 
> every invoice created on that specific date so the first invoice created 
> today would be 17072401 and the second would be 17072402, etc. I'm guessing 
> I need a field just for the date and another for the iteration of each 
> invoice.
>
> Can anyone give me some direction on this? First I'm not sure how to 
> autofill a field in the database without getting the input from the user, 
> and I'm also not sure how I would do the concatenation with the right 
> numbers. Thanks for your help
>

-- 
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/2628139c-e93e-474d-8d8e-d71c88e4d99c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelForm validation of foreign keys - extra database queries and performance bottleneck

2017-07-25 Thread johan de taeye

I've already tried the select_related in my queryset. No change at all.  

>>Also keep in mind that Django (or any other framework) has no idea 
whether or not fields have "changed" in a form submission without pulling 
the original set of values to compare against, so expect the object to be 
pulled at least once on every request. 

The first query already retrieves the primary key of the original object, 
or the complete object if selected_related is added.  Using select_related 
can keep things to a single query, and we should be good - it's the number 
of db queries that is executed which is drastically reducing the 
performance.


I believe I'll need a custom version of the ModelChoiceField class.


Op dinsdag 25 juli 2017 10:48:41 UTC+2 schreef James Schneider:
>
>
>
> On Jul 24, 2017 4:09 AM, "johan de taeye"  > wrote:
>
>
> I have a model that has a foreign key relation to a number of other 
> objects.
> When saving an instance of this model from the admin (or a ModelForm), I 
> see plenty of extra and redundant database calls. 
> For a single record it wouldn't make much of a difference, but when using 
> the same ModeForm to do some batch upload these become the bottleneck in 
> the process.
>
> Has anyone bumped into the same performance bottleneck? 
> Has anyone developed some solution for this?
>
> By logging all database queries and some digging in the code, here's my 
> analysis of what is happening:
>
>1. Open the admin editing screen for a single record.  
>I leave all fields to the original value, except for a field (not one 
>of the foreign key fields)
>2. When saving the record, the first query reads the existing record:
>  select field1, field2, field3,  from mytable;
>3. During the form/model validation, I get an extra database query for 
>each of the foreign key fields.
>It is generated from the to_python method 
>of django.forms.models.ModelChoiceField:
>  select field_a, field_b, field_c, field, ... from related_table 
>where pk = 'id_from_first_query';
>4. During the form/model validation, I get another database query for 
>each of the foreign key fields.
>It verifies that the values actually exists in the database:
> select (1) from related_table where pk = 'value from form'; 
>
> The queries in step 3 and 4 are redundant if the field hasn't changed. The 
> first query gives enough data to allow us to verify that the new form value 
> and the foreign key field on the existing instance are equal. I am using 
> django 1.11.
>
> The same queries, except 2, are executed when I create a new record. The 
> queries in step 4 are redundant then - we just retrieved the values from 
> the database.
>
> Looking forward to any insights and hints...
>
>
> You should look at modifying the query set that your view is using to pull 
> the main object to include select_related() calls. I don't know if you're 
> using function -based views or class-based views,  so I can't comment 
> further on implementation. 
>
> https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related
>
> The extra calls are likely occurring when the related fields are being 
> accessed during validation, etc. 
>
> Also keep in mind that Django (or any other framework) has no idea whether 
> or not fields have "changed" in a form submission without pulling the 
> original set of values to compare against, so expect the object to be 
> pulled at least once on every request. 
>
> -James 
>

-- 
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/5cc0b017-2759-4026-ab6e-41f5a6cb3dd3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django Forms HorizontalRadioSelect Renderer not working.

2017-07-25 Thread ecas
Which version of Django are you using? From 1.11 the widgets changed to a 
template mechanism.

https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#radioselect

Maybe this can help:
https://stackoverflow.com/questions/44187640/django-1-11-horizontal-choice-field

El dimarts, 25 juliol de 2017 9:53:13 UTC+2, Shazia Nusrat va escriure:
>
> Hi,
>
> I need to select form values horizontally but couldn't get it work.
>
> Following is the code:
>
> class HorizontalRadioRenderer(forms.RadioSelect.renderer):
>   def render(self):
> return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))
>
> class ResponseForm(models.ModelForm):
> class Meta:
> model = Response
> fields = ('interviewer', 'interviewee', 'conditions', 'comments')
> def __init__(self, *args, **kwargs):
> # expects a survey object to be passed in initially
> survey = kwargs.pop('survey')
> self.survey = survey
> super(ResponseForm, self).__init__(*args, **kwargs)
> self.uuid = random_uuid = uuid.uuid4().hex
> # add a field for each survey question, corresponding to the 
> question
> # type as appropriate.
> data = kwargs.get('data')
> for q in survey.questions():
> if q.question_type == Question.TEXT:
> self.fields["question_%d" % q.pk] = 
> forms.CharField(label=q.text,
> widget=forms.Textarea)
> elif q.question_type == Question.RADIO:
> question_choices = q.get_choices()
> self.fields["question_%d" % q.pk] = 
> forms.ChoiceField(label=q.text,
> 
> widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
> choices = question_choices)
>
> Error:
>
> class HorizontalRadioRenderer(forms.RadioSelect.renderer):
> AttributeError: type object 'RadioSelect' has no attribute 'renderer'
>
> Please advise
>
>

-- 
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/d7280ade-f0c0-4c31-813f-1747f1f3cd29%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelForm validation of foreign keys - extra database queries and performance bottleneck

2017-07-25 Thread James Schneider
On Jul 24, 2017 4:09 AM, "johan de taeye"  wrote:


I have a model that has a foreign key relation to a number of other objects.
When saving an instance of this model from the admin (or a ModelForm), I
see plenty of extra and redundant database calls.
For a single record it wouldn't make much of a difference, but when using
the same ModeForm to do some batch upload these become the bottleneck in
the process.

Has anyone bumped into the same performance bottleneck?
Has anyone developed some solution for this?

By logging all database queries and some digging in the code, here's my
analysis of what is happening:

   1. Open the admin editing screen for a single record.
   I leave all fields to the original value, except for a field (not one of
   the foreign key fields)
   2. When saving the record, the first query reads the existing record:
 select field1, field2, field3,  from mytable;
   3. During the form/model validation, I get an extra database query for
   each of the foreign key fields.
   It is generated from the to_python method of django.forms.models.
   ModelChoiceField:
 select field_a, field_b, field_c, field, ... from related_table
   where pk = 'id_from_first_query';
   4. During the form/model validation, I get another database query for
   each of the foreign key fields.
   It verifies that the values actually exists in the database:
select (1) from related_table where pk = 'value from form';

The queries in step 3 and 4 are redundant if the field hasn't changed. The
first query gives enough data to allow us to verify that the new form value
and the foreign key field on the existing instance are equal. I am using
django 1.11.

The same queries, except 2, are executed when I create a new record. The
queries in step 4 are redundant then - we just retrieved the values from
the database.

Looking forward to any insights and hints...


You should look at modifying the query set that your view is using to pull
the main object to include select_related() calls. I don't know if you're
using function -based views or class-based views,  so I can't comment
further on implementation.

https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-related

The extra calls are likely occurring when the related fields are being
accessed during validation, etc.

Also keep in mind that Django (or any other framework) has no idea whether
or not fields have "changed" in a form submission without pulling the
original set of values to compare against, so expect the object to be
pulled at least once on every request.

-James

-- 
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/CA%2Be%2BciUjjFKSCa-Sdi6yBd-sdLoaPCFmvs-XWCDKYsorKskUAQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: The best way to use AMP of google with Django

2017-07-25 Thread James Schneider
On Jul 24, 2017 10:54 AM, "carlos"  wrote:

Hi, i have blogs with Django i need use AMP (https://www.ampproject.org/)


After a quick look at the link, it doesn't appear as though that service
will support Django. It in itself is a development framework geared towards
fast mobile applications, with its own template syntax, and hooks in to
several other layers like Google caching. However,  it appears to be a
closed system and I don't see where Django would fit.

Django provides control over the back end application process and performs
advanced application logic for the end user in Python,  and is probably
more powerful than what can be [easily] accomplished through their
software.

Django is designed to run as the primary underlying framework, but it
doesn't provide the custom JS libraries,  etc.  because it expects you as
the developer to use whatever HTML or JS library you are comfortable with.

What is the best way to use it with django, someone has an example
To apply with django or idea, book, tutorial etc. i read, see this projects
https://github.com/shtalinberg/django-amp-tools


I don't think this project is related to the AMP service above other than
an overlap in nomenclature. It also looks to be somewhat unfinished. Open
an issue directly with them,  I don't know how much help this general
mailing list will be.

TL;DR; They aren't compatible because both tools have different goals and
implementation strategies,  although Django is technically capable of doing
anything the AMP service is,  but not the other way around.

I'd recommend that you don't focus on the new age terminology, rather
develop your project requirements and then look for a framework or software
service that fits those requirements. Starting with a buzzword and trying
to crow bar in a somewhat unrelated technology will likely not end well.

-James

-- 
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/CA%2Be%2BciVBB1Ko5fa8yFDp3O_%2B5hYO6jy8%3D2CDtZXxpG-aQhiTYA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Django Forms HorizontalRadioSelect Renderer not working.

2017-07-25 Thread Shazia Nusrat
Hi,

I need to select form values horizontally but couldn't get it work.

Following is the code:

class HorizontalRadioRenderer(forms.RadioSelect.renderer):
  def render(self):
return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))

class ResponseForm(models.ModelForm):
class Meta:
model = Response
fields = ('interviewer', 'interviewee', 'conditions', 'comments')
def __init__(self, *args, **kwargs):
# expects a survey object to be passed in initially
survey = kwargs.pop('survey')
self.survey = survey
super(ResponseForm, self).__init__(*args, **kwargs)
self.uuid = random_uuid = uuid.uuid4().hex
# add a field for each survey question, corresponding to the
question
# type as appropriate.
data = kwargs.get('data')
for q in survey.questions():
if q.question_type == Question.TEXT:
self.fields["question_%d" % q.pk] =
forms.CharField(label=q.text,
widget=forms.Textarea)
elif q.question_type == Question.RADIO:
question_choices = q.get_choices()
self.fields["question_%d" % q.pk] =
forms.ChoiceField(label=q.text,

widget=forms.RadioSelect(renderer=HorizontalRadioRenderer),
choices = question_choices)

Error:

class HorizontalRadioRenderer(forms.RadioSelect.renderer):
AttributeError: type object 'RadioSelect' has no attribute 'renderer'

Please advise

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