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.
Related
I have an e-commerce development and I'm looking to send an email to the client from the admin site, I can´t the queryset correclty to do this. I have the following model:
models.py:
class Orden(models.Model):
cliente = models.ForeignKey(
User, on_delete=models.CASCADE, verbose_name='Usuario')
productos = models.ManyToManyField(OrdenProducto)
fecha_orden = models.DateTimeField(auto_now_add=True)
completada = models.BooleanField(default=False, null=True, blank=True)
id_transaccion = models.CharField(max_length=20, null=True)
correo_enviado = models.BooleanField(default=False, null=True, blank=True)
datos_pedido = models.ForeignKey(
'DatosPedido', on_delete=models.SET_NULL, blank=True, null=True)
pago = models.ForeignKey(
'Pago', on_delete=models.SET_NULL, blank=True, null=True)
cupon = models.ForeignKey(
'Cupon', on_delete=models.SET_NULL, blank=True, null=True)
class Meta:
verbose_name_plural = "Orden"
def __str__(self):
return self.cliente.username
cliente has a foreign key to the User model and I want to get the email address, I have tried many ways but I just can´t get it.
admin.py:
class OrdenAdmin(admin.ModelAdmin):
list_display = ('cliente', 'completada', 'correo_enviado')
actions = ['enviar_correo']
def enviar_correo(self, request, queryset):
queryset.update(correo_enviado=True)
a = queryset.get(cliente=self.user.email)
send_mail('test', 'test', 'xxxxxx#mail.com',
['a], fail_silently=True)
You can try iterating the queryset to access the specific data in the rows.
Try the following code.
class OrdenAdmin(admin.ModelAdmin):
list_display = ('cliente', 'completada', 'correo_enviado')
actions = ['enviar_correo']
def enviar_correo(self, request, queryset):
queryset.update(correo_enviado=True)
for obj in queryset:
email = obj.cliente.email
send_mail('test', 'test', email,
['a], fail_silently=True)
I hope this code helps you
Unless you have extended the default user model or have created Your Own user model, django default user model does not have an email field.
So if you have extended or created Your Own model you can do
myordenobj.cliente.email
But if you're using the default user model and your username is an email then do.
myordenobj.cliente.username
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 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 new to both django and python and currently trying to implement a REST api using django-rest-framework. I know there are a lot of alike questions but they are serializing objects using .json, and i am not.
I have 2 models captain and boat as follows:
//models.py
from django.db import models
class Captain(models.Model):
name = models.CharField(max_length=255, blank=False, unique=False)
last_name = models.CharField(max_length=255, blank=False, unique=False)
government_id = models.CharField(max_length=55, blank=False, unique=True)
company_name = models.CharField(max_length=255, blank=False, unique=False)
phone_number = models.CharField(max_length=55, blank=False, unique=False)
tax_id = models.CharField(max_length=55, blank=False, unique=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
class Boat(models.Model):
captain = models.ForeignKey(Captain, on_delete=models.CASCADE, null=True, blank=True, related_name='boats')
name = models.CharField(max_length=55, blank=False)
journey_type = models.CharField(max_length=55, null=True, blank=True)
category = models.CharField(max_length=55, null=True, blank=True)
passenger_capacity = models.IntegerField()
crew_count = models.IntegerField()
have_ac = models.IntegerField(default=0)
year_built = models.DateField
year_restored = models.DateField(blank=True)
engine = models.CharField(max_length=255, blank=True, null=True)
generator = models.CharField(max_length=255, blank=True, null=True)
width = models.CharField(max_length=255, null=True)
height = models.CharField(max_length=255, null=True)
length = models.CharField(max_length=255, null=True)
wc_count = models.IntegerField(null=True)
master_cabin_count = models.IntegerField(null=True)
standart_cabin_count = models.IntegerField(blank=False, null=False)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
As you can see each boat has one captain and one captain can have many boats. So in database there is a captain_id field for Boat table. I have defined two serializers for each model:
//serializers.py
from rest_framework import serializers
from .models import Captain, Boat
class CaptainSerializer(serializers.ModelSerializer):
class Meta:
model = Captain
fields = ('id', 'name', 'last_name', 'government_id', 'company_name', 'phone_number', 'tax_id', 'date_created', 'date_modified','boats')
class BoatSerializer(serializers.ModelSerializer):
captain = serializers.PrimaryKeyRelatedField(many=False, read_only=True)
class Meta:
model = Boat
fields = ('id', 'captain', 'name', 'journey_type', 'category', 'passenger_capacity', 'crew_count', 'have_ac', 'year_built', 'year_restored', 'wc_count', 'standart_cabin_count')
Then i have defined views for each model.
//views.py
from django.shortcuts import render
from rest_framework import generics
from .serializers import CaptainSerializer, BoatSerializer
from .models import Captain, Boat
class CaptainCreateView(generics.ListCreateAPIView):
queryset = Captain.objects.all()
serializer_class = CaptainSerializer
def perform_create(self, serializer):
serializer.save()
class CaptainDetailsView(generics.RetrieveUpdateDestroyAPIView):
lookup_field = 'pk'
serializer_class = CaptainSerializer
queryset = Captain.objects.all()
class BoatCreateView(generics.ListCreateAPIView):
queryset = Boat.objects.all()
serializer_class = BoatSerializer
def perform_create(self, serializer):
serializer.save()
When i go to page localhost:port/captains/ (or /GET/captains from postman) i can have captain models including the boats he has.
But The problem is : when i go to localhost:port/boats (or postman) it gives,
Object of type type is not JSON serializable
Exception Type: TypeError at /boats/
Exception Value: Object of type type is not JSON serializable
Any ideas how can i fix this? Thanks in advance.
I think the year_built field in the Boat model is not well defined (you're assigning the class DateField but not creating an instance of it):
class Boat(models.Model):
year_built = models.DateField # should be models.DateField()
I've been stuck on this for a few days (new to django) and can't figure out how to update skills for a specific user model using a ManyToManyField, while simultaneously updating a skill model containing a list of skills. Currently when I enter a value in my SkillForm, it updates the skill model properly and creates a dropdown list of skills for a given CustomUser in the admin. However, I can't figure out how to assign a SPECIFIC skill to a particular user. Any help is appreciated.
models.py:
class Skill(models.Model):
name = models.CharField(max_length =50, null=True, default='')
def __str__(self):
return self.name
class CustomUserManager(UserManager):
pass
class CustomUser(AbstractUser):
objects = CustomUserManager()
skills = models.ManyToManyField(Skill, null=True, blank=True)
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
admin.py:
class SkillsInline(admin.StackedInline):
model = CustomUser.skills.through
class SkillAdmin(admin.ModelAdmin):
inlines = [SkillsInline ,]
UserAdmin.fieldsets += ('Custom fields set', {'fields': ('position', 'bio', )}),
class CustomUserAdmin(UserAdmin):
model = CustomUser
add_form = CustomUserCreationForm
form = EditProfile
inlines = [SkillsInline ,]
admin.site.register(CustomUser, CustomUserAdmin)
forms.py:
class SkillForm(forms.ModelForm):
name = forms.CharField()
class Meta:
model = Skill
fields =('name' ,)
def clean(self):
cleaned_data = super().clean()
name = cleaned_data.get('name')
I see somes problem here :
class CustomUser(AbstractUser):
objects = CustomUserManager()
skills = models.ManyToManyField(Skill, null=True, blank=True)
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
When you define an AbstractUser` class, it's mean for Django Authentification purpose, see the doc here., dont do that because it's better to have an unique entry (each user have an unique entry, so you can login each one).
In your system you dont have unique CustomUser, here is a solution IMO:
class User(AbstractUser):
email = models.EmailField(_('email'), unique=True)
class UserAction(models.Model):
objects = CustomUserManager()
user = models.ForeignKey(User, verbose_name="User")
skills = models.ManyToManyField(Skill, null=True, blank=True)
position = models.CharField(max_length =50, null=True, default='')
bio = models.CharField(max_length=300, null=True, default='')
class Skill(models.Model):
name = models.CharField(max_length =50, null=True, default='')
def __str__(self):
return self.name
You now have an unique User, a list of UserAction that have a related Skill
user = User.objects.create(email='my#email.com')
skill = Skill.objects.create(name="shadow step")
user_action = UserAction.objects.create(user=user, skill=skill, position='HERE', bio='10')
Is that what you needed ?