how to saven models dynamically inputted by user in form

35 views
Skip to first unread message

Aashita Dutta

unread,
Jul 1, 2014, 7:32:04 AM7/1/14
to django...@googlegroups.com
this is my code-
def final(request, name):
    if request.method == 'POST':
        form = ConfirmForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            quote_item = request.POST['quote_item']
            quote_qty = request.POST['quote_qty']
            #obj = PurchasedItem.objects.create(item__name=quote_item, qty=quote_qty,price=quote_price)
            obj = PurchasedItem(item__name=quote_item__name, qty=quote_qty)
            obj.save()
            purchase_order = PurchaseOrder.objects.get(pk=name)
            item = PurchasedItem.objects.filter(purchase_order_id=name).values_list('item__name', 'qty', 'price')
            total_cost = PurchasedItem.objects.filter(purchase_order_id=name).aggregate(Sum('price')).get('price__sum', 0.00)
            return render(request, 'bills/bills.html', {'purchase_order' : purchase_order,
                 'item' : item, 'total_cost' : total_cost, 'form':form })
     
    else:
        form = ConfirmForm()
    return render(request,'bills/bills.html')



in this code obj.save() method is not working . Kindly help.

Lachlan Musicman

unread,
Jul 1, 2014, 8:28:59 AM7/1/14
to django...@googlegroups.com
Hi Aashita,

There's a couple of things happening here. I'm no expert and this is a
rushed end of evening email.

For getting the obj.save() to work, here:

cd = form.cleaned_data
newPI = PurchasedItem()
newPI.name = cd['quote_item']
newPI.qty = cd['quote_qty']
newPI.save()

You now have a new PurchaseItem with a name and a qty.

Having said that, is there a reason you aren't using ModelForms and
Generic Views?

Then there's the PurchaseOrder. Will there be other PuchaseItems on
the order? Is it ManyToMany?

If it is, it might be better to have the PurchaseOrder Form, with
PurchaseItem as an attached ModelFormset - in that way you can have as
many PIs on you PO as you want.

The easiest way to get the sum price on a PO then, are a small fn on
the PO model:

def total(self):
total_cost = 0
for pi in self.pi_set.all():
total_cost += pi.price
return total_price

or something like that. Using aggregates is a good idea, but I'm not
fully across the syntax.

Then your last render can look like:

return render(request, 'bills/bills.html', {'purchase_order' : purchase_order})

You can call {{ purchase_order.total }} in the template, and there is
no need to pass the form at that point?



Good luck

Cheers
L.
> --
> 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 http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/c2c02b8c-0b14-4072-a97c-a4e452504afb%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--
The idea is that a beautiful image is frameable. Everything you need
to see is there: It’s everything you want, and it’s very pleasing
because there’s no extra information that you don’t get to see.
Everything’s in a nice package for you. But sublime art is
unframeable: It’s an image or idea that implies that there’s a bigger
image or idea that you can’t see: You’re only getting to look at a
fraction of it, and in that way it’s both beautiful and scary, because
it’s reminding you that there’s more that you don’t have access to.
It’s now sort of left the piece itself and it’s become your own
invention, so it’s personal as well as being scary as well as being
beautiful, which is what I really like about art like that.
-----------------------------------------------------------------------------------------------------------
Adventure Time http://theholenearthecenteroftheworld.com/

Aashita Dutta

unread,
Jul 1, 2014, 4:00:52 PM7/1/14
to django...@googlegroups.com


PurchaseOrder has no use here, and yes item is foreign key to Product class which consists of item's name i.e item__name. Actually my QuotedItem class in models consist of 5 fields, and i want to save only two. Would this method be work? And also can we save method item__name which is foreign key?
reply soon

Aashita Dutta

unread,
Jul 1, 2014, 4:10:35 PM7/1/14
to django...@googlegroups.com


On Tuesday, July 1, 2014 5:58:59 PM UTC+5:30, Lachlan Musicman wrote:
Hi Aashita,

