I want the boolean is_super field to change from True to False after the given timeout - python-3.x

`is_super is a user whose account expires after 30 days and is_super field should be false. I tried many methods, but they never false this field after the end of the time. I can't think of a way or I don't know where we made a mistake.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin,AbstractUser
from .managers import UserManager
from datetime import datetime,timedelta
from django.utils import timezone
# Create your models here.
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=100, unique=True)
phone = models.CharField(max_length=11, unique=True)
full_name = models.CharField(max_length=200)
is_active = models.BooleanField(default= True)
is_admin = models.BooleanField(default=False)
is_super = models.BooleanField(default=False)
create_time_super_user = models.DateTimeField(auto_now=True, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
objects = UserManager()
USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = ['email', 'full_name']
def __str__(self):
return self.phone
#property
def is_staff(self):
return self.is_admin
# #property
def active(self):
now = timezone.now()
if self.create_time_super_user > now - timedelta(seconds=15):
self.is_super = False
self.save()
return self
def User_expire_time(self):
user_super = self.object.all()
if self.is_super:
if self.objects.filter(create_time_super_user__lte=self.timezone.now() - timedelta(day=30)):
user_super.update(is_super = False)
user_super.save
return user_super

Related

MongoDB ObjectId "Instantiation" and saving

I use Django + MongoDB /Djongo for backend on Windows10/VSCode. How is it to instantiate document’s “ObjectId” like it is for other fields using Python? I have been struggling for a several days. Please help. Code example, below:
from djongo import models
class Blog(models.Model):
id= models.AutoField(
auto_created = True,
unique=True,
primary_key = True,
serialize = False,
verbose_name ='ID_nama: ')
name = models.CharField(max_length=100)
tagline = models.TextField()
def __str__(self):
return self.name, self.id
# return self.tagline
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
def __str__(self):
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField(default=date.today)
authors = models.ManyToManyField(Author)
number_of_comments = models.IntegerField(default=0)
number_of_pingbacks = models.IntegerField(default=0)
rating = models.IntegerField(default=5)
def __str__(self):
return self.headline
Here is the document JSON from MongodDB:
{
“_id”: {
“$oid”: “626b6627f0d91c65e9f78cc6”
},
“id”: 5,
“name”: “Beatles Blog”,
“tagline”: “Beatles tour of the Americas.”
}
My target is to be able to capture the “ObjectId” => “_id”: {
“$oid”: “626b6627f0d91c65e9f78cc6”, and save it to another new field for other use/purpose.

how to post data in a nested serializer in Django rest framework

I am working on an app and need help I want to authenticate LinkedIn and save the access token in a table and then collect the LinkedIn user details in another table below is my model.py
class LinkedInUserCode(models.Model):
"""
Credentials for the user to give access to LinkedIn.
"""
user = models.OneToOneField(User, on_delete=models.CASCADE)
token = models.CharField(max_length=1024)
expires_in = models.IntegerField()
def __str__(self):
return f'{self.token}'
class Meta:
db_table = 'linkedin_user_code'
verbose_name_plural = "LinkedIn User Codes"
class LinkedInProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
linkedin_id = models.CharField(max_length=1024, blank=True, null=True)
first_name = models.CharField(max_length=1024, blank=True, null=True)
last_name = models.CharField(max_length=1024, blank=True, null=True)
profile_image_url = models.CharField(max_length=1024, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return f'{self.linkedin_id}'
class Meta:
db_table = 'linkedin_profile'
verbose_name_plural = "LinkedIn Profiles"
I am using a nested serializer and this is my serialiser
class LinkedInProfileSerializer(ModelSerializer):
"""
Serializer for the LinkedInProfile model.
"""
id = IntegerField(required=False)
user = ReadOnlyField(source='user.email')
linkedin_access = ReadOnlyField(source='linkedin_access.token')
class Meta:
model = LinkedInProfile
fields = '__all__'
def create(self, validated_data):
"""
Create a new LinkedInProfile instance.
"""
return LinkedInProfile.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.linkedin_id = validated_data.get('linkedin_id')
instance.first_name = validated_data.get('first_name')
instance.last_name = validated_data.get('last_name')
instance.profile_image_url = validated_data.get('profile_image_url')
instance.linkedin_access = validated_data.get('linkedin_access')
instance.save()
return instance
class LinkedInUserCodeSerializer(ModelSerializer):
user = ReadOnlyField(source='user.email')
profiles = LinkedInProfileSerializer(many=True, read_only=True)
class Meta:
model = LinkedInUserCode
fields = ['user', 'token', 'expires_in', 'profiles']
def create(self, validated_data):
""" Create and return necessary credentials for linkedin."""
profile = validated_data.pop('profiles')
access_token = LinkedInUserCode.objects.create(**validated_data)
for profile_data in profile:
LinkedInProfile.objects.create(linkedin_access=access_token, **profile_data)
return access_token
def update(self, instance, validated_data):
profiles = validated_data.pop('profiles')
instance.token = validated_data.get('token', instance.token)
instance.expires_in = validated_data.get('expires_in', instance.expires_in)
instance.save()
temp_profile = []
existing_ids = [profiles.get('linkedin_id') for profile in instance.profiles.all()]
for profile_data in profile:
if profile_data.get('linkedin_id') in existing_ids:
temp_profile.append(LinkedInProfile.objects.get(linkedin_id=profile_data.get('linkedin_id')))
else:
temp_profile.append(LinkedInProfile.objects.create(linkedin_access=instance, **profile_data))
instance.profiles.set(temp_profile)
for profile in instance.profiles.all():
if profile not in temp_profile:
profile.delete()
return instance
I have written a script that I am using to make requests to the LinkedIn api and here is my view I want to populate it at once any idea how I can go about it I keep having issues with the foreign key of LinkedIn_access
class LinkedInCallbackAPIView(APIView):
"""
This View is used to get and save the Access Token from LinkedIn authorization page.
"""
def get(self, request, *args, **kwargs):
response = request.GET
if response is not None and state != response.get('state'):
return Response({'error': "Invalid state"}, status=status.HTTP_401_UNAUTHORIZED)
else:
queryset = LinkedInUserCode.objects.filter(user=request.user)
code = response.get('code')
access_token = linkedin.get_access_token(code)
profile = linkedin.get_user_profile(access_token.get('access_token'))
profile = {
'linkedin_id': profile.get('id'),
'first_name': profile.get('firstName').get('localized').get('en_US'),
'last_name': profile.get('lastName').get('localized').get('en_US'),
'profile_image_url': profile.get('profilePicture').get('displayImage'),
}
data = {
'token': access_token.get('access_token'),
'expires_in': access_token.get('expires_in'),
'user': request.user,
'profiles': profile,
}
serializer = LinkedInUserCodeSerializer(data=data)
if queryset.exists():
serializer.update(queryset.first(), data)
return Response({'message': 'Your LinkedIn user Access Token was Updated'},status=status.HTTP_200_OK)
if serializer.is_valid():
serializer.save(**data)
# there will be a return response here
I need help passing this table and not using a single table for it
thank you

I am trying to create drop down menu in django but my code is showing only text box ? Help Appricated

I have defined modles.py, view.py, and forms.py but unable to get the drop-down menu. at initial, I have created moodle.py using os_choice and later on a substitute in the operating_system. further, I have created forms and I am using crispy forms to render in front page. likewise, I have defined this in views.py but when I see it on the font page it shows only a text file, not a drop-down with choices.
Here is my model.py code:
from django.db import models
from django.utils.encoding import smart_text
from multiselectfield import MultiSelectField
# Create your models here.
class ResultQuery(models.Model):
os_choice = (
('Windows 10', 'Windows 10'),
('Windows 8', 'Windows 8'),
('Linux', 'Linux'),
)
operating_system = models.CharField(max_length=30, blank=True, null=True, choices=os_choice)
level = models.CharField(max_length=30)
program = models.CharField(max_length=30)
semester = models.CharField(max_length=20)
exam_year = models.IntegerField()
institute = models.CharField(max_length=4)
reg_no = models.CharField(max_length=50)
symbol_num = models.IntegerField()
student_name = models.CharField(max_length=50)
dob = models.DateField()
sgpa = models.TextField()
result = models.CharField(max_length=40)
name = models.CharField(max_length=30)
subject1_code=models.CharField(max_length=40)
subject1_title=models.CharField(max_length=40)
subject1_credit_hour=models.TextField()
subject1_grade_point=models.TextField()
subject1_grade=models.TextField()
subject1_remarks=models.CharField(max_length=20, null=True, blank=True)
subject2_code = models.CharField(max_length=40)
subject2_title = models.CharField(max_length=40)
subject2_credit_hour = models.TextField()
subject2_grade_point = models.TextField()
subject2_grade = models.TextField()
subject2_remarks = models.CharField(max_length=20, null=True, blank=True)
subject3_code = models.CharField(max_length=40)
subject3_title = models.CharField(max_length=40)
subject3_credit_hour = models.TextField()
subject3_grade_point = models.TextField()
subject3_grade = models.TextField()
subject3_remarks = models.CharField(max_length=20, null=True, blank=True)
subject4_code = models.CharField(max_length=40)
subject4_title = models.CharField(max_length=40)
subject4_credit_hour = models.TextField()
subject4_grade_point = models.TextField()
subject4_grade = models.TextField()
subject4_remarks = models.CharField(max_length=20, null=True, blank=True)
subject5_code = models.CharField(max_length=40)
subject5_title = models.CharField(max_length=40)
subject5_credit_hour = models.TextField()
subject5_grade_point = models.TextField()
subject5_grade = models.TextField()
subject5_remarks = models.CharField(max_length=20, null=True, blank=True)
subject6_code = models.CharField(max_length=40)
subject6_title = models.CharField(max_length=40)
subject6_credit_hour = models.TextField()
subject6_grade_point = models.TextField()
subject6_grade = models.TextField()
subject6_remarks = models.CharField(max_length=20, null=True, blank=True)
def __str__(self):
return smart_text(self.name)
Here is my forms.py
from django import forms
from search.models import ResultQuery
from django.forms import MultipleChoiceField, ChoiceField, Form
class ResultForm(forms.Form):
Reg_No=forms.CharField(label="Registration Number")
Name=forms.CharField(label="Your Name")
OS=forms.CharField(label="Operating System")
And here is my views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .forms import ResultForm
from .models import ResultQuery
def home(request):
form=ResultForm(request.POST or None)
template_name = "home.html"
context = {"form": form}
if form.is_valid():
objects = ResultQuery.objects.filter(reg_no=form.cleaned_data['Reg_No'], name=form.cleaned_data['Name'], operating_system=form.cleaned_data['OS'])
context['objects'] = objects
return render(request, template_name, context)
Have you tried doing it like so?
from django import forms
from search.models import ResultQuery
from django.forms import MultipleChoiceField, ChoiceField, Form
class ResultForm(forms.Form):
Reg_No=forms.CharField(label="Registration Number")
Name=forms.CharField(label="Your Name")
OS=forms.ChoiceField(choices=ResultQuery.os_choice)

strftime model object and display in html template

Good day, I want to strftime the created model instance and display it in the HTML template(as a transaction_id). But I don't seem to get it right. Thanks for your help.
models.py
class Order(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
phone_number = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
braintree_id = models.CharField(max_length=150, blank=True)
coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL)
discount = models.IntegerField(default=0, validators=[
MinValueValidator(0),
MaxValueValidator(100)
])
views.py
def order_list(request):#datetime.now().strftime("%Y%m%d%H%M%S")
transaction_id = Order.objects.get(created)
orders = Order.objects.all()
current_user = request.user
success = Order.objects.filter(user=current_user.id).filter(paid=True)
fail = Order.objects.filter(user=current_user.id).filter(paid=False)
return render(request, 'orders/order/order_list.html', {
'success': success,
'fail': fail,
'current_user': current_user,
'orders':orders,
'transaction_id':transaction_id,
})
html
<p class="card-text">
<mark style="color: whitesmoke; background-color: brown;border-radius: 3px;font-weight: bold;">{{transaction_id}}</mark>
</p>
you getting error of "transaction_id = Order.objects.get(created)" line
what is "created" in get() method
Well, this is what I did to fix this
I added the strftime func in my models.py
models.py
def htmldisplaytime(self):
time = self.created.strftime("%Y%m%d%H%M%S")
return time

Django AttributeError 'Tag' object has no attribute 'summary'

I run into this error whenever I tried to add a new Tag. I tried to google and read some SO posts, but nothing work for me.
Here are my 2 models :
Summary :
class Summary(models.Model):
question_text = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
url = models.URLField(null=False)
cover_image = models.CharField(max_length=255)
tags = models.ManyToManyField('Tag', related_name='summaries', blank=True)
userProfileSummary = models.ManyToManyField('UserProfile', through='UserProfileSummary')
def __str__(self):
return self.question_text
class Meta:
verbose_name_plural = "Summaries"
Tag :
class Tag(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
models/init.py:
...
from .tag import Tag
from .summary import Summary
__all__ = (
...
'Tag',
'Summary',
)
Error :
Please, what did I miss ?

Resources