How to sync OnetoOne relation in CreateView - django

models:
class Book(models.Model):
name = models.Char()
class BookCount(models.Model):
book = OneToOneField(Book)
count = SmallIntegerField(default=0)
views:
class BookCreate(CreateView):
model = Application
The question is, after create Book, I want insert a record to BookCount. Any ideas?

If your BookCount model is required you could use a listener for the post_save signal along the lines of this:
# models.py
from django.db.models.signals import post_save
# Model definitions
...
def create_book_count(sender, instance, created, **kwargs):
if created:
BookCount.objects.create(book=instance)
post_save.connect(create_book_count, sender=Book)
If your models are really this simple, you may want to drop the BookCount model and add a count field to your Book model instead to reduce the complexity and overhead here. See the docs on extending the user model for a short overview of why it might be better to avoid the OneToOneField option (the wording is specific to the User model, but it applies here, too):
Note that using related models results in additional queries or joins to retrieve the related data, and depending on your needs substituting the User model and adding the related fields may be your better option. However existing links to the default User model within your project’s apps may justify the extra database load.

Related

want to extend auth_user model in django by adding two fields

in django,i want to extend the auth_user model and adding the 2 fields.one is created_user which will display the date and time when user created something and other is modified_user which will display the date n time when modification is done..
is it possible by migration??
i ve tried dis code..
from django.contrib.auth.models import User, UserManager
class CustomUser(User):
created_user= models.DateTimeField("date and time when created")
modified_user=models.DateTimeField("date and time when modified")
objects= UserManager()
I suggest reading the documentation on creating your own custom user model.
In your particular case, the easiest thing would probably be to subclass AbstractUser and add your fields as above.
If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields. This class provides the full implementation of the default User as an abstract model.

In what model should I add the ManyToManyField?

I read the documentation about many-to-many relationships and the examples. What I could not find is a hint on where to put the ManyToManyField. In my case I have an extended user model Client and a model Pizza. Every client may mark one or more pizzas as favourites. Those are my two models:
from django.db import models
from django.contrib.auth.models import User
class Client(models.Model):
user = models.OneToOneField(User)
#? favourite_pizza = models.ManyToManyField()
class Pizza(models.Model):
name = models.CharField(max_length=255)
#? favourite_pizza = models.ManyToManyField()
In what model should I add the ManyToManyField? Does it matter?
PS The important information is how many favourite pizzas a client has (and which). It is less important how many clients marked a pizza as a favourite (and who). Consequently I would chose to put the ManyToManyField in the Client class.
From the Django documentation:
Generally, ManyToManyField instances should go in the object that’s going to be edited on a form.
Technically it does not matter. The question is from which model-side you will query the database.

Accessing a model variable in Django

Obviously I am new to Django, because I would assume this is relatively simple.
Lets say in my models.py I created a model "User", with two fields, a "username" and a "email" field. In a form called "UserForm", I want to access a list of all the "username"s in the "User" model. This list would then be used to populate a dropdown menu using Select.
I feel like this should be really easy, and I have been looking for some simple way to do it. I can find lots of ways that aren't all inclusive (ie filter(username = "Joe")), but I can't find one that will list all the users.
Any help would be greatly appreciated.
You're looking for a ModelChoiceField. Its queryset property can be populated from an ORM call, getting you all of the Users. Have a look at the section Creating Forms from Models in the docs for more information.
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
class Meta:
model = # Your model here
def __init__(self, *args, **kwargs):
self.fields['user'] = forms.ModelChoiceField(queryset=User.objects.all())
ForeignKey fields will be automatically shown as ModelChoiceFields, but you can always override the choices if you need.

Django admin inlines on default list page?

I have a table that only has a handful of entries in it, and it'd be nice if I could use inlines for their list instead of forcing staff to click through to the edit page each time.
That is, when someone clicks on the link that ordinarily gives a list of the model objects, they should instead see the model objects displayed inline.
I tried something like this, but unsurprisingly it gives an error because there's no foreign key:
class MyModelInline(admin.StackedInline):
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
inlines = [MyModelInline,]
admin.site.register(MyModel, MyModelAdmin)
For it to work as you've described you'll need an "editor" model to be a parent for the data. All the rows you want to display should have a foreign key to a single 'editor' model object. So, in models.py:
from django.db import models
class Editor(models.Model):
pass
class MyModel(models.Model):
name = models.CharField(max_length=100) # Field added for demonstration
# ... add any other fields you like ...
editor = models.ForeignKey(Editor)
And in admin.py:
from django.contrib import admin
from Test.models import Editor, MyModel
class MyModelInline(admin.StackedInline):
model = MyModel
class EditorAdmin(admin.ModelAdmin):
inlines = [MyModelInline,]
admin.site.register(Editor, EditorAdmin)
Some other things to consider:
When you make a new MyModel() object programmatically you must always set the foreign key to point to the editor. There should only be one instance of the editor for this to work as you've described. When using the admin interface, this foreign key should be set automatically by using the admin page for the editor object. I would suggest restricting creation and deletion of editor objects for everyone except yourself in production. If someone deletes the editor object then all MyModel objects disappear as well.
Alternative options:
1) If the edits the admin staff is doing are simple then I would recommend implementing "actions" instead.
2) There's also the possibility of overriding the admin template. I personally like this option less because every time Django is updated I have to check that my changes aren't interfering with new features. However, sometimes this is the only way to do some more advanced things in the admin interface. I've done this in my own project, but like to keep the changes minimal.

whats the difference between Django models and forms?

I am new to Django and can't understand the models and forms. Can any one suggest me the differences and tutorials related to them.
Basically, a model encapsulates information about something (i.e., it models it), and is stored in the database. For example, we could model a person:
from django import models
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
height = models.FloatField()
weight = models.FloatField()
Whenever a model instance is created and saved, Django stores it in the database for you to retrieve and use at a later date.
On the other hand, forms correspond to HTML forms, i.e., a set of fields which are presented to the end user to fill some data in. A form can be completely independent of a model, for example a search form:
from django import forms
class SearchForm(forms.Form):
search_terms = forms.CharField(max_length=100)
max_results = forms.IntegerField()
When submitted, Django takes care of validating the values the user entered and converting them to Python types (such as integers). All you then have to do is write the code which does something with these values.
Of course, if you have created a model, you will often want to allow a user to create these models through a form. Instead of having to duplicate all the field names and create the form yourself, Django provides a shortcut for this, the ModelForm:
from django.forms import ModelForm
class PersonForm(forms.ModelForm)
class Meta:
model = Person
As for further reading, I would start with the Django documentation, which includes a tutorial on creating and using models, and a fairly in-depth look at forms. There are also plenty of Django books and online tutorials to help you along.
Models are related to the database abstraction layer covered in Tutorial 1:
http://docs.djangoproject.com/en/dev/intro/tutorial01/
It covers everything from what they are, what the philosophy is, what it's abstracting (raw sql). Read it and come back if you have any questions, because it's really good.
Tutorial 4 covers forms.
http://docs.djangoproject.com/en/dev/intro/tutorial04/
The forms framework is just a helper for HTML forms. There are also ModelForms, based on the forms framework, that ties models together with forms, but the core of it is a framework for dealing with HTML form display, validation, and processing.