Re: Making an object unsaveable ...

2018-03-07 Thread Bernd Wechner
James,

Thanks, that's really well put. 

I've implemented an override, and better still I love that with a model mix 
in I can override the save method on the object. Sort of like:

class MyMixIn:
def check_stuff(self)
 ...
 if ...:
  self.save = self.disabled_save

def disabled_save(self):
raise Exception("Can't save me!")

class MyModel(MyMixIn, models.Model):
   ...

Now yes, your insight that this can be circumvented is interesting, and it 
might (though I wonder how in this version, perhaps by calling 
models.Model.save(obj)?) but am content with a solution for now that 
prevents inadvertent saving not malicious saving efforts. What this allows 
is that the extant body of code can tested and run and even put into 
production in a sense, trusting that any overlooked save avenues will throw 
this exception. Which is awesome.  

Bot 100% secure perhaps, but pretty danged good. I've tested this sort of 
thing now and walked the code in a debugger and am pretty happy with it. As 
long as there are not other ways the django core code might go and save an 
object (i.e. not using a models save() method. I sort of imagine and hope 
not that one of the deign paradigms was in fact to make something like this 
possible, to override base model methods with confidence (typically 
invoking super() to extend on existing functions but perhaps not as in 
here). 

Anyhow, rather pleased this works. Opens up a pile of interesting options 
(the main interest I have is in loading an object, modifying an object for 
display purposes and sandbox purposes, but securing against an inadvertent 
save of the object).

Regards,

Bernd.

On Tuesday, 6 March 2018 19:28:58 UTC+11, James Bennett wrote:
>
> 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...@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/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/06fd9834-aafc-4167-901f-5112cb3ca566%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Making an object unsaveable ...

2018-03-07 Thread Bernd Wechner
Melvyn,

Just preference. Nothing more. Fix the issue at its source so all views 
that exist or might exist honor the demand basically. One model, many 
views. 

Regards,

Bernd.

On Tuesday, 6 March 2018 19:13:42 UTC+11, 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/a5fc94e3-a2ae-4433-9880-9309843d6145%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


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

2018-03-07 Thread furzihurzischleim
hmm.. i don't think so. the info about the jobs is meant to be gathered 
before creating the invoice. see, the app should let you register "jobs" 
with timing, client and wage information. after creating jobs you can 
select in a form "open" jobs, meaning they have not been part of an 
invoice. so you select the jobs and create the invoice, if saving the 
invoice is succesful, i create the ForeignKey relation from each job to 
point to the invoice.

... so the CreateView _is_ the right thing, right? or would you create the 
object "by hand" while processing the POST data and redirect it to an 
UpdateForm (and delete the instance if updating fails)?


Am Mittwoch, 7. März 2018 19:18:03 UTC+1 schrieb Matthew Pava:
>
> Correct, post is for POST, get is for GET.
>
> When a form is POSTed successfully, the user is redirected to another URL, 
> typically a success page or something of your choosing.
>
> So after your POST, if you are simply redirecting back to this CreateView, 
> you no longer have access to the invoice that you just created in this 
> view.  You are creating a completely new invoice using the GET method.
>
> Maybe you mean to be creating an UpdateView with this new information 
> about self.jobs?
>
>  
>
> *From:* django...@googlegroups.com  [mailto:
> django...@googlegroups.com ] *On Behalf Of *furzihurzischleim
> *Sent:* Wednesday, March 7, 2018 12:10 PM
> *To:* Django users
> *Subject:* Re: unable to render initial data in ModelForm called through 
> CreateView
>
>  
>
> thanks for the link, i was aware of that but was unable to find my error 
> (that's why i turned to irc, and then to the list)..
>
> it is true self.jobs is set from the post() method. that's because the 
> CreateView should be called if there are jobs selected in a POST-form. so 
> post() sets self.jobs which get processed (and summed to 
> initial['amount'] and initial['currency']) in get_initial(), which itself 
> is printed to console correctly. it then instantiated a form, which gets 
> the right arguments (initial dict) with the right values. but they won't 
> show up :(
>
> just for clarification: post() gets called if the request uses 
> POST-method, and get() gets called on GET-requests, right?
>
> i know this is more of a beginner issue, but i'm unable to get further in 
> my work at this point. thanks for your time and your advice!
>
>
> Am Mittwoch, 7. März 2018 18:44:40 UTC+1 schrieb Matthew Pava:
>
> Well, I see that you only set self.jobs in the post method in 
> CreateInvoice.  How are you seeing proper console output for get_initial 
> when self.jobs is not even set in the get method?  Are you sure you are 
> seeing exactly what you want to see?  Please double-check.  When presenting 
> the form for the first time, it will use the get method on CreateInvoice.  
> Since you did not override it, it will use the default implementation.  You 
> didn’t set self.jobs anywhere else but in the post method.
>
>  
>
> I also find this website helpful when dealing with class-based views:
>
>
> https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/
>
>  
>
>  
>
> *From:* django...@googlegroups.com [mailto:django...@googlegroups.com] *On 
> Behalf Of *furzihurzischleim
> *Sent:* Wednesday, March 7, 2018 7:11 AM
> *To:* Django users
> *Subject:* Re: unable to render initial data in ModelForm called through 
> CreateView
>
>  
>
> :)
>
> Invoice Form is "just" a normal Modelform - nothing fancy added.
>
> class InvoiceForm(forms.ModelForm):
> class Meta:
> model = Invoice
> fields = '__all__'
> def __init__(self,*args,**kwargs):
> print("InvoiceForm.__init__();;;")
> #print( self)
> print( args)
> print( kwargs)
> return super(InvoiceForm, self).__init__( *args, **kwargs )
>
> Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb 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...@googlegroups.com [mailto:django...@googlegroups.com] On 
> Behalf Of Gabriel Wicki 
> Sent: Sunday, March 4, 2018 2:48 PM 
> To: django...@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', 

Borrowing functionality from Django Admin forms

2018-03-07 Thread Justin Johnson
I have a user who saw how new objects can be created using the Admin forms, 
and asked if I could reproduce some of that functionality.  I'm still new 
to Django, and even newer to building forms.  I'm wondering if there is a 
way to "borrow" elements from the Admin forms into my own forms and 
templates.  Particularly, I would like the ability to create a new related 
object by clicking the "+" sign next to that dropdown list on another form.

I have not been able to find much documentation on how the Admin forms are 
constructed for a given Django project.  I understand the basic form 
construction method, but I can't seem to find the equivalent workings in 
the Admin site.  Where is the equivalent of urls.py, where the links are 
mapped to specific Views?  Where are the equivalents of the Views, where a 
context is created and sent to the template?

I would like to get more familiar with the working code behind Django, and 
eventually contribute to the project, so feel free to get technical.

Thx.


-- 
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/92f87737-2be9-4a04-8840-2edc14452b43%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/$']

2018-03-07 Thread anyi.ll...@gmail.com
The profile already have an id. Just wanted to add to an existing profile in 
the db with generic view.

- Reply message -
From: "Andy" 
To: "Django users" 
Subject: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) 
tried: ['(?P[0-9]+)/$']
Date: Wed, Mar 7, 2018 11:08

If you actually are inside the profile create view, the profile probably does 
not have an id yet and thats why the url lookup is failing. The ID will be 
created on first save of the object.

Am Dienstag, 6. März 2018 00:11:53 UTC+1 schrieb anyi.lloyd:Am new to Django, 
please i need help here. Am trying to add a subject into a particular id using 
generic CreatView, i keeping getting errors
Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: 
['(?P[0-9]+)/$']

models.py
from django.db import models
from datetime import date
from django.core.urlresolvers import reverse
from django.shortcuts import redirect


class Profile(models.Model):
firstName = models.CharField(max_length=30)
middleName = models.CharField(max_length=30)
lastName = models.CharField(max_length=30)
dob = models.DateField(blank=True, null=True)
stud_id = models.CharField(max_length=5000)
gender = models.CharField(max_length=10)
parentsName =models.CharField(max_length=30)
address = models.CharField(max_length=250)
lga = models.CharField(max_length=250)
Religion = models.CharField(max_length=50)
email = models.EmailField(max_length=70, null=True, blank=True, unique=True)
phone = models.CharField(max_length=11, unique=True)
photo = models.FileField()
Comment = models.CharField(max_length=250)

def get_absolute_url(self):
return reverse('student:detail', kwargs={'pk': self.pk})

def __str__(self):
return self.firstName

class Course(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
subject = models.CharField(max_length=20)
score = models.CharField(max_length=20)
grade = models.CharField(max_length=20)

def get_absolute_url(self,):
return reverse('student:detail', kwargs={'pk': self.pk})

views.pyfrom django.views import generic
from django.views.generic import View
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .models import Profile, Course
from .forms import UserForm



#Index view
class IndexView(generic.ListView):
template_name = 'student/index.html'
context_object_name = 'all_profile'

def get_queryset(self):
return Profile.objects.all()

#Detail view
class DetailView(generic.DetailView):
model = Profile
template_name = 'student/detail.html'

#Add student section
class ProfileCreate(generic.CreateView):
model = Profile
fields = ['firstName', 'middleName', 'lastName', 'dob', 'gender', 
'parentsName', 'address',
'lga', 'Religion', 'email', 'phone', 'photo']

#Add Subject section
class CourseCreate(CreateView):
model = Course
fields = ['subject', 'score', 'grade']


def get_form_kwargs(self):
kwargs = super(CourseCreate, self).get_form_kwargs()
kwargs['instance'] = Course(pk=self.kwargs['pk'])
return kwargs
urls.py
urlpatterns = [
#index url
url(r'^$', views.IndexView.as_view(), name='index'),

url(r'^signup/$', views.UserFormView.as_view(), name='signup'),
#details
url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),
#profile/add
url(r'^profile/add/$', views.ProfileCreate.as_view(), name='profile-add'),
#course/add
url(r'^(?P[0-9]+)/course_form/$', views.CourseCreate.as_view(), 
name='course_form'),
#profile/pk for update
url(r'^profile/(?P[0-9]+)/$', views.ProfileUpdate.as_view(), 
name='profile-update'),
#profile/pk for deleting
url(r'^profile/(?P[0-9]+)/delete/$', views.ProfileDelete.as_view(), 
name='profile-delete'),
]

template{% extends 'student/base.html' %}
{% block title %}{% endblock %}

{% block body %}







{{profile.lastName}} {{profile.firstName}}



{% if profile.photo %}

{% else %}
No image to display
{% endif %}








View 
All
Add New Song




Add Subject


Add Subject
{% if error_message %}
{{ error_message }}
{% endif %}

{% csrf_token %}

{% include 'student/form-profile-temp.html' %}


Submit











{% endblock %}






-- 
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/By5BEzS0ZJE/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/msgid/django-users/8ecfd645-1aa7-462b-90fb-9d78d0a0fc38%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

-- 
You received this 

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

2018-03-07 Thread Matthew Pava
Correct, post is for POST, get is for GET.
When a form is POSTed successfully, the user is redirected to another URL, 
typically a success page or something of your choosing.
So after your POST, if you are simply redirecting back to this CreateView, you 
no longer have access to the invoice that you just created in this view.  You 
are creating a completely new invoice using the GET method.
Maybe you mean to be creating an UpdateView with this new information about 
self.jobs?

From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On 
Behalf Of furzihurzischleim
Sent: Wednesday, March 7, 2018 12:10 PM
To: Django users
Subject: Re: unable to render initial data in ModelForm called through 
CreateView

thanks for the link, i was aware of that but was unable to find my error 
(that's why i turned to irc, and then to the list)..

it is true self.jobs is set from the post() method. that's because the 
CreateView should be called if there are jobs selected in a POST-form. so 
post() sets self.jobs which get processed (and summed to initial['amount'] and 
initial['currency']) in get_initial(), which itself is printed to console 
correctly. it then instantiated a form, which gets the right arguments (initial 
dict) with the right values. but they won't show up :(

just for clarification: post() gets called if the request uses POST-method, and 
get() gets called on GET-requests, right?

i know this is more of a beginner issue, but i'm unable to get further in my 
work at this point. thanks for your time and your advice!


Am Mittwoch, 7. März 2018 18:44:40 UTC+1 schrieb Matthew Pava:
Well, I see that you only set self.jobs in the post method in 
CreateInvoice.  How are you seeing proper console output for get_initial when 
self.jobs is not even set in the get method?  Are you sure 
you are seeing exactly what you want to see?  Please double-check.  When 
presenting the form for the first time, it will use the get method on 
CreateInvoice.  Since you did not override it, it will use the default 
implementation.  You didn’t set self.jobs anywhere else but 
in the post method.

I also find this website helpful when dealing with class-based views:
https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/


From: django...@googlegroups.com 
[mailto:django...@googlegroups.com] On Behalf Of furzihurzischleim
Sent: Wednesday, March 7, 2018 7:11 AM
To: Django users
Subject: Re: unable to render initial data in ModelForm called through 
CreateView

:)

Invoice Form is "just" a normal Modelform - nothing fancy added.

class InvoiceForm(forms.ModelForm):
class Meta:
model = Invoice
fields = '__all__'
def __init__(self,*args,**kwargs):
print("InvoiceForm.__init__();;;")
#print( self)
print( args)
print( kwargs)
return super(InvoiceForm, self).__init__( *args, **kwargs )

Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb 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...@googlegroups.com 
[mailto:django...@googlegroups.com] On Behalf Of Gabriel Wicki
Sent: Sunday, March 4, 2018 2:48 PM
To: django...@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"), # 

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

2018-03-07 Thread Matthew Pava
Well, I see that you only set self.jobs in the post method in CreateInvoice.  
How are you seeing proper console output for get_initial when self.jobs is not 
even set in the get method?  Are you sure you are seeing exactly what you want 
to see?  Please double-check.  When presenting the form for the first time, it 
will use the get method on CreateInvoice.  Since you did not override it, it 
will use the default implementation.  You didn’t set self.jobs anywhere else 
but in the post method.

I also find this website helpful when dealing with class-based views:
https://ccbv.co.uk/projects/Django/1.11/django.views.generic.edit/CreateView/


From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On 
Behalf Of furzihurzischleim
Sent: Wednesday, March 7, 2018 7:11 AM
To: Django users
Subject: Re: unable to render initial data in ModelForm called through 
CreateView

:)