There's a couple of things happening here. I'm no expert and this is a
rushed end of evening email.

For getting the obj.save() to work, here:

            cd = form.cleaned_data
            newPI = PurchasedItem()
            newPI.name = cd['quote_item']
            newPI.qty = cd['quote_qty']
            newPI.save()

You now have a new PurchaseItem with a name and a qty.
Now error is coming ,
EOL while scanning string literal (views.py, line 31)
 


Aashita Dutta

unread,
Jul 1, 2014, 4:16:17 PM7/1/14
to django...@googlegroups.com


On Tuesday, July 1, 2014 5:58:59 PM UTC+5:30, Lachlan Musicman wrote:
Hi Aashita,

There's a couple of things happening here. I'm no expert and this is a
rushed end of evening email.

For getting the obj.save() to work, here:

            cd = form.cleaned_data
            newPI = PurchasedItem()
            newPI.name = cd['quote_item']
            newPI.qty = cd['quote_qty']
            newPI.save()

You now have a new PurchaseItem with a name and a qty.

Having said that, is there a reason you aren't using ModelForms and
Generic Views?

Then there's the PurchaseOrder.  Will there be other PuchaseItems on
the order? Is it ManyToMany?

If it is, it might be better to have the PurchaseOrder Form, with
PurchaseItem as an attached ModelFormset - in that way you can have as
many PIs on you PO as you want.



now new error is coming-
The view librehatti.bills.views.final didn't return an HttpResponse object. It returned None instea

Lachlan Musicman

unread,
Jul 1, 2014, 8:01:55 PM7/1/14
to django...@googlegroups.com
Woah there.

Ok, well it's hard to help without more info, but here are some tips:

- please don't ask a community project to "reply soon". We will reply
when and if we can. Obviously ideally we would reply, and speedily,
but we get what we got.

- How to save the ForeignKey on an item? Well assign it. FYI, it's
incredibly difficult to help without some code to look at. HAving said
that, the Django documentation is *excellent* and you should utilise
it - like I said in my original emails, ModelFormsets are your friend,
you should look into them.

- With errors, sending them raw is not a way to get them solved. They
way I solve errors like that is to Google the error, and then look at
the line of code indicated:
"EOL while scanning string literal (views.py, line 31)" <- views, line
31. Maybe line 30, probably line 31. If Google doesn't help, and you
do need to ask here (which may well be the case), you MUST include
line 31 (pref the lines 25-35) so we have an idea of what is going on.

- The error "The view librehatti.bills.views.final didn't return an
HttpResponse object. It returned None instea" means your return
statement in the view final isn't sending a proper object back -
either change the return statement, or figure out why it's sending
None. Again, without any context at all, it's very hard to help you.



cheers
L.
> --
> 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 http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/aa9f7896-e19a-46f5-ae5f-830a0484106e%40googlegroups.com.

Aashita Dutta

unread,
Jul 2, 2014, 1:33:58 AM7/2/14
to django...@googlegroups.com


here is my model-
from django.db import models
import useraccounts
from librehatti.catalog.models import *
from django.contrib.auth.models import User

class QuotedOrder(models.Model):
    quote_buyer_id = models.ForeignKey(User)
    quote_is_debit = models.BooleanField()
    quote_delivery_address = models.ForeignKey('useraccounts.Address')
    quote_organisation = models.ForeignKey('useraccounts.AdminOrganisations')
    quote_date_time = models.DateTimeField(auto_now_add=True)
    def __unicode__(self):
        return '%s' % (self.quote_buyer_id) +' - ' '%s' % (self.quote_date_time.strftime ('%b %d, %Y'))

class QuotedItem(models.Model):
    quote_order = models.ForeignKey(PurchaseOrder)
    quote_price = models.IntegerField()
    quote_qty = models.IntegerField()
    quote_discount= models.IntegerField()
    quote_item = models.ForeignKey(Product)
    status = models.IntegerField(default=0)
    def save(self):
        if not self.id:
            self.quote_price = self.quote_item.price * self.quote_qty
        super(QuotedItem,self).save()

    def __unicode__(self):
        return '%s' % (self.quote_item) + ' - ' '%s' % (self.quote_order)


   
   
