开发者

Manager for a user profile to create and delete both user and the profile

I have a model called Personnel which I'm using as the profile model for the User model. Moderators on my site can create and their own accounts but all the profile fields should be filled in. Here's my model

class Personnel(models.Model):
    """
    Model for storing the personnel information
    """
  开发者_StackOverflow  user = models.OneToOneField(
        User
    )
    phone = models.CharField(
        null=False, max_length=50, verbose_name="Phone"
    )
    address = models.CharField(
        null=True, max_length=500, verbose_name="Address"
    )

I need to implement the following.

A create method on the Personnel model so that when someone invokes the method Personnel.objects.create(username, email, phone, address), it creates a new user in the User model and also stores the profile fields in the Personnel model. I would need a form for this to handle the request but this form should validate both the fields of the Personnel model and the User model.

An delete method on the Personnel model so that when someone invokes the method Personnel.objects.delete(username), it deletes the profile from the Personnel model and the user from the User model. I don't think I need a form for this.

Could anyone please tell me how to do the form bit and the manager bit. Here's what I have so far:

Form:

?

Manager:

from django.db import models
from django.contrib.auth.models import User

class Personnel(models.Manager):
    """
    This is the manager for the Personnel model. It contains the logic for
    creating a new personnel which also creates a new User.
    """
    def create(self, username, email, phone, address):
        """
        Creates a new personnel
        """
        pass

    def delete(self, username):
        """
        Deletes a personnel
        """
        super(Personnel, self).delete()

Thanks a lot.


class PersonnelManager(models.Manager):
    def create(self, username, email, phone, address, **kwargs):
        user = User.objects.get_or_create(username=username, email=email)
        return super(PersonnelManager, self).create(user=user, phone=phone, address=address, **kwargs)

class Personnel(models.Model):
    ...
    objects = PersonnelManager()

Deleting should take care of itself through the cascade.


It's probably easier to add methods to Personnel.save() and Personnel.delete() to do this work.

https://docs.djangoproject.com/en/1.3/topics/db/models/#overriding-model-methods

The Personnel.save() is called by Django and can create a missing User and Profile.

The "Overriding Delete" sidebar may not be relevant, depending on your application. Bulk deletes are rare and it's easy to do a post-bulk-delete cleanup. Or do individual deletes instead of a bulk delete.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