I am learning Django 2.2, I am trying to display the user name of my model named 'Profile' but instead I have : Profile objet(3), Profile Object(4)
Here is the code in Profile Apps=> models.py :
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import FileExtensionValidator
# Create your models here.
class Profile(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
website = models.URLField(blank=True)
avatar = models.ImageField(upload_to='uploads/img', validators=[FileExtensionValidator(allowed_extensions=['png'])], blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
#property
def get_created(self):
return self.created.strftime("%m/%d/%Y, %H:%M:%S")
def __str__(self):
return "{}-{}".format(self.name, self.get_created)
Here is the code in Profile Apps=> admin.py :
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
Here is the code in Profile Apps=> init.py :
default_app_config = "profiles.apps.ProfilesConfig"
I have this, instead of user name:
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
but i see Groups and Users model by default if i try to register my model in app/admin.py using admin.site.register(model_name) if i try to registered the default Groups and User it will also not working for me.
CODE
Directory 'app/admin.py'
from django.contrib import admin
from app.models import Contact
admin.site.register(Contact)
Directory 'app/models.py'
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
gender = models.CharField(max_length=50,choices=('female','Female')
('male','Male')))
email = models.EmailField(max_length=100)
info = models.CharField(max_length=100)
phone = models.IntegerField()
image = models.ImageField(blank=true,upload_to='images/')
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
Change the import from "app.models" to just ".models" because they are in the same directory and see
The documentation for django-import-export is a bit weak on how to configure the admin to import from a spreadsheet. Does anyone have a full example?
This is not a fully complete module. But you can understand how it should be.
resources.py file
from import_export import resources
from .models import edxUser
class edxUserResource(resources.ModelResource):
class Meta:
model = edxUser
#skip_unchanged = True
#report_skipped = True
#if you want to exclude any field from exporting
exclude = ('id','edx_anonymized_id')
fields = ('id', 'edx_id', 'edx_anonymized_id', 'edx_email', 'edx_name', 'time_created', 'created_by')
#Order of the export fields
export_order = ('edx_id', 'edx_email')
admin.py file
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import edxUser
from resources import edxUserResource
#admin.register(edxUser)
class edxUserAdmin(ImportExportModelAdmin):
resource_class = edxUserResource
models.py file
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
class edxUser(models.Model):
edx_id = models.IntegerField('edX user id', blank=True, null=True)
edx_anonymized_id = models.IntegerField("edX anonymized user id", blank=True, null=True)
edx_email = models.EmailField('edx user email', max_length=75, blank=True)
edx_name = models.CharField('edx name', max_length=75, blank=True, null=True)
time_created = models.DateField('Created time', blank=True, null=True)
created_by = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
def __unicode__(self):
return str(self.edx_id)
Here's how to do it, assuming that the column names in the spreadsheet are Title and Field one. This example assumes that the model instances will be created afresh every import (rather than being updated via a primary key).
from django.contrib import admin
from import_export.admin import ImportMixin
from import_export import resources, fields
from .models import MyModel
class MyModelResource(resources.ModelResource):
title = fields.Field(attribute='title',
column_name='Title')
field_one = fields.Field(attribute='field_one',
column_name='Field one')
def get_instance(self, instance_loader, row):
# Returning False prevents us from looking in the
# database for rows that already exist
return False
class Meta:
model = MyModel
fields = ('title', 'field_one')
export_order = fields
class MyModelAdmin(ImportMixin, admin.ModelAdmin):
resource_class = MyModelResource
admin.site.register(MyModel, MyModelAdmin)
I have installed MPTT for Django, put it in "installed apps," set up my files, and synced my database. My model shows in admin, but when I click save after trying to add a category I get the following error:
DatabaseError at /admin/myapp/category/add/
relation "django_admin_log" does not exist
LINE 1: INSERT INTO "django_admin_log" ("action_time", "user_id", "c...
Here are my files:
Models:
from django.db import models
from django.contrib.auth.models import User
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
user = models.ForeignKey(User)
name = models.CharField(max_length=30, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
def __unicode__(self):
return self.name
Admin:
from django.contrib import admin
from myapp.models import Category
from mptt.admin import MPTTModelAdmin
admin.site.register(Category, MPTTModelAdmin)
Is it possible, that you've enabled the admin logs feature without running syncdb afterwards? Here you'll find a very similar question.
from django.db import models
from django.contrib.auth.models import User
class MySiteProfile(models.Model):
# This is the only required field
user = models.ForeignKey(User, unique=True)
# The rest is completely up to you...
favorite_band = models.CharField(max_length=100, blank=True)
favorite_cheese = models.CharField(max_length=100, blank=True)
lucky_number = models.IntegerField()
The problem is that
User._meta.admin and MySiteProfile._meta.admin both return NoneType. I've dropped and recreated whole database, but no new fields appeared in admin panel; AUTH_PROFILE_MODULE is set.
There are a few ways you can make your MySiteProfile show up in the admin. One is to simply register your model with the admin, and it will show up under the app name it resides in.
Another is to unregister the contrib user from admin and instead load yours:
#admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_app.models import MySiteProfile
class MySiteProfileAdmin(UserAdmin):
def __init__(self,*args,**kwargs):
super(MySiteProfileAdmin).__init__(*args,**kwargs)
fields = list(UserAdmin.fieldsets[0][1]['fields'])
fields.append('favorite_band')
fields.append('favorite_cheese')
fields.append('lucky_number')
UserAdmin.fieldsets[0][1]['fields']=fields
admin.site.unregister(User)
admin.site.register(MySiteProfile, MySiteProfileAdmin)
There are quite a few articles around on this topic, but hope that helps you out.