Cannot generate instances of abstract factory UserFactory ( Factory boy) - django

factory.errors.FactoryError: Cannot generate instances of abstract factory UserFactory; Ensure UserFactory.Meta.model is set and UserFactory.Meta.abstract is either not set or False.
Im using factory boy library To test my functions
my class UserFactory Here
UserFactory image
import factory
import factory.django
from users.models import Users
from django.contrib.auth.hashers import make_password
from django.db import models
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Sequence(lambda n: f"user_{n:004}")
email = factory.LazyAttribute(lambda user: f"{user.username}#example")
password = factory.LazyFunction(make_password("password"))
class Meta:
model: Users
abstract = True
Here Model User I'm inheritance from class abstract user
User Class Image
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser
class Users(AbstractUser):
bio = models.CharField(max_length=256, blank=True)
I added class meta abstract and still not working

The error message says it all: factory_boy will only allow you to instantiate from a factory if said factory has a Meta.model and is not marked Meta.abstract = True.
Typically, one would use:
class MyFactory(...):
class Meta:
model = SomeModel
In advanced cases, some projects might have abstract factories; in which case that abstractness must be disabled:
class SomeAbstractFactory(...):
class Meta:
model = MyModel
abstract = True
class MyFactory(SomeAbstractFactory):
class Meta:
abstract = False
In your code example, you have written model: User instead of model = User; it can easily be fixed with:
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
# (No "abstract = " clause)

Related

Why are we inheriting here in django?

This is my first post here. I am a beginner in django and I am almost done reading through django for beginners by William S. Vincent. In chapter 8, he goes over the custom user model and creates the following code for the forms needed:
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = UserCreationForm.Meta.fields + ("age",)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = UserChangeForm.Meta.fields
My question is why are we using class Meta here and why is the first class Meta inheriting from "UserCreationForm", but the second class Meta doesn't. Thanks!
My question is why are we using class Meta here and why is the first class Meta inheriting from "UserCreationForm", but the second class Meta doesn't.
Likely that is a typo, it should be:
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta): # šŸ–˜ inherit from the Meta innerclass
model = CustomUser
fields = UserCreationForm.Meta.fields + ('age',)
It is usually a good idea to always inerhit from the Meta of the superclass, since it will for example in this case also include the field_classes attributeĀ [GitHub]:
class Meta:
model = User
fields = ("username",)
field_classes = {"username": UsernameField}
It here thus adds a specific field class for username, not the default CharField. If we want that behavior to continue, then we will need to inherit this, otherwise our Meta has no such field_classes item, and it will thus "fallback" on a simple CharField.
The latter was better with a simple:
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = CustomUser
since for modern versions of Django, it will make use of the UsernameField field class as well.

How to pass value as string in ForeignKey and not integer?

IMPORT PHOTO
I tried to import my model in admin to csv file and the output of the foreignkeys are integers(see Department and Status fields in photo above). How can i convert that into string?
You can check how to add relationship fields the documentation. It suggests adding two classes: a resource class to define which fields are exported and an admin class that connects the resource class to the admin interface. In your case admin.py may look like
from django.contrib import admin
from models import *
from import_export.admin import ImportExportModelAdmin
from import_export import resources
class HrmResource(resources.ModelResource):
class Meta:
model = hrm
fields = ('name', 'place', 'department__nm_dept')
class HrmAdmin(ImportExportModelAdmin):
resource_class = HrmResource
admin.site.register(r_dept)
admin.site.register(hrm, HrmAdmin)
and models.py like
from django.db import models
class r_dept(models.Model):
nm_dept = models.CharField(max_length=200)
def __str__(self):
return self.nm_dept
class hrm(models.Model):
name = models.CharField(max_length=200)
place = models.CharField(max_length=200)
department = models.ForeignKey('r_dept')
def __str__(self):
return self.name

How to get all objects linked to a given foreign ket field using rest_framework serializers?

I have two models and I want to call the field values associated with the foreign key present in both the models.
For example:
Say we have two models:
from django.db import models
from django.contrib.auth.models import User
class Bike(models.Model):
bike_model = models.CharField(max_length=200)
owner = models.ForeignKey(User,on_delete=models.CASCADE)
class Car(models.Model):
car_model = models.CharField(max_length=200)
owner = models.ForeignKey(User,on_delete=models.CASCADE)
And the relating serializer class is:
from rest_framework import serializers
from .models import Bike,Car
class BikeSerializer(serializers.ModelSerializer):
class Meta:
model = Bike
fields = ('bike_model','owner')
class CarSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('car_model','owner')
Now, I want to add a field in BikeSerializer to get all the cars associated with the given owner. That is I want to make the following change:
class BikeSerializer(serializers.ModelSerializer):
cars_owned = ???
class Meta:
model = Bike
fields = ('bike_model','owner','cars_owned')
I am unable to get how the cars owned by the owner can be returned. Thus, for the data from serializer, I want the bike model, the owner id and the list of all the car ids that the owner has.
You should look this SerializerMethodField.
Basically, you need to create a method inside BikeSerializer that return cars owned.
class BikeSerializer(serializers.ModelSerializer):
cars_owned = serializers.SerializerMethodField()
class Meta:
model = Bike
fields = ('bike_model','owner','cars_owned')
def get_cars_owned(self, object):
# This is your query to get all cars associated
return object.cars_owned.all()
You may add seializer as field:
class BikeSerializer(serializers.ModelSerializer):
cars_owned = CarSerializer(source='owner.car_set', many=True, read_only=True)
class Meta:
model = Bike
fields = ('bike_model','owner','cars_owned')

