I'm trying to create new instances based off of the form below however when it saves, the database only saves the foreign key value and the order value but nothing else. Any Idea why?
models:
class danceType(models.Model):
eventtype = models.ForeignKey(compType)
dance_name = models.CharField(max_length = 20)
Price = models.FloatField(max_length = 7, null=True, blank=True )
field_2 = models.CharField(max_length = 20, null=True, blank=True)
def __unicode__(self):
fields = ('field_2')
return self.dance_name
class dancer(models.Model):
dancetype = models.ForeignKey(danceType)
e_number = models.IntegerField(max_length = 4, null=True, blank=True)
D1_first_name = models.CharField(max_length = 20)
D1_last_name = models.CharField(max_length = 20)
D1_email = models.EmailField(max_length = 20)
city = models.CharField(max_length = 20)
order = models.PositiveIntegerField()
perform = models.NullBooleanField(null=True, blank=True)
View:
if request.method =='POST':
sub_type = request.POST.get("form")
dancetype = request.POST.get("dancetype")
ext = request.POST.get("quantity")
form = modelformset_factory(dancer, form=CompReg, extra=int(ext))
productform = form(queryset = dancer.objects.none())
if sub_type == "submitted":
productform = form(request.POST, request.FILES)
if productform.is_valid():
for p in productform:
dance=p.save(commit=False)
dance.dancetype_id = 4
dance.order = 1
dance.save()
else:
der = "it didnt save"
Related
class Product(models.Model):
product_name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(max_length=255)
brand = models.CharField(max_length=255)
price = models.CharField(max_length=255)
product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False)
product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False)
product_description = models.TextField()
category_id = models.ForeignKey(Categories,on_delete=models.CASCADE)
subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.product_name
def get_url(self):
return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug,
self.slug ])
'''view'''
val=request.POST.get('value')
val = re.findall("\d+", val) # code to get all inigers from string
min_price = int(val[0])
max_price = int(val[1])
print(min_price)
print(max_price)
***product = Product.objects.filter(category_id = categories,is_active =
True,price__gte = min_price, price__lte = max_price)***
when i give value greater than max_value product object returns null object
I want all objects between the two min_value and max_value
I made a create view that should be able to save an object and then redirect bit form some reasons the form is not valid and it's not saving the object. If anybody knows the answer then please write the whole answer with code.
My create view
class Submit_Property(generic.CreateView):
model = models.Property
form_class = forms.Property_Form
template_name = 'profile_details/submit-property.html'
Here's the model for This
class Property(models.Model):
title = models.CharField(max_length = 210,default = 'None')
STATUS_CHOICES = (
('RENT','Rent'),
('SALE','Sale'),
)
status = models.CharField(max_length = 210,choices = STATUS_CHOICES,default = 'Rent')
price = models.IntegerField()
area = models.CharField(max_length = 210,default = 'None')
ROOM_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('MORE','More'),
)
rooms = models.CharField(max_length = 210,choices = ROOM_CHOICES,default = '1')
BATHROOM_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
)
bathroom = models.CharField(max_length = 210,choices = BATHROOM_CHOICES,default = '2')
address = models.CharField(max_length = 210,default = 'None')
state = models.CharField(max_length = 210,default = 'None')
code = models.CharField(max_length = 210,default = 'None')
images = models.ImageField(upload_to = 'images',)
info = models.TextField(max_length = 1000,default = 'None')
parking = models.BooleanField(default = False,verbose_name = 'Parking')
air = models.BooleanField(default = False)
swimming = models.BooleanField(default = False)
laundry = models.BooleanField(default = False)
dealer_name = models.CharField(max_length = 210,default = 'None')
dealer_email = models.EmailField(max_length = 210,default = 'abc#gmail.com')
dealer_number = models.CharField(max_length = 210,default = 'Not mentioned')
user = models.ForeignKey(User,related_name = 'user',default = True)
timpestamp = models.DateTimeField(auto_now_add = True)
category = models.ManyToManyField(Category,related_name = 'categories',default = None)
def get_absolute_url(self,*args,**kwargs):
return reverse('profile_details:property')
def __str__(self):
return self.title
It's right here in form valid
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super().form_valid(form)
But don't write like this
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super(models.Property, self).form_valid(form)
Good day.
Am having a model called AddInv
AddInv(models.Model):
client = models.ForeignKey(User, null=True)
description = models.CharField(max_length = 100)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
sold = models.PositiveIntegerField(default=0)
details = models.CharField(max_length = 100)
country = models.ForeignKey(Signup, null = True)
def __str__(self):
return self.country
Model for Signup is
class Signup(models.Model):
user = models.OneToOneField(User)
phone_number = models.PositiveIntegerField( null=True)
zipcode = models.PositiveIntegerField(null=True)
street = models.CharField(max_length = 75, null=True)
city = models.CharField(max_length = 75, null=True)
state = models.CharField(max_length = 75, null= True)
country = models.CharField(max_length = 32, null=True, choices = CATEGORIES)
def __str__(self):
return self.country
and a views to filter by country
def homepage(request): # Client View
context = {}
items = get_object_or_404(AddInv, country="USA")
print "Items", items
return render(request, "selly/homepage.html", {'items': items})
Am having error pointing to
items = get_object_or_404(AddInv, country="USA")
What could be wrong with the code
Try this. Just an assume
items = get_object_or_404(AddInv, country__country="USA")
I used
items = AddInv.objects.filter(country__country="USA")
which worked
Hi I'm trying to populate my django app with data from a dbf file , I'm trying to make objects , as taught in the djangobook
>>> p = Publisher(name='Apress',
address='2855 Telegraph Ave.',
city='Berkeley',
state_province='CA',
country='U.S.A.',
website='http://www.apress.com/')
>>> p.save()
How can I add foreign keys and many to many keys this way ?
Or probably a better approach? dbf files have thousands of rows , so updating data by hand wouldn't be a viable approach.
Here's my models.py as suggested , almoust every model includes a foreign key , or a many to many field , I'm kind of stuck , because of filling them , I'm using dbf2py library to read the foxpro databases, and want to make a script for exporting the data
thanks in advance
from __future__ import unicode_literals
from django.db import models
class Terminos_pago(models.Model):
terminos = models.CharField(max_length = 20)
def __unicode__(self):
return self.terminos
class Clientes(models.Model):
"""docstring for Clientes"""
nombre = models.CharField(max_length=40)
direccion = models.CharField(max_length=70)
estado = models.CharField(max_length=16)
ciudad = models.CharField(max_length=30)
cp = models.IntegerField()
kilometros= models.IntegerField()
rfc = models.CharField(max_length=13 , null = True)
horas = models.DecimalField(null = True,decimal_places = 2 , max_digits = 5)
terminos_pago = models.ForeignKey(Terminos_pago,null=True)
dias_de_credito = models.IntegerField(blank = True , null = True)
def __unicode__(self):
return u'%s %s' % (self.nombre , self.horas)
class Contactos(models.Model):
"""docstring for Contactos"""
nombre = models.CharField(max_length=30)
departamento = models.CharField(max_length=16)
telefono = models.CharField(max_length = 16)
extension = models.IntegerField()
email = models.EmailField(blank = True)
cliente = models.ForeignKey(Clientes)
def __unicode__(self):
return self.nombre
class Maquinas(models.Model):
"""docstring for Maquinas"""
contacto = models.ForeignKey(Contactos , null = True)
id_usuario = models.CharField(max_length=13 , null = True , blank = True)
fabricante = models.CharField(max_length=15 )
no_serie = models.CharField(max_length=10 )
modelo = models.CharField(max_length=10 )
rango_x = models.IntegerField()
rango_y = models.IntegerField()
rango_z = models.IntegerField()
mppl = models.IntegerField()
mppe = models.IntegerField()
probe_type = models.CharField(max_length=10 )
probe_head = models.CharField(max_length=16)
probe_serial = models.CharField(max_length=15 )
extension = models.IntegerField( blank = True , null = True)
version_software=models.CharField(max_length=15)
version_firmware=models.CharField(max_length=15)
controlador = models.CharField(max_length=10)
accesorios = models.CharField(max_length=15 , null = True , blank = True)
driver_software= models.CharField(max_length=15)
modelo_computadora=models.CharField(max_length=10)
fecha_fabricacion = models.DateField(blank=True , null = True)
diametro_stylus= models.IntegerField()
def __unicode__(self):
return u'%s %s %s %s ' % (self.modelo , self.fabricante , self.contacto.nombre , self.contacto.cliente.nombre)
class Servicios(models.Model):
"""docstring for Servicios"""
servicio = models.CharField(max_length = 20)
def __unicode__(self):
return self.servicio
class ListaPrecios(models.Model):
"""docstring for ListaPrecios"""
fecha = models.DateField(null = True)
horas = models.IntegerField()
horas_extra = models.IntegerField()
horas_viaje = models.IntegerField(null = True)
kilometros = models.IntegerField()
hotel = models.IntegerField()
manuales = models.IntegerField()
traslados = models.IntegerField()
avion = models.IntegerField()
sobre_equipaje = models.IntegerField()
renta_auto = models.IntegerField()
papeleria = models.IntegerField()
def __unicode__(self):
return str(self.fecha)
class Ingenieros(models.Model):
"""docstring for Ingenieros"""
nombre = models.CharField(max_length=20)
referencia = models.CharField(max_length=4)
telefono = models.CharField(max_length = 16)
email = models.EmailField(null = True)
def __unicode__(self):
return self.nombre
class Cotizacion(models.Model):
"""docstring for Cotizacion"""
fecha = models.DateField()
contacto = models.ForeignKey(Contactos , null = True)
servicio = models.ManyToManyField(Servicios)
maquinas = models.ManyToManyField(Maquinas)
horas = models.IntegerField()
horas_extra = models.IntegerField(blank=True ,null = True)
#horas_viaje = models.IntegerField()
viajes = models.IntegerField()
hotel = models.IntegerField(blank=True ,null = True)
manuales = models.IntegerField(blank=True ,null = True)
traslados = models.IntegerField( blank=True ,null = True)
aviones = models.IntegerField(blank=True ,null = True)
sobre_equipaje = models.IntegerField(blank=True ,null = True)
renta_auto = models.IntegerField(blank=True ,null = True)
papeleria = models.IntegerField(blank=True ,null = True)
importe = models.IntegerField(blank = True , null = True)
iva = models.DecimalField(decimal_places = 2 , max_digits = 5 ,blank = True , default = 0.16)
observaciones = models.CharField(blank=True ,max_length = 255, null = True)
SA = models.NullBooleanField()
tipo_cambio = models.DecimalField(decimal_places = 2 , max_digits = 5, blank = True , null = True)
def __unicode__(self):
return u'%s %s %s %s' % (self.fecha , self.contacto.cliente.nombre , self.contacto.nombre ,self.servicio)
class Ordenes_de_servicio(models.Model):
"""docstring for Ordenes_de_trabajo"""
fecha = models.DateField(null = True)
ingeniero = models.ManyToManyField(Ingenieros)
observaciones = models.CharField(max_length = 255,null = True , blank = True)
viaticos = models.IntegerField()
orden_compra = models.CharField(max_length = 15)
orden_compra_interna = models.IntegerField(blank = True , null = True)
fecha_servicio = models.DateField(null = True)
viaticos_pagados = models.NullBooleanField()
cotizacion = models.ForeignKey(Cotizacion,null = True)
mail_enviado = models.IntegerField(null=True,blank=True,default=0)
fecha_mail_enviado = models.DateField(null=True , blank = True)
contacto_servicio = models.ForeignKey(Contactos , null = True )
def __unicode__(self):
return u'%s %s' % (self.fecha,self.ingeniero)
class Factura(models.Model):
"""docstring for Factura"""
fecha = models.DateField()
orden_servicio = models.ForeignKey(Ordenes_de_servicio)
descripcion = models.CharField(max_length=255,null = True , blank = True)
pagada = models.NullBooleanField()
def __unicode__(self):
return u'%s %s %s' % (self.orden_servicio.cotizacion.contacto.cliente.nombre , self.orden_servicio , self.fecha)
try and include your models.py, while you do that take a look at One-toMany for Many-to-many relationship
When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).
Using the models for example, an Entry object e can get its associated Blog object by accessing the blog attribute: e.blog.
(Behind the scenes, this functionality is implemented by Python descriptors. This shouldn’t really matter to you)
Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().
This is directly from the link i gave above, so visit the link and read deep
If a model has a ForeignKey, instances of that model will have access to the related (foreign) object via a simple attribute of the model.
Example:
>>> e = Entry.objects.get(id=2)
>>> e.blog # Returns the related Blog object.
You can get and set via a foreign-key attribute. As you may expect, changes to the foreign key aren’t saved to the database until you call save(). Example:
>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()
I'm having an issue where I instantiate a ModelForm-based form with a pre-existing instance of the model in the GET portion of my view function. This model already has several fields filled in; the ModelForm is used to collect other fields in the model. The pre-existing fields are excluded in the ModelForm's definition.
The problem is, during POST processing, after successful validation of the ModelForm, I'm calling ModelForm.save(commit=False)...and the model returned (which should be the same one I passed in as 'instance' in the GET handling, remember) has somehow lost all the fields that were previously set. The fields actually set by the form are fine; but it's no longer the original instance of my model.
This is not the behavior I expected; and in fact I've used this partial-model-in-modelform previously, and it works other places. What am I missing here??
Hopefully some code'll make all this clear...
So here's the Model:
class Order(models.Model):
STATUS = (
('Created', -1),
('Pending', 0),
('Charged', 1),
('Credited', 2),
)
SHIPPING_STATUS = (
('Cancelled', 0),
('Ready for pickup', 1),
('Shipped', 2),
('OTC', 3),
)
orderID = models.IntegerField(max_length=15, null=True, blank=True)
store = models.ForeignKey(Store)
paymentInstrument = models.ForeignKey(PaymentInstrument, null=True, blank=True)
shippingMethod = models.ForeignKey(ShippingMethod, null=True, blank=True)
last_modified = models.DateTimeField(null=True, blank=True)
date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
total = models.FloatField(default=0.0, blank=True)
shippingCharge = models.FloatField(default=0.0, blank=True)
tax = models.FloatField(default=0.0, blank=True)
status = models.CharField(max_length=50, choices=STATUS, default = 'Created')
shippingStatus = models.CharField(max_length=50, choices=SHIPPING_STATUS, default = '1')
errstr = models.CharField(max_length=100, null=True, blank=True)
# billing info
billingFirstname = models.CharField(max_length = 50, blank = True)
billingLastname = models.CharField(max_length = 50, blank = True)
billingStreet_line1 = models.CharField(max_length = 100, blank = True)
billingStreet_line2 = models.CharField(max_length = 100, blank = True)
billingZipcode = models.CharField(max_length = 5, blank = True)
billingCity = models.CharField(max_length = 100, blank = True)
billingState = models.CharField(max_length = 100, blank = True)
billingCountry = models.CharField(max_length = 100, blank = True)
email = models.EmailField(max_length=100, blank = True)
phone = models.CharField(max_length=20, default='', null=True, blank=True)
shipToBillingAddress = models.BooleanField(default=False)
# shipping info
shippingFirstname = models.CharField(max_length = 50, blank = True)
shippingLastname = models.CharField(max_length = 50, blank = True)
shippingStreet_line1 = models.CharField(max_length = 100, blank = True)
shippingStreet_line2 = models.CharField(max_length = 100, blank = True)
shippingZipcode = models.CharField(max_length = 5, blank = True)
shippingCity = models.CharField(max_length = 100, blank = True)
shippingState = models.CharField(max_length = 100, blank = True)
shippingCountry = models.CharField(max_length = 100, blank = True)
Here's the ModelForm definition:
class OrderForm(ModelForm):
class Meta:
model = Order
exclude = ('orderID',
'store',
'shippingMethod',
'shippingStatus',
'paymentInstrument',
'last_modified',
'date',
'total',
'payportCharge',
'errstr',
'status', )
widgets = {
'billingCountry': Select(choices = COUNTRIES, attrs = {'size': "1"}),
'shippingCountry': Select(choices = COUNTRIES, attrs = {'size': "1"}),
'billingState': Select(choices = STATES, attrs = {'size': "1"}),
'shippingState': Select(choices = STATES, attrs = {'size': "1"}),
}
And here is the view function:
def checkout(request):
theDict = {}
store = request.session['currentStore']
cart = request.session.get('cart', False)
order = request.session['currentOrder'] # some fields already set
if not cart: # ...then we don't belong on this page.
return HttpResponseRedirect('/%s' % store.urlPrefix)
if request.method == 'GET':
form = OrderForm(instance=order, prefix='orderForm')
else: # request.method == 'POST':
logging.info("Processing POST data...")
form = OrderForm(request.POST, prefix='orderForm')
if form.is_valid():
### AT THIS POINT, ORDER FIELDS ARE STILL GOOD (I.E. FILLED IN)
order = form.save(commit=False)
### AFTER THE SAVE, WE'VE LOST PRE-EXISTING FIELDS; ONLY ONES SET ARE
### THOSE FILLED IN BY THE FORM.
chargeDict = store.calculateCharge(order, cart)
request.session['currentOrder'] = order
return HttpResponseRedirect('/%s/payment' % store.urlPrefix)
else:
logging.info("Form is NOT valid; errors:")
logging.info(form._errors)
messages.error(request, form._errors)
theDict['form'] = form
theDict['productMenu'] = buildCategoryList(store)
t = loader.get_template('checkout.html')
c = RequestContext(request, theDict)
return HttpResponse(t.render(c))
Any/all help appreciated...
When you instantiate the form during the POST, the instance of the model you're editing is None, because you're not passing it in, and you're not persisting the form instance from the GET. Django won't do anything on its own to persist data between requests for you.
Try:
...
form = OrderForm(request.POST or None, instance=order, prefix='orderForm')
if request.method == 'POST':
logging.info("Processing POST data...")
if form.is_valid():
...
Now the instance will be populated for GET and POST, but the data from request.POST is optional for the form if it's None. It also saves you from having to instantiate the form in two places depending on request.method