How do I find an object with relationship and how to save an object in relationship with Django Rest Framework?
I looked in the documentation and found something similar to this
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'profile')
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('nome_empresa', 'cnpj')
profile = ProfileSerializer()
NameError: name 'ProfileSerializer' is not defined
Python is not a compiled language. Everything is created/done at runtime.
At the following line:
profile = ProfileSerializer()
you are using the ProfileSerializer but at this point it is not created yet. It is created a little later. To fix this, you need to put it before the UserSerializer class:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('nome_empresa', 'cnpj')
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'profile')
Hope it helps!
Related
models.py
class UserProfile(User):
bio = models.TextField(blank=True, null=True)
pfp = models.ImageField(verbose_name='Profile Picture', blank=True, null=True, upload_to="images/profile")
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control", "placeholder":"example#example.com"}))
first_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
last_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
pfp = forms.ImageField(required=False, widget=forms.FileInput(attrs={"class":"form-control"}))
bio = forms.CharField(required=False, widget=forms.Textarea(attrs={"class":"form-control", 'rows':5, "placeholder":"Write something about yourself..."}))
class Meta:
model = UserProfile
fields = ['first_name', 'last_name', 'username', 'email', "pfp", "bio"]
When creating the user, the two newly added fields (bio and pfp) are not being saved in admin/auth/user, so my question is, is it possible to add those fields to the admin users database?
views.py
class SignUpView(CreateView):
form_class = UserRegisterForm
template_name = "registration/signup.html"
success_url = reverse_lazy("login")
are not being saved in admin/auth/user
Indeed, these are safed on the UserProfile model.
You thus can make a ModelAdmin for this:
# app_name/admin.py
from django.contrib import admin
from app_name.models import UserProfile
#admin.register(UserProfile)
class AuthorAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'username', 'email', 'pfp', 'bio')
Then the details can be seen in the admin/app_name/userprofile section.
Create a custom user model by inheriting the AbstractUser and adding extra fields needed. After that, register that custom user model by assigning it to AUTH_USER_MODEL.
Check here for detailed implementation.
I am using Django 2.2 for a project, I want to remove the currently displayed image link from the user update form as shown in the image below, how do I do this?
image
forms.py
from .models import Profile
class CreateUserForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
help_texts = {
'username': None,
}
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['profile_pic']
You can try to change ImageField to FileInput using widgets. I use Django version 4.1.1 and it works for me.
# forms.py
class ProfileUpdateForm(forms.ModelForm):
profile_pic = forms.ImageField(widget=forms.FileInput)
class Meta:
...
so I'm new to Django and I'm creating an API using djangorestframework
When creating the serializers I encountered a problem that I can't find a way to go around it.
I have 2 models, Site and Article
The site can have many articles
an article can have one site
I did the relationship in the models and everything looks fine.
When tried to serialize the information I started with the SiteSerializer which had a line to get the ArticleSerializer and had a related name of 'articles' (also the name of the variable) and it worked
But when trying to serialize the SiteSerializer inside the ArticleSerializer with the same way it cannot be done because the order of the classes, it cannot reference to it when it's yet to be created
CODE:
class ArticleSerializer(serializers.ModelSerializer):
site = SiteSerializer(many=false)
class Meta:
model = Article
fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site')
class SiteSerializer(serializers.ModelSerializer):
articles = ArticleSerializer(many=True)
class Meta:
model = Site
fields = ('id', 'name', 'url', 'articles')
I can't reference to SiteSerializer when it's below, but it will be the opposite if I switch them up.
What can I do in this situation, is there another way to serialize different models with many to one or many to many relationships?
You are going to have an infinite loop (Site > Articles > Site > Article, ...).
You can create 4 serializers :
class NestedArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site')
class SiteSerializer(serializers.ModelSerializer):
articles = NestedArticleSerializer(many=True)
class Meta:
model = Site
fields = ('id', 'name', 'url', 'articles')
class NestedSiteSerializer(serializers.ModelSerializer):
class Meta:
model = Site
fields = ('id', 'name', 'url')
class ArticleSerializer(serializers.ModelSerializer):
site = NestedSiteSerializer()
class Meta:
model = Article
fields = ('id', 'title', 'url', 'summary', 'img', "published_date", 'site')
I have two models, the default User model and a UserProfile model that extends the user model:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='UserProfile')
universidad = models.ForeignKey(Universidad, related_name ='universidad')
group_admin = models.ManyToManyField(Group, related_name = 'group_admin')
I'm trying to obtain a user field that allows to GET, PUT and POST data with this format:
'username' = 'foo'
'password' = 'password'
'email' = 'a#b.com'
'universidad' = 'Harvard'
'group_admin' = [1] #list of groups id
I have used nested serializers but it's read only.
I also proved this solution, but i obtain a KeyError: 'universidad'.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'password', 'email','universidad', 'group_admin')
write_only_fields = ('password',)
Any help would be appreciated.
The KeyError occurs because you are trying to use the reverse relationship of UserProfile in the serializer. Reverse relationships aren't automatically included in HyperLinkedModelSerializers. See the docs for more information and try:
fields = ('url', 'username', 'password', 'email','UserProfile__universidad', 'group_admin')
Hello I'm trying to learn django and django-restful-framework.
I was wondering can I add more fields to User(contrib.auth) like so
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'firstName', 'lastName', 'ssn', 'email',
'phone', 'jobTitle','image', 'isActive','groups')
This gives me error on firstName. I also tried to tie this with person, but no luck either
class PersonSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
class Meta:
model = Person
fields = ('url', 'firstName', 'lastName', 'ssn', 'owner')
class UserSerializer(serializers.HyperlinkedModelSerializer):
persons = serializers.ManyHyperlinkedRelatedField(view_name='person-detail')
class Meta:
model = User
fields = ('url', 'username', 'persons')
I'm trying to make this so that the user can register with more information.
I suggest you head to the Django docs on extending and/or replacing the existing user model.
Once you've got what you want as the model level see if you can serialize that to your needs. (If not post again.)
The field names are lowercase with underscores. E.g it should be first_name and not firstName.