I try to add ImageField but I get error.
Code I am working with:
#models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core.exceptions import ValidationError
import datetime
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
verified = models.BooleanField(default=False)
status = models.CharField(max_length=200, null=True, blank=True)
country = models.CharField(max_length=100, null=True, blank=True)
province = models.CharField(max_length=100, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
date_of_birth = models.DateField(null=True, blank=True)
class ProfileImages(models.Model):
profile = models.ForeignKey(Profile, related_name='images')
image = models.ImageField()
#admin.py
from django.contrib import admin
from .models import *
class ProfileImagesInline(admin.TabularInline):
model = ProfileImages
extra = 3
class ProfileAdmin(admin.ModelAdmin):
inlines = [ ProfileImagesInline, ]
admin.site.register(Profile, ProfileImages)
This throws:
'Attribute Error' ProfileImages has no attrbute 'urls'. I don't know why. Any ideas?
The second parameter to admin.site.register is the ModelAdmin class. You are passing a model there instead.
admin.site.register(Profile, ProfileAdmin)
Related
I'm working on a small Django Project, I would like to create a second ForeignKey in the same model, but it doesn't work after the migration I don't see the field in my table contact,
this is my Models ( i have a Custom User Model and work fine )
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
username = models.CharField(max_length=255, unique=False, blank=True, null=True)
email = models.EmailField('email address', unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
This is my class Contact ( as you can see I try to add a foreign key called user )
from django.db import models
from list.models import List
from users.models import CustomUser
class Contact(models.Model):
list = models.ForeignKey(List, on_delete=models.DO_NOTHING, related_name="list")
user = models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING, related_name="user")
greeting = models.CharField(null=True, blank=True, max_length=255)
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=60)
title = models.CharField(null=True, blank=True, max_length=60)
company = models.CharField(null=True, blank=True,max_length=60)
phone = models.CharField(null=True, blank=True, max_length=60)
def __str__(self):
return self.first_name
What i try to do :
Each user can have Contacts
Each Contact depend on a list
I don't know if this fixes the problem but
you should not name your model field "list"
because "list" is one of python's reserved keywords. When you redefine it Unexpected things can happen
I have a website working perfectly in Django for me, I can add and delete instances of models as I want. However, if someone else tries to add an instance with the exact same admin account, the page shows "Server Error 500".
I am using the default SQLite settings for django.
models.py:
from django.db import models
from datetime import datetime
# Create your models here.
class Receita(models.Model):
titulo_receita = models.CharField(max_length=200);
resumo_receita = models.CharField(max_length=255, default='')
tempo_receita = models.CharField(max_length=200, default='');
rendimento_receita = models.CharField(max_length=200, default='');
imagem_preview = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png')
conteudo_receita = models.TextField();
data_receita = models.DateTimeField('Data publicação', default=datetime.now());
def __str__(self):
return self.titulo_receita;
class Produto(models.Model):
nome = models.CharField(max_length=200);
desc = models.TextField()
# desc = models.CharField(max_length=255, default='');
imagem = models.ImageField(upload_to='uploads/%Y/%m/%d/', default='static/default_image.png')
info1 = models.CharField(max_length=255, default='', blank=True)
cod1 = models.CharField(max_length=255, default='', blank=True)
info2 = models.CharField(max_length=255, default='', blank=True)
cod2 = models.CharField(max_length=255, default='', blank=True)
info3 = models.CharField(max_length=255, default='', blank=True)
cod3 = models.CharField(max_length=255, default='', blank=True)
def __str__(self):
return self.nome;
admin.py:
from django.contrib import admin
from .models import Receita
from .models import Produto
from tinymce.widgets import TinyMCE
from django.db import models
# Register your models here.
class ReceitaAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TinyMCE()}
}
admin.site.register(Receita, ReceitaAdmin)
admin.site.register(Produto)
i am new to programming and doing a small project(simple bug tracker) using django-rest-framework.
so far i have a Bugs model and if the user is logged in, he can see the bugs reported by him.Now i created a new model called Team in which one can make a team by adding email ids (i used MultiEmailField to store the list of emails).My requirement is that if the logged in user's email is present in any Team, the user should be able to see all the team members activities.I dont know how to accomplish this .please help me.Thanks in advance
#bugs model#
from django.db import models
from django.contrib.auth.models import User
class Bugs(models.Model):
issueId = models.PositiveIntegerField(primary_key=True)
projectName = models.CharField(max_length=300)
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100, unique=True)
description = models.TextField(max_length=3000, blank=True)
actualResult = models.TextField(max_length=1000, blank=True)
expectedResult = models.TextField(max_length=1000, blank=True)
status = models.TextField(max_length=30, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(
User, related_name="bugs", on_delete=models.CASCADE, null=True)
#team model#
from django.db import models
from multi_email_field.fields import MultiEmailField
from django.contrib.auth.models import User
class Team(models.Model):
projectTitle = models.CharField(max_length=300, blank=False, null=True)
durationFrom = models.DateField(null=True)
durationEnd = models.DateField(null=True)
teamMembers = MultiEmailField()
owner = models.ForeignKey(
User, related_name="team", on_delete=models.CASCADE, null=True)
#api.py#
from bugs.models import Bugs
from rest_framework import viewsets, permissions
from .serializers import BugsSerializer
class BugsViewSet(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = BugsSerializer
def get_queryset(self):
return self.request.user.bugs.all()
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
I am a bit stumped as to how I can add multiple access_token and items_ids in Django Admin. The models and apps involved are as follows. This is my first post so please forgive if it isn't in proper format.
Trans/models.py
class Exchange(models.Model):
created = models.DateTimeField()
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='token', on_delete=models.CASCADE)
access_token = models.CharField(max_length=300, blank=True, default='')
item_id = models.CharField(max_length=300, blank=True, default='')
request_id = models.CharField(max_length=300, blank=True, default='')
class Meta:
ordering = ('item_id',)
I have setup a userprofile section for the admin:
Users/models.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE)
avatar_url = models.CharField(max_length=256, blank=True, null=True)
dob = models.DateField(verbose_name="dob", blank=True, null=True)
public_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='public_token')
access_token = models.CharField(max_length=100, blank=True, null=True, verbose_name='access_token')
item_id = models.CharField(max_length=100, blank=True, null=True, verbose_name='item_ID')
just_signed_up = models.BooleanField(default=True)
def __str__(self):
return force_text(self.user)
class Meta():
db_table = 'user_profile'
users/forms.py
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('user', 'public_token', 'access_token', 'item_id',)
users/admin.py
class UserProfileAdmin(admin.ModelAdmin):
search_fields = ('user', 'dob', 'public_token', 'access_token', 'item_id',)
ordering = ('user',)
list_select_related = ('user',)
admin.site.register(UserProfile, UserProfileAdmin)
class UserProfileAdminInline(admin.TabularInline):
model = UserProfile
I'm really just stumped as I tried making many to many field but couldnt seem to link correctly and or the process broke when testing in a sandbox environment. Any help would be greatly appreciated! In my case I need to record multiple access_tokens and item_ids for each user.
It's a little bit confusing what you are asking...particularly the way that your data model is setup....but I'm going to make a couple of assumptions in my answer (it would be helpful to better understand what you are trying to do at a high level).
I think what you are wanting to do is to be able to configure multiple Exchange objects per user profile...in which case I would set things up this way:
1. The related_name field on the FK to the user profile in the exchange model will be how you access multiple exchanges...so in this case you probably want a pluralized name.
2. To be able to edit multiple in the Django Admin you will need to setup an InlineAdmin object.
3. The CharFields that are actually ON the UserProfile will only ever be single fields...if you want multiple then you need to move them to another related object (like the Exchange model).
4. I don't think what you want here is a ManyToMany as that would imply user's would be sharing these tokens and item ids (or Exchanges?)...but maybe that is what you want...in which case you should change the ForeignKey to UserProfile from the Exchange model to a ManyToManyField. The rest of this post assumes you don't want that.
trans/models.py
from django.db import models
from django.conf import settings
class Exchange(models.Model):
class Meta:
ordering = ('item_id', )
created = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='exchanges', on_delete=models.CASCADE)
access_token = models.CharField(max_length=300, blank=True)
item_id = models.CharField(max_length=300, blank=True)
request_id = models.CharField(max_length=300, blank=True)
users/models.py
from django.db import models
from django.conf import settings
class UserProfile(models.Model):
class Meta:
db_table = 'user_profile'
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE)
avatar_url = models.CharField(max_length=256, blank=True)
dob = models.DateField(verbose_name="dob", blank=True, null=True)
public_token = models.CharField(max_length=100, blank=True, null=True)
access_token = models.CharField(max_length=100, blank=True, null=True)
item_id = models.CharField(max_length=100, blank=True, null=True)
just_signed_up = models.BooleanField(default=True)
def __str__(self):
return force_text(self.user)
users/admin.py
from django.contrib import admin
from trans.models import Exchange
from users.models import UserProfile
class ExchangeAdminInline(admin.TabularInline):
model = Exchange
class UserProfileAdmin(admin.ModelAdmin):
inlines = (ExchangeAdminInline, )
search_fields = ('user', 'dob', 'public_token', 'access_token', 'item_id', )
ordering = ('user', )
list_select_related = ('user', )
admin.site.register(UserProfile, UserProfileAdmin)
There is a lot that you can do to configure the inlines to behave how you want...but that's the basics.
I have an error in django authentication with a user model that extends from AbstracBaseUser and its id is a foreign key from another table.
views.py
ModelsUser
ModelPeople
from django.db import models
from apps.area.models import Area
from apps.company_dependence.models import CompanyDependence
from apps.position.models import Position
class People(models.Model):
documentPeople = models.AutoField(primary_key=True, null=False)
fullname = models.CharField(max_length=50)
phone = models.IntegerField()
address = models.CharField(max_length=50)
email = models.CharField(max_length=50)
codeArea = models.ForeignKey(Area, null=True, blank=True, on_delete=models.CASCADE)
codePosition = models.ForeignKey(Position, null=True, blank=True, on_delete=models.CASCADE)
codeCompaDepen = models.ForeignKey(CompanyDependence, null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return '{}'.format(self.fullname)
in the settings I put AUTH_USER_MODEL = 'user.User'