Tech Forum Network

Programming, technical solutions and hot scripts
Home » TechQns » How to initialise model objects explicitly without json data in django rest framework

How to initialise model objects explicitly without json data in django rest framework

May 4, 2014 Posted by forumadmin under TechQns
Comments off

This is my Model: Client

from django.db import models

class Client(models.Model):
        client_code = models.CharField(max_length=20, blank=False)
        client_name = models.CharField(max_length=50, blank=False)
        debit = models.DecimalField(max_digits=19, decimal_places=2)
        credit = models.DecimalField(max_digits=19, decimal_places=2)

This is a method in my views.py

def importClientsFromCSV(request):
        if request.method == 'GET':
                pathToCSV = os.path.dirname(os.path.abspath(__file__)) + '/portfolio.csv'
                with open(pathToCSV, 'rU') as csvfile:
                        portfolioreader = csv.reader(csvfile, delimiter=',')
                        printer = "Number of Rows = "

                    rows = 0
                    for row in portfolioreader:
                            try:
                                    client = Client.objects.get(client_code=row[0])
                                    #Client Exists - Update Details
                                    client.debit = row[2]
                                    client.credit = row[3]
                                    serializer = ClientSerializer(client)
                                    if serializer.is_valid():
                                            serializer.save()
                                            rows = rows + 1
                            except Client.DoesNotExist:
                                    client = Client()
                                    client.client_code=row[0]
                                    client.client_name=row[1]
                                    client.debit=row[2]
                                    client.credit=row[3]
                                    serializer = ClientSerializer(client)
                                    if serializer.is_valid():
                                            serializer.save()
                                            rows = rows + 1
                    if rows > 0:
                            return HttpResponse(pathToCSV+", "+printer+str(rows),status=200)
                    else:
                            return HttpResponse("Could Not Process",status=404)

The problem is I am facing is not able to add the client object that i create in Except block into my database. I am not sure why i am not able to serialize this object and save it.

 

Asked By – Ishan Khanna        Read Answers    

More Related Questions

  • Nested JSON with Django apiREST I have a Django REST Framework view like this: #views.py class RegistroViewSet(viewsets.ModelViewSet): queryset = Registro.objects.all() serializer_class = RegistroSerializer and JSON […]
  • How to serializer/deserialize Django models My current Django REST Framework application has a Parameter model with 2 fields: "key" and "value". Currently, my REST API asks clients for a list of dictionaries with always the same […]
  • Django rest framework check if user exist with password The code I'm showing you below its what works for me right now. its not the most secure but does the job but i want to do it using POST method. any ideas how to change it? I have a […]
  • Django Rest Framework depth based on direction I have two models: class Organization(models.Model): name = models.CharField(max_length=64) class OrgUser(User): organization = models.ForeignKey(Organization, […]
  • Django Rest Framework wont let me have more than one permission I have a problem with the Django Rest Framework and permissions. DRF won't let me have more than one permission on my views for example. If I login to the API as an admin user I can get […]
  • global name get_serializer_class is not defined I understand I need to import it but where am I importing it from? from rest_framework import get_serializer_class The above doesn't work and I'm not seeing anything in documentation […]
  • Django ORM Cross-Product I have the following schema: class PCs(models.Model): model = models.ForeignKey(Products, primary_key=True) speed = models.IntegerField(max_length=256, blank = True, null=True) ram […]
  • nested if elif in view I have the following code which is always returning an HttpResponse even if I change the URL to specify the format - http://myserver/cdxcomposites/?format=xml What am I doing wrong […]
  • Default value for field in Django model Suppose I have a model: class SomeModel(models.Model): id = models.AutoField(primary_key=True) a = models.CharField(max_length=10) b = […]
  • django different serializer for GET and PUT – SyntaxError: invalid syntax I'm trying to use get_serializer_class() and I'm getting error messages. Here's my view - class CalendarDetail(RetrieveUpdateDestroyAPIView): def get_serializer_class(self): […]
0
  
Email
Tags: django, django-models, django-rest-framework, python

Comments are closed.

« keyboard block the tableview inside the popover controller
Doctrine2 association mapping with conditions »
Tech Forum Network powered by WordPress and The Clear Line Theme