here is my forms.py-
from django import forms
from librehatti.bills.models import *

#class ConfirmForm(forms.Form):
    #quote_item = forms.CharField()
    #quote_qty = forms.IntegerField()


class ConfirmForm(ModelForm):
     class Meta:
         model = QuotedItem
         fields = ('quote_item', 'quote_qty')


here is my html-file-
<html>
<head>
    <title>display items</title>
</head>
<body>

    <h1>CONFIRM ITEMS</h1>
    <form action="/bills/confirm/final/{{quoted_order.quote_buyer_id.username}}/" method="POST"> {% csrf_token %}
    <table>
    <tr>
    <th>Item</th>
    <th>Quantity</th>
    </tr>

     {% for i in quoted_item %}
     
    <tr>
        
    <td>Item:<input type="text" name = "quote_item" value="{{i.quote_item.name}}"></td> 
    <td>Quantity:<input type="text" name="quote_qty" value="{{i.quote_qty}}"></td>
      
  
    </tr>
     
   {% endfor %}
   </table

    
   
    <a href="/bills/confirm/final/{{quoted_order.quote_buyer_id.username}}">
    <input type="submit" value="Submit" name="submit"/> </a>
    </form>
</body>
</html>



here is catalog models, where i want to save the values, input by user in form-

from django.db import models
from django.forms import ModelForm
import useraccounts
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('self', blank=True, null=True)
    def __unicode__(self):
        return unicode(self.name)


class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category)
    price = models.IntegerField()
    organisation = models.ForeignKey('useraccounts.AdminOrganisations')
    def __unicode__(self):
        return self.name


class Attributes(models.Model):
    name = models.CharField(max_length=200)
    is_number = models.BooleanField()
    is_string = models.BooleanField()
    def __unicode__(self):
        return self.name


class PurchaseOrder(models.Model):
    buyer_id = models.ForeignKey(User)
    is_debit = models.BooleanField()
    delivery_address = models.ForeignKey('useraccounts.Address')
    organisation = models.ForeignKey('useraccounts.AdminOrganisations')
    date_time = models.DateTimeField(auto_now_add=True)
    def __unicode__(self):
        return '%s' % (self.buyer_id) +' - ' '%s' % (self.date_time.strftime
               ('%b %d, %Y'))


class PurchasedItem(models.Model):
    purchase_order = models.ForeignKey(PurchaseOrder)
    price = models.IntegerField()
    qty = models.IntegerField()
    discount= models.IntegerField()
    item = models.ForeignKey(Product)
   
    def save(self):
        if not self.id:
            self.price = self.item.price * self.qty
        super(PurchasedItem,self).save()

    def __unicode__(self):
        return '%s' % (self.item) + ' - ' '%s' % (self.purchase_order)


class Catalog(models.Model):
    attribute = models.ForeignKey(Attributes)
    value = models.CharField(max_length=200)
    product = models.ForeignKey(Product)
    def __unicode__(self):
        return self.attribute.name;


how to save now? and to generate bills also?

here is bill.html-


<!DOCTYPE html>
<html lang="en">

<head>
   
<meta charset='UTF-8'>

    <link rel="stylesheet" type="text/css" href="style.css" />

    <title>bill</title>
     
</head>

<body>

<div style="text-align:center">
    
<h1>{{quoted_order.quote_organisation.organisation_type}}</h1>
<p>{{quoted_order.quote_organisation.tagline}}</p>      
<h1 style="font-sixe:14px">{{quoted_order.quote_organisation.title}}
</h1> 
<p>{{quoted_order.quote_organisation.address}}</p>
<p><i>Website :</i> {{quoted_order.quoted_organisation.quote_url}}
 <i>Email:</i>{{quoted_order.quoted_organisation.quote_email1}}  <i>Ph :</i>
{{quoted_order.quote_organisation.telephone}}
 <i>Fax :</i> {{quoted_order.quote_organisation.fax}}</p>
