POST 400 Bad Request Django - python

My branch model has 4 primary keys which are unique together: ('branch_short_name', 'partner_short_name', 'tenant', 'contributor'). I would like to be able to create/ POST some objects with similar
'branch_short_name', 'partner_short_name', 'tenant' but then with a unique 'contributor'.
When doing that I get a 400 bad request error in postman. I don't know where the problem lies, in the model or in the serializer.
models.py
class Branch(models.Model):
additional_address1 = models.CharField(max_length=255, blank=True, null=True)
additional_address2 = models.CharField(max_length=255, blank=True, null=True)
branch_number = models.CharField(max_length=255, blank=True, null=True)
branch_short_name = models.CharField(primary_key=True, max_length=255)
building = models.CharField(max_length=255, blank=True, null=True)
city = models.CharField(max_length=255, blank=True, null=True)
end_date = models.DateTimeField(blank=True, null=True)
country_code = models.CharField(max_length=255, blank=True, null=True)
created = models.DateTimeField(blank=True, null=True)
display_name = models.CharField(max_length=255, blank=True, null=True)
display_web = models.BooleanField(blank=True, null=True)
district = models.CharField(max_length=255, blank=True, null=True)
file_origin_date = models.DateTimeField(blank=True, null=True)
filename = models.CharField(max_length=255, blank=True, null=True)
floor = models.CharField(max_length=255, blank=True, null=True)
business_name = models.CharField(max_length=255, blank=True, null=True)
house_number = models.CharField(max_length=255, blank=True, null=True)
import_file_number = models.BigIntegerField(blank=True, null=True)
contributor = models.CharField(max_length=255)
job_id = models.CharField(max_length=255, blank=True, null=True)
latitude = models.FloatField(blank=True, null=True)
longitude = models.FloatField(blank=True, null=True)
start_date = models.DateTimeField(blank=True, null=True)
branch_hours = models.CharField(max_length=255, blank=True, null=True)
po_box = models.CharField(max_length=255, blank=True, null=True)
province = models.CharField(max_length=255, blank=True, null=True)
region = models.CharField(max_length=255, blank=True, null=True)
remarks = models.CharField(max_length=255, blank=True, null=True)
street = models.CharField(max_length=255, blank=True, null=True)
tenant = models.CharField(max_length=255)
updated = models.DateTimeField(blank=True, null=True)
zip_code = models.CharField(max_length=255, blank=True, null=True)
ranking = models.FloatField()
branch_type = models.IntegerField(blank=True, null=True)
branch_contact_text1 = models.CharField(max_length=255, blank=True, null=True)
branch_contact_text2 = models.CharField(max_length=255, blank=True, null=True)
phone_number = models.CharField(max_length=255, blank=True, null=True)
email_address = models.CharField(max_length=255, blank=True, null=True)
website = models.CharField(max_length=500, blank=True, null=True)
branch_hours_osm = models.CharField(max_length=400, blank=True, null=True)
partner_short_name = models.ForeignKey('Partner', models.DO_NOTHING, db_column='partner_short_name')
features = models.TextField(blank=True, null=True) # This field type is a guess.
marketing_attribute_short_names = models.TextField(blank=True, null=True) # This field type is a guess.
marketing_attribute_values = models.TextField(blank=True, null=True) # This field type is a guess.
class Meta:
managed = False
db_table = 'branch'
unique_together = (('branch_short_name', 'partner_short_name', 'tenant', 'contributor'),)
serializers.py
class BranchSerializer(serializers.ModelSerializer):
class Meta:
model = Branch
fields = '__all__'
views.py
#api_view(['GET', 'POST', 'DELETE'])
def branch_list(request):
# GET list of branchs, POST a new branch, DELETE all branchs
if request.method == 'GET':
branchlist = Branch.objects.all()[:10]
branchlist_serializer = BranchSerializer(branchlist, many=True)
return JsonResponse(branchlist_serializer.data, safe=False)
# 'safe=False' for objects serialization
elif request.method == 'POST':
branch_data = JSONParser().parse(request)
branch_serializer = BranchSerializer(data=branch_data)
if branch_serializer.is_valid():
branch_serializer.save()
return JsonResponse(branch_serializer.data, status=status.HTTP_201_CREATED)
return JsonResponse(branch_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
urls.py
urlpatterns = [
url(r'^api/places$', views.branch_list),
url(r'^api/placescount$', views.branch_count),
url(r'^api/latestimport/(?P<contributor>\D+)$', views.latest_import),
url(r'^api/partners$', views.partner_list),
url(r'^api/partners/(?P<partner_short_name>[0-9]+)$', views.partner_detail),
url(r'^api/places/(?P<branch_short_name>[0-9]+)$', views.branch_detail),
url(r'^api/places/(?P<branch_short_name>[0-9]+)/(?P<contributor>\D+)$' , views.branch_from_contributor),
]

Related

Django queryset foreign key 3 tables

I have the following models:
class Productos(models.Model):
nombre = models.CharField(max_length=200, null=True)
precio_publico = models.FloatField(null=True, blank=True)
costo = models.FloatField(null=False, blank=False)
inventario = models.IntegerField(null=False, blank=False, default=0)
fecha_compra = models.DateField(blank=True, null=True)
tipo_movimiento = models.CharField(max_length=1, choices=TIPO_MOVIMIENTO)
slug = models.SlugField(blank=True, null=True)
descripcion_corta = models.TextField(blank=True, null=True)
descripcion = models.TextField(blank=True, null=True)
imagen = models.ImageField(upload_to='images/',blank=True, null=True)
marca = models.CharField(max_length=20)
categoria = models.ForeignKey(Categorias, null= True, on_delete=SET_NULL)
descuento = models.ForeignKey(Promos, blank=True, null=True, on_delete=CASCADE)
inventariar = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class ProductosOrden(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
producto = models.ForeignKey(Productos, on_delete=models.CASCADE)
cantidad = models.IntegerField(default=1)
ordenado = models.BooleanField(default=False)
class Orden(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
producto = models.ManyToManyField(
ProductosOrden)
medio_de_venta = models.ForeignKey(MediosVenta, null=True, blank=False, on_delete=models.SET_NULL)
fecha_venta = models.DateField(blank=False, null=False)
ordenado = models.BooleanField(default=False)
ref_code = models.CharField(max_length=20, blank=True, null=True)
promo = models.ForeignKey(Promos,null=True, blank=True, on_delete=CASCADE )
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
vendido_por = models.CharField(max_length=20, null=False, blank=False)
I need to query from Orden all the way to Productos and get the 'name' attribute
I have tried the following:
categoria = Orden.objects.filter(user=self.request.user, ref_code = '225v3cwhvqi0ymp2yw2n').values('producto__producto')
and I get Id's instead of 'nombre':
<QuerySet [{'producto__producto': 5}, {'producto__producto': 19}, {'producto__producto': 3}]>
how can I access the attribute 'nombre' from the 'Productos' Model?
You should build query like this categoria = Orden.objects.filter(user=self.request.user, ref_code = '225v3cwhvqi0ymp2yw2n').values('producto__producto__nombre')

How do I attach the user's order to the product issued Django

Ok, so I have this application where the users make an order for a Category through the app. Every category contains products. And what I want to do is when a product is issued to the user the order status for the order made by the user should change from 1(approved) to 4(issued) and the product name should be added in the order table to confirm the product that was issued to that request.
How do I do that in Django? Below are my models
class Category(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Product(models.Model):
pro_name = models.CharField(max_length=100, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
issue_to = models.ForeignKey('Order',default='', on_delete=models.CASCADE,blank=True, null=True)
serial_num = models.CharField(max_length=100, blank=True, null=True)
model_num = models.CharField(max_length=100, blank=True, null=True)
storage_size = models.CharField(max_length=50, blank=True, null=True)
memory_size = models.CharField(max_length=50, blank=True, null=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, blank=True, null=True)
receive_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_quantity = models.IntegerField(default='0', blank=True, null=True)
issue_by = models.CharField(max_length=50, blank=True, null=True)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=False, null=True)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Order(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
pro_name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True,related_name='product')
staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
order_quantity = models.PositiveIntegerField(null=True)
department = models.CharField(max_length=50, choices=DEPARTMENT, null=True)
order_status = models.IntegerField(default=0)
approve_quantity = models.IntegerField(default='1', blank=True, null=True)
transaction_id = models.CharField(default=uuid.uuid4().hex[:8].upper(), max_length=50, editable=False)
timestamp = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
Currently what I do is after a particular product has been issued to a user I have to go to the order table and change the order status to 4(issued) which is hectic especially when the orders are plenty.

Django: Join Two Models without ForeignKey: (Can i Use Polymorphic Relation, if Yes Then How)

class Services(models.Model):
id = models.BigAutoField(primary_key=True)
medical_unit = models.ForeignKey(MedicalUnits, models.DO_NOTHING, related_name='services_medical_unit',
blank=True, null=True)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
name = models.CharField(max_length=500, blank=True, null=True)
billing_code = models.CharField(max_length=500, blank=True, null=True)
department_id = models.IntegerField(blank=True, null=True)
assignable_type = models.CharField(max_length=500, blank=True, null=True)
assignable_id = models.BigIntegerField(blank=True, null=True)
department_service_id = models.IntegerField(blank=True, null=True)
user_id = models.IntegerField(blank=True, null=True)
is_active = models.BooleanField(blank=True, null=True)
ward_id = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'services'
class PackageServices(models.Model):
id = models.BigAutoField(primary_key=True)
billing_package = models.ForeignKey(BillingPackages, models.DO_NOTHING, blank=True, null=True)
assignable_type = models.CharField(max_length=500, blank=True, null=True)
assignable_id = models.BigIntegerField(blank=True, null=True)
quantity = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
class Meta:
managed = False
db_table = 'package_services'
I want To access "PackageService" Through "Services".

Copy Model Object Id From a Model To Another Model In Django

I want to copy data from a model to another model, I found an example Copy Model Object From a Model To Another In Django but I'm getting an error:
AttributeError: 'BigAutoField' object has no attribute 'wid'.
I want wid in the tobjects model to get the Id from w_orders model. This is my code:
models.py
class w_orders(models.Model):
Id = models.BigAutoField(primary_key=True)
datedefwo = models.DateField(default=datetime.now)
datesched = models.DateField(blank=True, null=True)
datefinished = models.DateField(blank=True, null=True)
sign = models.BigIntegerField(blank=True, null=True)
statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES)
typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES)
comments = models.CharField(max_length=254, blank=True, null=True)
navid = models.BigIntegerField(blank=True, null=True)
navkonsid = models.CharField(max_length=12, blank=True, null=True)
navname = models.CharField(max_length=254, blank=True, null=True)
navcustadr = models.CharField(max_length=254, blank=True, null=True)
navdebt = models.FloatField(blank=True, null=True)
navpropcode = models.CharField(max_length=254, blank=True, null=True)
navdepcode = models.CharField(max_length=254, blank=True, null=True)
navphoneno = models.CharField(max_length=254, blank=True, null=True)
navreasoncomp = models.CharField(max_length=254, blank=True, null=True)
nightshift = models.BooleanField(default=False)
priority = models.BigIntegerField(blank=True, null=True)
stid = models.BigIntegerField(blank=True, null=True)
mapurl = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.Id
def save(self, *args, **kwargs):
super(w_orders, self).save(*args, **kwargs)
newob = tobjects()
...
newob.save()
class tobjects(models.Model):
oid = models.BigAutoField(primary_key=True)
wid = models.ForeignKey(w_orders, on_delete=models.CASCADE)
objtypegisid = models.BigIntegerField(blank=True, null=True, default=1)
objgisid = models.BigIntegerField(blank=True, null=True, default=1)
condgenid = models.BigIntegerField(blank=True, null=True, default=1)
condriskid = models.BigIntegerField(blank=True, null=True, default=1)
condratsid = models.BigIntegerField(blank=True, null=True, default=1)
condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1)
condmhwallid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydrsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydreid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvolsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvoleid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconssid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconseid = models.BigIntegerField(blank=True, null=True, default=1)
txt = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.oid
class w_orders(models.Model):
Id = models.BigAutoField(primary_key=True)
datedefwo = models.DateField(default=datetime.now)
datesched = models.DateField(blank=True, null=True)
datefinished = models.DateField(blank=True, null=True)
sign = models.BigIntegerField(blank=True, null=True)
statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES)
typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES)
comments = models.CharField(max_length=254, blank=True, null=True)
navid = models.BigIntegerField(blank=True, null=True)
navkonsid = models.CharField(max_length=12, blank=True, null=True)
navname = models.CharField(max_length=254, blank=True, null=True)
navcustadr = models.CharField(max_length=254, blank=True, null=True)
navdebt = models.FloatField(blank=True, null=True)
navpropcode = models.CharField(max_length=254, blank=True, null=True)
navdepcode = models.CharField(max_length=254, blank=True, null=True)
navphoneno = models.CharField(max_length=254, blank=True, null=True)
navreasoncomp = models.CharField(max_length=254, blank=True, null=True)
nightshift = models.BooleanField(default=False)
priority = models.BigIntegerField(blank=True, null=True)
stid = models.BigIntegerField(blank=True, null=True)
mapurl = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.Id
class tobjects(models.Model):
oid = models.BigAutoField(primary_key=True)
wid = models.ForeignKey(w_orders, on_delete=models.CASCADE)
objtypegisid = models.BigIntegerField(blank=True, null=True, default=1)
objgisid = models.BigIntegerField(blank=True, null=True, default=1)
condgenid = models.BigIntegerField(blank=True, null=True, default=1)
condriskid = models.BigIntegerField(blank=True, null=True, default=1)
condratsid = models.BigIntegerField(blank=True, null=True, default=1)
condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1)
condmhwallid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydrsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipehydreid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvolsid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepvoleid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconssid = models.BigIntegerField(blank=True, null=True, default=1)
condpipedepconseid = models.BigIntegerField(blank=True, null=True, default=1)
txt = models.CharField(max_length=254, blank=True, null=True)
def __unicode__(self):
return self.oid
#receiver(post_save, sender=w_orders)
def ensure_order_exists(sender, **kwargs):
if kwargs.get('created', False):
tobjects.objects.get_or_create(wid=kwargs.get('instance'))
for o in w_orders.objects.all():
t = tobjects.create(wid=o)
t.save()
Also possible is bulk_create which is faster but only works with PostgreSQL (please read https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create):
tobjects.objects.bulk_create([tobjects(wid=o) for o in w_orders.objects.all()])
Please consider PEP 8 for your code. It's horrible to read.

