RE: unable to render initial data in ModelForm called through CreateView

2018-03-06 Thread Matthew Pava
Let's see InvoiceForm.
Also, it doesn't make much of a different, but I wouldn't call copy on the 
super.get_initial() method.

 
-Original Message-
From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On 
Behalf Of Gabriel Wicki
Sent: Sunday, March 4, 2018 2:48 PM
To: django-users@googlegroups.com
Subject: unable to render initial data in ModelForm called through CreateView

hello list

i ran into some weird stuff and neither i nor 2 gentle folks down at the 
irc-chat could find any obvious problems. task should have been easy:
calculate some special initial data and present it as initials in a form. the 
form is showed correctly, and the right values are printed in console.. and, of 
course, there is no error raised..

thank you for any hints! i've been stuck here


gabriel




# models.py
class AmountModel(models.Model):
    class Meta:
    abstract = True
    currencies = (
    ('CHF', "Swiss Francs"),
    ('EUR', "Euros"),
    )
    amount = models.FloatField();
    currency = models.CharField( max_length=3, choices=currencies, 
default='CHF' )

    def __str__(self):
    return "{} {}".format(self.amount, [ j[1] for i,j in
enumerate(self.currencies) if j[0] == self.currency][0] )
    def short(self):
    return "{} {}".format([ j[0] for i,j in
enumerate(self.currencies) if j[0] == self.currency][0], self.amount )
    def __add__(self, other):
    return AmountModel(amount=self.amount+other.amount,
currency=self.currency)

class DocumentModel(models.Model):
    class Meta:
    abstract = True
    tex = models.FileField(verbose_name = "TeX")
    pdf = models.FileField(verbose_name = "PDF")
    def generate_pdf( self ):
    return

class Invoice(AmountModel, DocumentModel):
    STATUS = (
    ("o", "open"), # initialized
    ("c", "complete"), # completed (no info missing)
    ("s","sent"), # sent
    ("p","pending"), # sent but money not yet received
    ("pd","paid") # paid and archived
    )
    client = models.ForeignKey( 'Client', on_delete=models.CASCADE )
    title = models.CharField( max_length=200 )
    status = models.CharField( max_length=2, choices = STATUS )
    number = models.IntegerField( blank=True )
    date_created = models.DateField( auto_now=True )
    date_sent = models.DateField( blank=True )
    date_paid = models.DateField( blank=True )

    @property
    def jobs(self):
    return Job.objects.filter( invoice=self )

    @property
    def expenses(self):
    return Expense.objects.filter( invoice=self )

    def __str__(self):
    if self.status.startswith('p'):
    return '%d %s'.format(self.number, self.title )
    return self.title

    def update_status(self):
    if (self.date_sent == None):
    self.status = STATUS[0][0]
    elif (self.date_paid == None):
    self.status = STATUS[1][0]
    else:
    self.status = STATUS[2][0]
    return

    def calculate_amount(self):
    amount = 0
    for o in [ self.jobs, self.expenses ].flatten:
    amount += o.amount
    self.amount = amount
    self.save()
    return

    def create_tex( self ):
    template_file = 'templates/invoice.tex'
    t = loader.get_template(template_file)
    context = {
        'title': self.title,
    }
    filename = '%d %s'.format(self.number, slugify(self.title) )
    self.tex.file = open(filename+'.tex', 'w')
    self.tex.file.write(smart_str( t.render(context) ))
    return

    def send_to_client( self ):
    return

# views.py
class CreateInvoice(CreateView):
    model = Invoice
    form_class = InvoiceForm
    template_name = 'standard_form.html'

    def get_initial(self):
    initial = super(CreateView, self).get_initial().copy()
    initial['title'] = "blablabla"
    amount = {'CHF': 0, 'EUR': 0}
    currency = self.jobs[0].worth.currency
    for j in self.jobs:
    amount[j.worth.currency] += j.worth.amount
    for a in amount.keys():
    if not amount[a] == 0:
    try:
    initial['value'] is None
    except KeyError:
    initial['currency'] = a
    initial['amount'] = amount[a]
    print(initial)
    return initial

    def post(self, request, *args, **kwargs):
    print("post()")
    req = request.POST.copy()
    req.pop('csrfmiddlewaretoken')
    self.jobs = Job.objects.filter(id__in=req.keys(),
client_id=kwargs['client_id'])
    return super(CreateView, self).post(request,*args,**kwargs)