Invoice Form is "just" a normal Modelform - nothing fancy added.

class InvoiceForm(forms.ModelForm):
class Meta:
model = Invoice
fields = '__all__'
def __init__(self,*args,**kwargs):
print("InvoiceForm.__init__();;;")
#print( self)
print( args)
print( kwargs)
return super(InvoiceForm, self).__init__( *args, **kwargs )

Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb 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...@googlegroups.com 
[mailto:django...@googlegroups.com] On Behalf Of Gabriel Wicki
Sent: Sunday, March 4, 2018 2:48 PM
To: django...@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


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

2018-03-07 Thread furzihurzischleim
:)

Invoice Form is "just" a normal Modelform - nothing fancy added.

class InvoiceForm(forms.ModelForm):
class Meta:
model = Invoice
fields = '__all__'
def __init__(self,*args,**kwargs):
print("InvoiceForm.__init__();;;")
#print( self)
print( args)
print( kwargs)
return super(InvoiceForm, self).__init__( *args, **kwargs )

Am Dienstag, 6. März 2018 18:08:33 UTC+1 schrieb 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...@googlegroups.com  [mailto:
> django...@googlegroups.com ] On Behalf Of Gabriel Wicki 
> Sent: Sunday, March 4, 2018 2:48 PM 
> To: django...@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: 
>  