Django: How do i extract the email ID of users on the admin page

How do I extract the email ID of users from the Users columns? I've managed to make sure that the name of the users are extracted through the Users table.
class Project(models.Model):
STATUS_CHOICE = (
('Project Manager', 'Project Manager'),
('Technician', 'Technician'),
('Tester', 'Tester')
)
STATUS_CHOICE_1 = (
('Work Assigned', 'Work Assigned'),
('Work in Progress', 'Work in Progress'),
('Testing', 'Testing'),
('Completed', 'Completed')
)
project_name = models.CharField(max_length=100)
project_description = models.CharField(max_length=100)
Admin_Name = models.CharField(max_length=100)
Admin_Mail_ID = models.EmailField(max_length=50)
Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Project_Manager_1_users")
Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
Project_Manager_2 = models.CharField(max_length=50, blank=True, null=True)
Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Technician_1_users")
Technician_1_Mail_ID = models.EmailField(max_length=50)
Technician_2 = models.CharField(max_length=50, blank=True, null=True)
Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_3 = models.CharField(max_length=50, blank=True, null=True)
Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Tester_1 = models.CharField(max_length=50, blank=True, null=True)
Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example#gmail.com')
Additional_User_1 = models.CharField(max_length=50, blank=True, null=True)
Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_2 = models.CharField(max_length=18, blank=True, null=True)
Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_3 = models.CharField(max_length=18, blank=True, null=True)
Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Finish_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents = models.FileField(null=True, blank=True)
I'm not that great at coding and I would really appreciate all the help I'd get.. Thank you so much everyone..

Categories