How to show all group content if user is a group member - python

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)

Related

Why am I getting an integer precision error when I run: heroku run python manage.py migrate

I have deployed a Django app on Heroku, but I want to migrate to PostgreSQL, so I am following a video tutorial on YouTube on how to do that. In the tutorial, we have to run Heroku run python manage.py migrate to migrate my current SQLite database to the PostgreSQL one on Heroku. I keep getting this error:
psycopg2.errors.CannotCoerce: cannot cast type date to double precision
LINE 1: ...cted" TYPE double precision USING "lastInteracted"::double p...
Here is my models.py file. I am pretty sure that the problem is in the Conversation model with the lastInteracted variable, but I do not know why it is happening.
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.fields import CharField
from django.db.models.fields.files import FileField, ImageField, ImageFieldFile
from django.utils.timezone import localtime, now
from datetime import datetime
import time
import os
import sys
from django.core.files.base import File
from django.core.files.uploadedfile import InMemoryUploadedFile
class User(AbstractUser):
userType = models.CharField(max_length=20, default="student")
profile_pic = models.ImageField(
null=True, blank=True, default="blankUserIcon.svg")
class Classroom(models.Model):
name = models.CharField(max_length=100, default="Classroom")
students = models.ManyToManyField(User, blank=True)
teacher = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="teacher")
code = models.CharField(max_length=20)
subject = models.CharField(max_length=50, default="")
theme = models.CharField(max_length=20, default="cardBlue")
class Comment(models.Model):
date = models.DateTimeField(default=datetime.now())
text = CharField(max_length=5000, default="")
commenter = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="commenter", null=True)
class Announcement(models.Model):
classroom = models.ForeignKey(
Classroom, on_delete=models.CASCADE, related_name="classroom", null=True)
body = CharField(max_length=20000, default="")
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="creator", null=True)
date = models.DateTimeField(default=datetime.now())
comments = models.ManyToManyField(Comment, blank=True)
class Text(models.Model):
sender = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="sender")
reciever = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="reciever")
date = models.DateTimeField(default=datetime.now())
text = CharField(max_length=1000, default="")
class Conversation(models.Model):
user1 = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="user1")
user2 = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="user2")
texts = models.ManyToManyField(Text, blank=True)
lastInteracted = models.IntegerField(default=-1)
readUser1 = models.BooleanField(default=True)
readUser2 = models.BooleanField(default=True)
class FileModel(models.Model):
file = models.FileField(blank=True)
def name(self):
return os.path.basename(self.file.name)
class Submission(models.Model):
resubmitted = models.BooleanField(default=False)
grade = models.IntegerField(default=-1)
files = models.ManyToManyField(FileModel, blank=True)
description = models.CharField(max_length=1000, default="")
user = models.ForeignKey(
User, null=True, related_name="submitter", on_delete=models.CASCADE)
date = models.DateField(default=datetime.now())
class Assignment(models.Model):
givenFiles = models.ManyToManyField(FileModel, blank=True)
title = models.CharField(max_length=500, default="")
description = models.CharField(max_length=20000, default="")
duedate = models.DateTimeField()
submissions = models.ManyToManyField(Submission, blank=True)
classroom = models.ForeignKey(
Classroom, on_delete=models.CASCADE, related_name="belongingToClassroom", null=True)
class MCanswer(models.Model):
answer = models.IntegerField(default=-1)
class MultipleChoiceQuestion(models.Model):
question = models.CharField(max_length=1000)
option1 = models.CharField(max_length=1000)
option2 = models.CharField(max_length=1000)
option3 = models.CharField(max_length=1000)
option4 = models.CharField(max_length=1000)
correctOption = models.IntegerField(default=1)
selectedOption = models.IntegerField(default=-1)
class QuizSubmission(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
date = models.DateField(default=datetime.now())
grade = models.IntegerField(default=0)
answers = models.ManyToManyField(MCanswer, blank=True)
class Quiz(models.Model):
name = models.CharField(max_length=1000, default="Untitled Quiz")
submissions = models.ManyToManyField(QuizSubmission, blank=True)
questions = models.ManyToManyField(MultipleChoiceQuestion, blank=True)
duedate = models.DateTimeField(null=True)
classroom = models.ForeignKey(
Classroom, null=True, on_delete=models.CASCADE)
To clarify, the lastInteracted variable holds the current time since epoch time in seconds. I verified this and it is indeed less than 2.47B which is the integer max value.
And here are the code snippets of the times where I try to use this lastInteracted variable:
conversation = Conversation()
conversation.lastInteracted = int(time.time())
and
convs = (Conversation.objects.filter(
Q(user1=request.user) | Q(user2=request.user))).order_by('-lastInteracted')
I reset the database by deleting it and deleting the migrations folder as well. I also removed the default=datetime.now() from all of the models and these changes seemed to have worked. Not sure if this will help anyone, but putting an answer here anyways.

Django admin queryset foreign key to user django-allauth

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 can't create another ForeignKey using Django

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

How to display multiple objects from fields in Django Admin

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.

Class has no atribute 'urls' - Django models.ImageField() can't migrate

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)

Categories