Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create model objects in a Django view?

Tags:

python

django

I know how to create model objects via a submitted form, but I'm wondering how to create objects in a view without having to go through a form. I'm aware that this can be done via the shell, but I have different reasons for doing it in the view.

As an example let's say I have a blog table that has a title and a body. How would I create a new object that sets the fields of the title and body?

def create_blog(request):
    # Create a new blog object.
    blog_obj.title= "First Blog"
    blog_obj.body= "This is the body"

Update: Here is my model.py

from django.db import models 

class Rating(models.Model):
    movie_name= models.CharField(max_length=100)
    total_ratings = models.IntegerField()
    total_rating_value = models.IntegerField()
    rating_average = models.DecimalField(max_digits=2, decimal_places=2)

Update 2: when I try saving my object it returns an error (class 'decimal.InvalidOperation'). rating_average is a Decimal_field. This is my actual object:

rating_obj = Rating(movie_name="Test Movie", total_ratings=1, total_rating_value= 5, rating_average= 5.0)
like image 788
Michael Smith Avatar asked Sep 25 '14 18:09

Michael Smith


People also ask

What is Django model view?

In the model view controller (MVC) architecture, the view component deals with how data is presented to users for consumption and viewing. In the Django framework, views are Python functions or classes that receive a web request and return a web response.

What is model object in Django?

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.


2 Answers

This is straight forward Python code and nothing specific to Django:

blog_obj = Blog(title="First Blog", body="This is the body")

Maybe you want to go through the good and easy to understand Django tutorial?

EDIT:
In order to solve your problem with your DecimalField you need to set max_digits greater than decimal_places.

From the docs:

Note that this number must be greater than or equal to decimal_places.

like image 61
timo.rieber Avatar answered Oct 16 '22 05:10

timo.rieber


Creating a model manager is recommended. Example from here:

class BookManager(models.Manager):
    def create_book(self, title):
        book = self.create(title=title)
        # do something with the book
        return book

class Book(models.Model):
    title = models.CharField(max_length=100)

    objects = BookManager()

book = Book.objects.create_book("Pride and Prejudice")
like image 38
Josh Avatar answered Oct 16 '22 03:10

Josh