I am new to django management commands! I am trying to write a commands to populate author...
My models.py is:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField(unique=True, blank=False, null=False)
class Book(models.Model):
book_name = models.CharField(max_length=10)
summery = models.TextField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)
and i am tried to write a command but i failed..
this is my blog/management/commands/populate_author.py below:
from django.core.management.base import BaseCommand, CommandError
from blog.models import Author, Book
class Command(BaseCommand):
help = 'Populate author'
def handle(self, *args, **options):
Author.objects.create()
Author.save()
Can anyone please help me to make it happen?
You're trying to create an Author without giving any data for the fields. If you've managed to create one Author with a blank value for the required email field, then the next Author you try to create will have a blank email field and that is what causes the non-unique error. Do this to create an Author:
Author.objects.create(name='Author Name', email='authoremail#domain.com')
Related
I am doing a group project for a bootcamp and we just started Django for the back-end. We also are using React for front-end. Our project is basically a knockoff reddit.
We have a User model:
`from django.db import models
class User(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
email = models.CharField(max_length=100, unique=True)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=255)
def __str__(self):
return '%s' % (self.username)`
and a Post model:
`from django.db import models
from auth_api.models import User
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=255)
formBody = models.TextField(null=True, blank=True)
imageURL = models.CharField(max_length=200, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)`
Our Post Serializers(pretty unfamiliar with this):
`from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
user = serializers.CharField(required=True)
class Meta:
model = Post
fields = ('id', 'user', 'title', 'formBody', 'imageURL', 'created',)`
And our Post Views:
`from django.shortcuts import render
from rest_framework import generics
from .serializers import PostSerializer
from .models import Post
from auth_api.models import User
class PostList(generics.ListCreateAPIView):
queryset = Post.objects.all().order_by('id')
serializer_class = PostSerializer
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all().order_by('id')
serializer_class = PostSerializer`
The idea was when a user created a post their info would be saved with the post so that way when we display the post we could say who created at. Also we could have a user profile that could see all of their posts. I assumed that what would happen is the user info would get saved inside a object in the user column, but the first way we tried only saved the userID and we couldn't access any of the users info. The second way(what we have now) keeps giving us this error: ValueError: Cannot assign "'1'": "Post.user" must be a "User" instance.The 1 is the userID that we pass in from the frontend of the user that created the post. I am unsure of where to go from here and have been stuck for a while on this. Hopefully I provided enough info
I was building my app using django but I got this error in the models.py file:
creator = models.ManyToManyField(Teacher, on_delete=models.CASCADE)
NameError: name 'Teacher' is not defined
This is my current code in models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class School(models.Model):
nombre = models.CharField(max_length=355)
profesoras = models.ManyToManyField(Teacher)
class Teacher(models.Model):
user = models.ForeignKey(User, related_name="teacherClass", blank=False)
school = models.ManyToManyField(School, blank=True)
class Post(models.Model):
creator = models.ManyToManyField(Teacher, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
text = models.TextField(max_length=2000)
Do you know how can I solve this error?
The issue here is that you are trying to reference a model that has not been created yet. The Django docs state what to do in such a case.
If you need to create a relationship on a model that has not yet been
defined, you can use the name of the model, rather than the model
object itself:
class Car(models.Model):
manufacturer = models.ForeignKey(
'Manufacturer',
on_delete=models.CASCADE,
)
# ...
class Manufacturer(models.Model):
# ...
pass
So for your case, you would just change your model relationships to strings.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class School(models.Model):
nombre = models.CharField(max_length=355)
profesoras = models.ManyToManyField("Teacher") # Make this a string because it has not been defined yet
class Teacher(models.Model):
user = models.ForeignKey(User, related_name="teacherClass", blank=False)
school = models.ManyToManyField(School, blank=True)
class Post(models.Model):
creator = models.ManyToManyField("Teacher", on_delete=models.CASCADE) # Same with this one.
title = models.CharField(max_length=255)
text = models.TextField(max_length=2000)
The django docs are always really useful and have a lot of good information.
The error is just fine because you are using it before declaring it and also your relationships are a little messy. You can say that you can have as many schools as you wish in this app and each professor teaches in many schools so it can be something like this by using many to many relation:
class School(models.Model):
name = models.CharField(max_length=355)
class Teacher(models.Model):
user = models.ForeignKey(User, related_name="teacherClass", blank=False, on_delete=models.CASCADE)
school = models.ManyToManyField(School, blank=True)
class Post(models.Model):
creator = models.ManyToManyField(Teacher)
title = models.CharField(max_length=255)
text = models.TextField(max_length=2000)
I suggest you that study a little bit about relations in databases so you won't have any similar problem in future.
according to https://docs.djangoproject.com/en/1.9/topics/testing/overview/ :
from django.test import TestCase
from myapp.models import Animal
class AnimalTestCase(TestCase):
def setUp(self):
Animal.objects.create(name="lion", sound="roar")
Animal.objects.create(name="cat", sound="meow")
def test_animals_can_speak(self):
"""Animals that can speak are correctly identified"""
lion = Animal.objects.get(name="lion")
cat = Animal.objects.get(name="cat")
self.assertEqual(lion.speak(), 'The lion says "roar"')
self.assertEqual(cat.speak(), 'The cat says "meow"')
I want to create setUp to my model class:
class Post(models.Model):
author = models.ForeignKey('auth.User')
tags = models.ManyToManyField('blogUserPlane.Tag')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
This is my NOT WORKING setUp:
def setUp(self):
Post.objects.all().create(author=User(), tag=models.ManyToManyField('blogUserPlane.Tag'), title="title1", text="text1", created_date=None, published_date=None)
What is correct way to create records of model with ManyToManyField and ForeginKey?
If you want to enter a value in a ForeignKey or ManyToMany field ,you first need to import that value .
For example if you want to enter a value in author field ,
from django.contrib.auth.models import User
user = User.objects.get(username = 'your_username')
Post.objects.create(author = user)
To save M2M
Save some values in the link table
`tag = blogUserPlane.Tag()
...
tag.save()`
To save Foreign key
from django.contrib.auth.models import User
post = Post()
post.author = User
...
post.tags.add(tag)
post.save()
I'm using Django 1.5 on Python 3.2.3.
When I run python3 manage.py syncdb, it builds the DB tables, & asks for my email (defined as the unique instead of a username), and then when I enter that, I get this error --
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'
Oddly, it creates the tables anyway, but now, I'm confused 'cause I really don't get what I'm supposed to do. The documentation says I should create a Custom User Manager, but that's all it really says. It doesn't give me a clue where to create it or how. I looked through the docs on Managers, but that really didn't help me figure anything out. It's all too vague. I keep Googling trying to find some clue as to what I need to do, but I'm just going crazy with more and more questions instead of any answer. Here's my models.py file:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class MyUsr(AbstractBaseUser):
email = models.EmailField(unique=True,db_index=True)
fname = models.CharField(max_length=255,blank=True, null=True)
surname = models.CharField(max_length=255,blank=True, null=True)
pwd_try_count = models.PositiveSmallIntegerField(blank=True, null=True)
pwd_last_try = models.DateTimeField(blank=True, null=True)
resetid = models.CharField(max_length=100,blank=True, null=True)
last_reset = models.DateTimeField(blank=True, null=True)
activation_code = models.CharField(max_length=100,blank=True, null=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['fname','activation_code']
How do I write a Custom User Manager? Do I put it in the MyUsr model as a method? Or is that even what I'm supposed to do? Should I be doing something totally different? I'm not sure of anything at this point. I just don't understand. The documentation on this doesn't seem clear to me, leaving a lot open for interpretation. I'm pretty new to Django, but I've been into Python for several months.
You define a custom manager by sub-classing BaseUserManager and assigning it in your Model to the objects attribute.
from django.contrib.auth.models import AbstractUser, BaseUserManager
class MyMgr(BaseUserManager):
def create_user(...):
...
def create_superuser(...):
...
class MyUsr(AbstractBaseUser):
objects = MyMgr()
email = models.EmailField(unique=True, db_index=True)
fname = models.CharField(max_length=255, blank=True, null=True)
...
You must define the create_user and create_superuser methods for your BaseUserManager. See the docs.
Depending on your case all you might need to fix this error will be to assign the objects variable in the CustomUser class, to inherit form BaseUserManager() instead of models.Manager() which some would have initially set
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
class CustomUser(AbstractUser):
name = models.CharField(null=True, blank=True, max_length=100)
......
# model managers
# objects = models.Manager()
objects = BaseUserManager()
I'm a new Django (1.3) user and I'm setting up the typical blog/article application. I have a model in which I'd like to save the current username (to see who created the article). I've implemented advice on this, but my code crashes the server with the message: "NameError: name 'User' is not defined". Here's my model:
from django.db import models
class Resort(models.Model):
name = models.CharField(max_length=300)
description = models.TextField()
location = models.CharField(max_length=300)
ski_hire = models.TextField()
weather = models.TextField()
piste_map = models.TextField()
webcam = models.TextField()
snow = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User)
def __unicode__(self):
return self.name
I have a sneaking suspicion that I need to override the save method in admin.py, but I'm not sure how to do this. Any advice would be greatly appreciated. Thanks!
You need to make sure you import user from django.contrib.auth.models in your models.py when using User in a foreign key.
In your admin.py you can use save_model:
class ResortAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
Maybe You should import User class before assignment?
from django.contrib.auth.models import User