<br><br> 
<h2 style="text-align:center;font-size:175%;"> Bill</h2>

</div>
<div style="font-size:100%;">
<p>STC No. {{ STC_NO }}</P>
<p>PAN No. {{ PAN_No. }}
</div>

<div style="position:absolute;top:290px;left:35px;">
No. : GNDEC/TCC/B/{{ job_no }}</div>
<div style="position:absolute;top:290px;right:0px;">
Dated : {{quoted_order.date_time}} </div>
<br>
<br>
<br>

</br> To,
</br> {{quote_delivery_address}}
</br> Organisation:{{quote_organisation}}
</br> Buyer Id : {{ purchased_order.buyer_id.username }}
</br> Ref: Your Letter No.{{L_No.}},
dated:{{quoted_order.date_time}} , respectively.
 
</br>
</br>
</br>

<table>
<tr>

  <th>S.no.</th>
  <th>Charges For Following</th>
  <th>Price</th>
  <th>Per</th>
  <th>Total</h>

</tr>

{% if QuotedItem %}
{% for i in QuotedItem %}

<tr>
  <td>{{ forloop.counter }}</td>
  <td>{{ i.quote_item }}</td>
  <td>{{ i.quote_price }} </td>
  <td>{{ i.quote_qty  }}</td>
  <td>{{ i.total }}</td>
</tr>

{% endfor %}
{% endif %}

<tr>
    <td><b>Total </b></td>
    <td colspan="3"></td>
        <td align="right"> <b>{{total_cost}}</b></td>
</tr>

</br>
{% if bill.trans_total != None %}
<tr>
     <td>Transportation Charges</td>
     <td colspan="3"></td>
     <td align="right">{{bill.trans_total}}</td>
</tr>

<tr>
     <td>Total Amount</td>
     <td colspan="3"></td>
     <td align="right">{{bill.trans_net_total}}</td>
</tr>
{% endif %}

<tr>
     <td>Service Tax  @ {{ servicetaxprint }}% </td>
     <td colspan="3"></td>
     <td align="right">{{ bill.service_tax }}</td>
</tr>

<tr>
     <td>Education Cess  @ {{ educationtaxprint }}% </td>
     <td colspan="3"></td>
     <td align="right">{{ bill.education_tax }}</td>
</tr>


<tr>
     <td><b>G.Total (Rupees {{ net_total_eng }} only)</b> </td>
     <td colspan="3"></td>
     <td  align="right"><b>{{ cdftotal }} {{ bill.net_total}}</b></td>
</tr>   

      
</table>


<div style="position:absolute;right:30px;top:1050px;">

<!-- Dean is liable to change-->
<p> Dean Training And Consultancy Cell </p>
</div>

<br><div style="position:absolute;top:1050px;">
I/We here by agree to the terms & conditions as mentioned above</div>

<div style="position:absolute;right:30px;top:1100px;">
(Signature of Client/Deptt. Representative)</div>
</body>

</html>



Sandeep kaur

unread,
Jul 3, 2014, 2:54:57 PM7/3/14
to django-users

On Wed, Jul 2, 2014 at 11:03 AM, Aashita Dutta <aashit...@gmail.com> wrote:
>
> here is my model-
> from django.db import models
> import useraccounts
> from librehatti.catalog.models import *
> from django.contrib.auth.models import User
>
> class QuotedOrder(models.Model):
>     quote_buyer_id = models.ForeignKey(User)

OMG.
What do want to say?
Can you please use some other medium to show your code? Github may be one.

--
Sandeep Kaur
E-Mail: mkaur...@gmail.com
Blog: sandymadaan.wordpress.com



Reply all
Reply to author
Forward
0 new messages