# standard_form.html
{% extends 'main_form.html' %}
{% block formaction %}{{ formaction }}{% endblock %} {% block 'title' %}{{ 
title }}{% endblock %} {% block form %} {% for field in form %} 
  {{ field.errors }}
  {{ field.label_tag }}
  {{ field }}

{% endfor %}
{% endblock %}

--
You received this message because you are subscribed t

Redirect to DetailView with success_url.

2018-03-06 Thread j . romeroc97
Hi!, I have a question and I hope you guys can help me, 

I wanna redirect to a DetailView using the success_url from my CreateView.

How is this, I have a CreateView to save a device, and I wanna do that once 
the device is saved, redirect to DetailView to show a QR Code and vinculate 
with Google Authenticator or Authy like apps.

Any advice to do this? Thanks anyway!

-- 
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/c16e199a-5d8e-485a-9e86-f5b154379118%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Clarification on Foreign Keys requested

2018-03-06 Thread Bill Freeman
When all is as usual, you don't play with pk in your code.  You put the
foreign object in the field of the referring object.  (In python that's
just a reference, so don't worry about copies, etc.)  When the referring
object is saved, django saves the pk of the object in the field in the db
in a field called foo_id, if the field itself is called foo. Later when
you fetch the referrer, say as bar, then when you refer to bar,foo django
makes sure the foo object has been fetched, so bar.foo.ugh get's you the
ugh field of the foo object referred to by bar.

I suggest that with this in mind, you go back of the part of the tutorial
example that talks about foreign keys and see how many of the things that
you're doing aren't required, and are just opportunities to confuse things.

On Mon, Mar 5, 2018 at 6:21 PM, Malik Rumi  wrote:

> I tried the to_field argument, that was a mistake, and I put it back.
>
> I was just inserting the pk of the foreign object. However, as things are
> moving through the pipeline, I used uuid.uuid4() to create additional pks
> as needed at it went along.
>
> Example:
>
> def process_item(self, item, spiders):
> itemcasebycase['case_arrow'] = item['uniqid']
> itemcasebycase['uniqid'] = get_u
>
> But this is what works in the pipeline:
>
> scotus = Jurisdiction.objects.get(
> uniqid='5e4dd0c2-5cc9-4d08-ab43-fcf0e84dfc44')
> item['jurisdiction'] = scotus
>
> And this is the error message I got:
>
> ValueError: Cannot assign "UUID('5e4dd0c2-5cc9-4d08-ab43-fcf0e84dfc44')":
> "Case.jurisdiction" must be a "Jurisdiction" instance
>
> Finally, yes, under normal circumstances, my pk uuids are made
> automatically. Thanks
>
> *“None of you has faith until he loves for his brother or his neighbor
> what he loves for himself.”*
>
> On Mon, Mar 5, 2018 at 2:16 PM, Bill Freeman  wrote:
>
>> Are you specifying the to_field argument, or are you letting it default?
>>
>> And is the pk of the other model made by Django by default, or are you
>> explicitly specifying a foreign key constraint on some field of your own.
>>
>> Things might be better in 2.0, but I've had my troubles with pk that
>> isn't an AutoField (such as made by default).
>>
>> If you're only doing the standard (defaulted) stuff, it's a mystery.
>> Either way folks probably need to see some of your code to help out.
>>
>> On Mon, Mar 5, 2018 at 5:06 PM, Malik Rumi 
>> wrote:
>>
>>> Hello all,
>>>
>>> Up to now, (admittedly not long - I'm not a total newbie but I still
>>> have a LOT to learn) when making a foreign key I would just put the pk of
>>> that instance in the fk field, as the docs suggest:
>>>
>>> By default ForeignKey will target the pk of the remote model but this 
>>> behavior
>>> can be changed by using the ``to_field`` argument.
>>>
>>> *https://docs.djangoproject.com/en/2.0/_modules/django/db/models/fields/related/#ForeignKey
>>> 
>>> *
>>>
>>> However, recently while working with a scrapy pipeline, these fields
>>> started catching errors, which told me
>>>
>>> "...must be an instance of ...(foreign object)"
>>>
>>> And sure enough, if I did a get queryset for the one specific instance
>>> in question, that worked. My question is why, or maybe it should be, what's
>>> the difference, or maybe even, what's going on here, or wtf?
>>>
>>> Any light you can shed on this for me would, as always, be greatly
>>> appreciated.
>>>
>>> --
>>> 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/ms
>>> gid/django-users/5f9399d4-6a48-450a-b2bd-2e33a296b1b5%40googlegroups.com
>>> 
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>
>> --
>> 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/to
>> pic/django-users/GDuwEZXyQ3k/unsubscribe.
>> To unsubscribe from this group and all its topics, 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/ms
>> gid/django-users/CAB%2BAj0vGREMexQPAg8tpAaMP_3iL8QNPCk9WbQFZ
>> SZ9hrsksHw%40mail.gmail.com
>> 

Django security releases issued: 2.0.3, 1.11.11, and 1.8.19

2018-03-06 Thread Tim Graham
Today the Django team issued Django 2.0.3, 1.11.11, and 1.8.19 as part
of our security process. These releases address two security issues,
and we encourage all users to upgrade as soon as possible:

https://www.djangoproject.com/weblog/2018/mar/06/security-releases/

As a reminder, we ask that potential security issues be reported via
private email to secur...@djangoproject.com and not via Django's Trac
instance or the django-developers list. Please see
https://www.djangoproject.com/security for further information.

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


Re: Making an object unsaveable ...

2018-03-06 Thread James Bennett
The only way to guarantee a model is unsaveable is to do it at the database
permission level.

You can override methods on the model in your Python code to make it
*harder* to save, but you can't make it impossible, because of how Python
works.

Consider the following simplified pair of classes:


class Base:
def __init__(self, name):
self.name = name

def save(self):
print("Saving {}".format(self.name))


class Child(Base):
def save(self):
raise Exception("Can't save me!")


You'd think you can't save() an instance of Child. Except:


c = Child(name="Unsaveable instance")
Base.save(c)


Which will succeed and print that it's saving the "unsaveable" instance of
Child. Now imagine that you override save() and everything else you can
think of on your model class, and then someone goes and grabs the base
Model class and calls its save() method passing in an instance of your
"unsaveable" class. It's going to succeed in saving your "unsaveable" model.

No matter how much you do to your model class in Python, someone who's
sufficiently determined will always be able to find a way to save it. Only
by cutting off the ability to run INSERT/UPDATE queries at the
database-permission level can you completely stop this.



On Tue, Mar 6, 2018 at 12:12 AM, Melvyn Sopacua 
wrote:

> Hi Bernd,
>
> On zondag 4 maart 2018 10:41:52 CET Bernd Wechner wrote:
>
> > Here is the use case:
> >
> >  1. Load an object from database
> >  2. Flag it as unsaveable, not to be written back to database under any
> > circumstances
> >  3. Make changes to the object (its fields)
> >  4. Present a detail view of the object.
>
> Since this is for display purposes, why does it have to remain a model?
> --
> Melvyn Sopacua
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit https://groups.google.com/d/
> msgid/django-users/2367426.DusgZ0bLcz%40fritzbook.
> 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/CAL13Cg9GrypCNg97rE2PKUHWdHVqcKWYHjo1YcJTfpPfsq1v1A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Making an object unsaveable ...

2018-03-06 Thread Melvyn Sopacua
Hi Bernd,

On zondag 4 maart 2018 10:41:52 CET Bernd Wechner wrote:

> Here is the use case:
> 
>  1. Load an object from database
>  2. Flag it as unsaveable, not to be written back to database under any
> circumstances
>  3. Make changes to the object (its fields)
>  4. Present a detail view of the object.

Since this is for display purposes, why does it have to remain a model?
-- 
Melvyn Sopacua

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