Django & Graphene: How to handle bidirectional relationship with polmorphic models?

I have a Django model that looks like this (simplified of course):
from django.db import models
from polymorphic.models import PolymorphicModel
class Tournament(models.Model):
slug = models.CharField(max_length=100, unique=True)
class Event(PolymorphicModel):
tournament = models.ForeignKey(Tournament, related_name='events')
slug = models.CharField(max_length=100)
class PracticeEvent(Event):
pass
class MatchEvent(Event):
winner = models.CharField(max_length=100, null=True, blank=True, default=None)
Tournaments consist of two kinds of events: practice events, and matches. I'd like to expose this model using GraphQL, using Graphene. This is what I have come up with:
import graphene
from graphene_django import DjangoObjectType
from . import models
class TournamentType(DjangoObjectType):
class Meta:
model = models.Tournament
exclude_fields = ('id',)
class EventType(graphene.Interface):
tournament = graphene.Field(TournamentType, required=True)
slug = graphene.String(required=True)
class PracticeEventType(DjangoObjectType):
class Meta:
model = models.PracticeEvent
interfaces = (EventType,)
exclude_fields = ('id',)
class MatchEventType(DjangoObjectType):
class Meta:
model = models.MatchEvent
interfaces = (EventType,)
exclude_fields = ('id',)
extra_types = {PracticeEventType, MatchEventType}
class Query(graphene.ObjectType):
tournaments = graphene.List(TournamentType)
events = graphene.List(EventType)
# ... resolvers ...
schema = graphene.Schema(
query=Query,
types=schema_joust.extra_types,)
So far, so good; I can query events { ... } directly, and even the tournament is available. However, as there is no DjangoObjectType with model = models.Event, I can't query tournaments { events {...} }...
How can I fix this? I can't make EventType a DjangoObjectTpe, and I don't know to add the events field after the fact.
On their own, EventType.tournament and TournamentType.events aren't so hard. The first one is shown in the question, and the second one can be implemented like this:
class EventType(graphene.Interface):
slug = graphene.String(required=True)
class TournamentType(DjangoObjectType):
class Meta:
model = models.Tournament
exclude_fields = ('id',)
events = graphene.List(EventType)
def resolve_events(self, info):
return self.events.all()
graphene-django doesn't recognize the relationship, but declaring and resolving the field manually does the trick. To also get the reverse-field, which would work if we didn't need to reference TournamentType, I digged into graphene-django and found graphene_django.converter.convert_django_field_with_choices. This lets us define the field like this:
import graphene
from graphene_django import DjangoObjectType, converter, registry
from . import models
class EventType(graphene.Interface):
tournament = converter.convert_django_field_with_choices(
models.Event.tournament.field, registry.get_global_registry())
slug = graphene.String(required=True)
Perhaps a Union type is what you want, combined with declaring EventType explicitly to inherit from an interface:
import graphene
# Rename your existing EventType to EventTypeInterface and redefine like
class EventType(DjangoObjectType):
class Meta:
model = Event
interfaces = [EventTypeInterface]
class EventUnionType(graphene.Union):
#classmethod
def resolve_type(cls, instance, info):
if isinstance(instance, MatchEvent):
return MatchEventType
elif isinstance(instance, PracticeEvent):
return PracticeEventType
return EventType
class Meta:
types = [MatchEventType, PracticeEventType, EventType]

Django admin GenericForeignKey widget

I'm creating a Django app where all the models can be related to each other in an order set by the user. I'm setting all this up using GenericForeignKeys. The kicker is that I need to be able to support multiple collections of these types of relationship/admin. So one object can have a more than one collection of related objects.
Does anyone know of a good GenericForeignKey widget for this situation? Preferably, it would be an autocomplete search that populates the admin form since I can end up having a large number of objects.
Here is the code for my app to get a better idea of what I mean.
from django.contrib import admin
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django import forms
# Models
class Base(models.Model):
title = models.CharField(max_length=255)
class Meta:
abstract = True
def __unicode__(self):
return self.title
class Related(Base):
""" A generic relationship model for relating resources.
"""
order = models.IntegerField(blank=True, null=True)
limit = models.Q(model = 'Apple') | models.Q(model = 'Orange') | models.Q(model = 'Pear')
content_type = models.ForeignKey(ContentType, related_name="related_%(class)s")
object_id = models.PositiveIntegerField(db_index=True)
object = generic.GenericForeignKey()
related_content_type = models.ForeignKey(ContentType, related_name="related_related_%(class)s", limit_choices_to = limit)
related_object_id = models.PositiveIntegerField(db_index=True)
related_object = generic.GenericForeignKey('related_content_type', 'related_object_id')
class Meta:
ordering = ('order',)
abstract = True
def __unicode__(self):
return self.object.title
class FreshFruit(Related):
pass
class OldFruit(Related):
pass
class Apple(Base):
pass
class Orange(Base):
pass
class Pear(Base):
pass
# Admin classes
class FreshFruitInline(generic.GenericStackedInline):
model = FreshFruit
extra = 1
# Admin classes
class OldFruitInline(generic.GenericStackedInline):
model = OldFruit
extra = 1
class AppleAdmin(admin.ModelAdmin):
inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Apple, AppleAdmin)
class OrangeAdmin(admin.ModelAdmin):
inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Orange, OrangeAdmin)
class PearAdmin(admin.ModelAdmin):
inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Pear, PearAdmin)
I've searched and searched, and found widgets that do this for a ManyToMany relationship, but nothing for my situation.
Thanks for taking the time to look at this.
Have a look at Grappelli's generic foreign key widget, which works well:
django-grappelli/generic_2_2