Re: how should i make a non downloadable image in my django website

2018-03-07 Thread Aditi Bandopadhyay
Badtameez Insaan. Namard. Agar paise dene k himmat na ho toh mere banaye 
hue videos bhi use karke youtube me upload mat karo.

On Saturday, 9 July 2016 10:23:49 UTC+5:30, deepak manupati wrote:
>
> how should i make a non downloadable image in my django website
>

-- 
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/8317f86c-40e2-471a-85f5-568f6275ff72%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Change Django admin behaviour

2018-03-07 Thread Hervé Edorh
 


I have 3 models, the idea is that i can do many test on one product and a 
product can be removed of my stock (insert values in out table) by peoples. 
In django admin how can i do for blocking to insert values in Test table 
when the product is in the out table(inserted in the out table)? Where 
could i write the function to block the adding and how making the error or 
warning message come to the admin interface telling the user that product 
is removed?

class Person (models.Model): 
name = models.Charfield (max_lenght=15) 

class Product (models.Model): 
name = models.CharField (max_lenght=15) 

outs=models.ManytoMany(Person,related_name="outs_of_product",through="Out") 

class Test(models.Model): 
testname = models.Charfield (max_lenght=15) 
product = models.ForeignKey(Product,on_delete=models.CASCADE) 

class Out (models.Model): 
date= models.DateField () 

person=models.ForeignKey(Persone,related_name="peoples_out_product",on_delete=models.CASCADE)
 


product=models.ForeignKey(Persone,related_name="products_out",on_delete=models.CASCADE)

-- 
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/a063ac99-42a4-463c-ab32-9308d9983d4d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/$']

2018-03-07 Thread Andy
If you actually are inside the profile create view, the profile probably 
does not have an id yet and thats why the url lookup is failing. The ID 
will be created on first save of the object.

Am Dienstag, 6. März 2018 00:11:53 UTC+1 schrieb anyi.lloyd:
>
> Am new to Django, please i need help here. Am trying to add a subject into 
> a particular id using generic CreatView, i keeping getting errors
> Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: 
> ['(?P[0-9]+)/$']
>
> models.py
>
> from django.db import models
> from datetime import date
> from django.core.urlresolvers import reverse
> from django.shortcuts import redirect
>
>
> class Profile(models.Model):
> firstName = models.CharField(max_length=30)
> middleName = models.CharField(max_length=30)
> lastName = models.CharField(max_length=30)
> dob = models.DateField(blank=True, null=True)
> stud_id = models.CharField(max_length=5000)
> gender = models.CharField(max_length=10)
> parentsName =models.CharField(max_length=30)
> address = models.CharField(max_length=250)
> lga = models.CharField(max_length=250)
> Religion = models.CharField(max_length=50)
> email = models.EmailField(max_length=70, null=True, blank=True, 
> unique=True)
> phone = models.CharField(max_length=11, unique=True)
> photo = models.FileField()
> Comment = models.CharField(max_length=250)
>
> def get_absolute_url(self):
> return reverse('student:detail', kwargs={'pk': self.pk})
>
> def __str__(self):
> return self.firstName
>
> class Course(models.Model):
> profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
> subject = models.CharField(max_length=20)
> score = models.CharField(max_length=20)
> grade = models.CharField(max_length=20)
>
> def get_absolute_url(self,):
> return reverse('student:detail', kwargs={'pk': self.pk})
>
> views.py
>
> from django.views import generic
> from django.views.generic import View
> from django.views.generic.edit import CreateView, UpdateView, DeleteView
> from django.core.urlresolvers import reverse_lazy, reverse
> from django.shortcuts import render, redirect
> from django.contrib.auth import authenticate, login
> from .models import Profile, Course
> from .forms import UserForm
>
>
>
> #Index view
> class IndexView(generic.ListView):
> template_name = 'student/index.html'
> context_object_name = 'all_profile'
>
> def get_queryset(self):
> return Profile.objects.all()
>
> #Detail view
> class DetailView(generic.DetailView):
> model = Profile
> template_name = 'student/detail.html'
>
> #Add student section
> class ProfileCreate(generic.CreateView):
> model = Profile
> fields = ['firstName', 'middleName', 'lastName', 'dob', 'gender', 
> 'parentsName', 'address',
>   'lga', 'Religion', 'email', 'phone', 'photo']
>
> #Add Subject section
> class CourseCreate(CreateView):
> model = Course
> fields = ['subject', 'score', 'grade']
>
>
> def get_form_kwargs(self):
> kwargs = super(CourseCreate, self).get_form_kwargs()
> kwargs['instance'] = Course(pk=self.kwargs['pk'])
> return kwargs
>
>
> urls.py
>
>
> urlpatterns = [
> #index url
> url(r'^$', views.IndexView.as_view(), name='index'),
>
> url(r'^signup/$', views.UserFormView.as_view(), name='signup'),
> #details
> url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),
> #profile/add
> url(r'^profile/add/$', views.ProfileCreate.as_view(), name='profile-add'),
> #course/add
> url(r'^(?P[0-9]+)/course_form/$', views.CourseCreate.as_view(), 
> name='course_form'),
> #profile/pk for update
> url(r'^profile/(?P[0-9]+)/$', views.ProfileUpdate.as_view(), 
> name='profile-update'),
> #profile/pk for deleting
> url(r'^profile/(?P[0-9]+)/delete/$', views.ProfileDelete.as_view(), 
> name='profile-delete'),
> ]
>
>
>
> template
>
> {% extends 'student/base.html' %}
> {% block title %}{% endblock %}
>
> {% block body %}
>
> 
> 
> 
> 
> 
> 
> {{profile.lastName}} 
> {{profile.firstName}}
> 
> 
>
> {% if profile.photo %}
>  class="img-thumbnail" width="250px" hieght="100px">
> {% else %}
> No image to display
> {% endif %}
> 
> 
> 
>
> 
>
> 
> 
> View All
> Add New Song
> 
> 
> 
> 
> Add Subject
> 
> 
>  Add Subject
> {% if error_message %}
> {{ error_message }}
> {%