From e360d48256701aec2631e9fd157bd9de3b4c8910 Mon Sep 17 00:00:00 2001 From: shubhushan Date: Mon, 19 Jul 2021 18:41:37 +0200 Subject: [PATCH] Issue #926 fixed --- project/accounts/api.py | 32 ++++---- project/accounts/authentication.py | 20 ++--- project/accounts/forms.py | 18 ++--- .../migrations/0004_auto_20210914_0739.py | 24 ++++++ project/accounts/models.py | 75 ++++++++++--------- project/accounts/views.py | 16 ++-- project/api/forms.py | 4 +- project/api/models/activity.py | 4 +- project/api/models/civi.py | 10 +-- project/api/models/notification.py | 4 +- project/api/models/rebuttal.py | 6 +- project/api/models/response.py | 4 +- project/api/models/thread.py | 4 +- project/api/permissions.py | 6 +- project/api/read.py | 38 +++++----- project/api/serializers.py | 34 ++++----- project/api/urls.py | 2 +- project/api/utils.py | 8 +- project/api/views/__init__.py | 2 +- project/api/write.py | 52 ++++++------- project/core/custom_decorators.py | 4 +- project/frontend_views/views.py | 16 ++-- 22 files changed, 205 insertions(+), 178 deletions(-) create mode 100644 project/accounts/migrations/0004_auto_20210914_0739.py diff --git a/project/accounts/api.py b/project/accounts/api.py index fa39357c4..5f34d78fa 100644 --- a/project/accounts/api.py +++ b/project/accounts/api.py @@ -1,23 +1,23 @@ from rest_framework.viewsets import ModelViewSet from rest_framework.decorators import action from rest_framework.response import Response -from api.permissions import IsAccountOwnerOrDuringRegistrationOrReadOnly +from api.permissions import IsProfileOwnerOrDuringRegistrationOrReadOnly from api.utils import get_account from api.models import Thread -from accounts.models import Account +from accounts.models import Profile from api.serializers import ( ThreadSerializer, CategorySerializer, CiviSerializer, - AccountSerializer, - AccountListSerializer, + ProfileSerializer, + ProfileListSerializer, ) -class AccountViewSet(ModelViewSet): +class ProfileViewSet(ModelViewSet): """ - REST API viewset for an Account + REST API viewset for an Profile retrieve: Return the given user based a username. @@ -25,29 +25,29 @@ class AccountViewSet(ModelViewSet): Return a list of all the existing users. Only with privileged access. """ - queryset = Account.objects.all() + queryset = Profile.objects.all() lookup_field = "user__username" - serializer_class = AccountSerializer + serializer_class = ProfileSerializer http_method_names = ["get", "head", "put", "patch"] - permission_classes = (IsAccountOwnerOrDuringRegistrationOrReadOnly,) + permission_classes = (IsProfileOwnerOrDuringRegistrationOrReadOnly,) authentication_classes = () def list(self, request): """ """ if self.request.user.is_staff: - accounts = Account.objects.all() + accounts = Profile.objects.all() else: - accounts = Account.objects.filter(user=self.request.user) - serializer = AccountListSerializer(accounts, many=True) + accounts = Profile.objects.filter(user=self.request.user) + serializer = ProfileListSerializer(accounts, many=True) return Response(serializer.data) def retrieve(self, request, user__username=None): """ """ account = get_account(username=user__username) if self.request.user == account.user: - serializer = AccountSerializer(account) + serializer = ProfileSerializer(account) else: - serializer = AccountListSerializer(account) + serializer = ProfileListSerializer(account) return Response(serializer.data) @action(detail=True) @@ -69,7 +69,7 @@ def followers(self, request, user__username=None): """ account = get_account(username=user__username) account_followers = account.followers.all() - serializer = AccountListSerializer(account_followers, many=True) + serializer = ProfileListSerializer(account_followers, many=True) return Response(serializer.data) @action(detail=True) @@ -80,7 +80,7 @@ def following(self, request, user__username=None): """ account = get_account(username=user__username) account_followings = account.following.all() - serializer = AccountListSerializer(account_followings, many=True) + serializer = ProfileListSerializer(account_followings, many=True) return Response(serializer.data) @action(detail=True) diff --git a/project/accounts/authentication.py b/project/accounts/authentication.py index 69d655ede..1219f8793 100644 --- a/project/accounts/authentication.py +++ b/project/accounts/authentication.py @@ -21,15 +21,15 @@ from accounts.utils import send_email -from accounts.models import Account -from .forms import AccountRegistrationForm, PasswordResetForm, RecoverUserForm +from accounts.models import Profile +from .forms import ProfileRegistrationForm, PasswordResetForm, RecoverUserForm from core.custom_decorators import require_post_params User = get_user_model() -class AccountActivationTokenGenerator(PasswordResetTokenGenerator): +class ProfileActivationTokenGenerator(PasswordResetTokenGenerator): """Token Generator for Email Confirmation""" @@ -45,7 +45,7 @@ def _make_token_with_timestamp(self, user, timestamp): return "%s-%s" % (ts_b36, hash) -account_activation_token = AccountActivationTokenGenerator() +account_activation_token = ProfileActivationTokenGenerator() def send_activation_email(user, domain): @@ -68,7 +68,7 @@ def send_activation_email(user, domain): html_message = render_to_string("email/base_email_template.html", context) sender = settings.EMAIL_HOST_USER send_email( - subject="CiviWiki Account Setup", + subject="CiviWiki Profile Setup", message=message, sender=sender, recipient_list=[user.email], @@ -99,7 +99,7 @@ def cw_login(request): if user.is_active: - account = get_object_or_404(Account, user=user) + account = get_object_or_404(Profile, user=user) request.session["login_user_firstname"] = account.first_name request.session["login_user_image"] = account.profile_image_thumb_url @@ -135,7 +135,7 @@ def cw_register(request): Return: (200, ok) (500, Internal Error) """ - form = AccountRegistrationForm(request.POST or None) + form = ProfileRegistrationForm(request.POST or None) if request.method == "POST": # Form Validation if form.is_valid(): @@ -143,11 +143,11 @@ def cw_register(request): password = form.clean_password() email = form.clean_email() - # Create a New Account + # Create a New Profile try: user = User.objects.create_user(username, email, password) - account = Account(user=user) + account = Profile(user=user) account.save() user.is_active = True @@ -187,7 +187,7 @@ def activate_view(request, uidb64, token): user = None if user is not None and account_activation_token.check_token(user, token): - account = Account.objects.get(user=user) + account = Profile.objects.get(user=user) if account.is_verified: redirect_link = {"href": "/", "label": "Back to Main"} template_var = { diff --git a/project/accounts/forms.py b/project/accounts/forms.py index 19791d58c..b3a879604 100644 --- a/project/accounts/forms.py +++ b/project/accounts/forms.py @@ -19,12 +19,12 @@ from accounts.utils import send_email from .reserved_usernames import RESERVED_USERNAMES -from accounts.models import Account +from accounts.models import Profile User = get_user_model() -class AccountRegistrationForm(ModelForm): +class ProfileRegistrationForm(ModelForm): """ This class is used to register new account in Civiwiki @@ -189,7 +189,7 @@ def save( email_body = body_txt.format(domain=domain, username=user.username) context = { - "title": "Account Recovery for CiviWiki", + "title": "Profile Recovery for CiviWiki", "greeting": "Recover your account on CiviWiki", "body": email_body, "link": url_with_code, @@ -202,7 +202,7 @@ def save( html_message = render_to_string(html_message_template, context) sender = settings.EMAIL_HOST_USER send_email( - subject="Account Recovery for CiviWiki", + subject="Profile Recovery for CiviWiki", message=message, sender=settings.EMAIL_HOST_USER, recipient_list=[email], @@ -210,14 +210,14 @@ def save( ) -class UpdateAccount(forms.ModelForm): +class UpdateProfile(forms.ModelForm): """ - Form for updating Account data + Form for updating Profile data """ def __init__(self, *args, **kwargs): readonly = kwargs.pop("readonly", False) - super(UpdateAccount, self).__init__(*args, **kwargs) + super(UpdateProfile, self).__init__(*args, **kwargs) if readonly: self.disable_fields() @@ -226,7 +226,7 @@ def disable_fields(self): field.disabled = True class Meta: - model = Account + model = Profile fields = [ "first_name", "last_name", @@ -297,7 +297,7 @@ class UpdateProfileImage(forms.ModelForm): """ class Meta: - model = Account + model = Profile fields = ["profile_image"] profile_image = forms.ImageField() diff --git a/project/accounts/migrations/0004_auto_20210914_0739.py b/project/accounts/migrations/0004_auto_20210914_0739.py new file mode 100644 index 000000000..6ce0f0922 --- /dev/null +++ b/project/accounts/migrations/0004_auto_20210914_0739.py @@ -0,0 +1,24 @@ +# Generated by Django 3.2.7 on 2021-09-14 07:39 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0041_auto_20210906_0802'), + ('taggit', '0003_taggeditem_add_unique_index'), + ('accounts', '0003_account'), + ] + + operations = [ + migrations.RenameModel( + old_name='Account', + new_name='Profile', + ), + migrations.RenameField( + model_name='profile', + old_name='full_account', + new_name='full_profile', + ), + ] diff --git a/project/accounts/models.py b/project/accounts/models.py index e6f1f9b8b..55b688b61 100644 --- a/project/accounts/models.py +++ b/project/accounts/models.py @@ -33,68 +33,68 @@ class Meta: User = get_user_model() -class AccountManager(models.Manager): - def summarize(self, account): +class ProfileManager(models.Manager): + def summarize(self, profile): from api.models.civi import Civi data = { - "username": account.user.username, - "first_name": account.first_name, - "last_name": account.last_name, - "about_me": account.about_me, + "username": profile.user.username, + "first_name": profile.first_name, + "last_name": profile.last_name, + "about_me": profile.about_me, "history": [ Civi.objects.serialize(c) - for c in Civi.objects.filter(author_id=account.id).order_by("-created") + for c in Civi.objects.filter(author_id=profile.id).order_by("-created") ], - "profile_image": account.profile_image_url, - "followers": self.followers(account), - "following": self.following(account), + "profile_image": profile.profile_image_url, + "followers": self.followers(profile), + "following": self.following(profile), } return data - def chip_summarize(self, account): + def chip_summarize(self, profile): data = { - "username": account.user.username, - "first_name": account.first_name, - "last_name": account.last_name, - "profile_image": account.profile_image_url, + "username": profile.user.username, + "first_name": profile.first_name, + "last_name": profile.last_name, + "profile_image": profile.profile_image_url, } return data - def card_summarize(self, account, request_account): + def card_summarize(self, profile, request_profile): # Length at which to truncate 'about me' text about_me_truncate_length = 150 # If 'about me' text is longer than 150 characters... add elipsis (truncate) ellipsis_if_too_long = ( - "" if len(account.about_me) <= about_me_truncate_length else "..." + "" if len(profile.about_me) <= about_me_truncate_length else "..." ) data = { - "id": account.user.id, - "username": account.user.username, - "first_name": account.first_name, - "last_name": account.last_name, - "about_me": account.about_me[:about_me_truncate_length] + ellipsis_if_too_long, - "profile_image": account.profile_image_url, + "id": profile.user.id, + "username": profile.user.username, + "first_name": profile.first_name, + "last_name": profile.last_name, + "about_me": profile.about_me[:about_me_truncate_length] + ellipsis_if_too_long, + "profile_image": profile.profile_image_url, "follow_state": True - if account in request_account.following.all() + if profile in request_profile.following.all() else False, - "request_account": request_account.first_name, + "request_profile": request_profile.first_name, } return data - def followers(self, account): - return [self.chip_summarize(follower) for follower in account.followers.all()] + def followers(self, profile): + return [self.chip_summarize(follower) for follower in profile.followers.all()] - def following(self, account): - return [self.chip_summarize(following) for following in account.following.all()] + def following(self, profile): + return [self.chip_summarize(following) for following in profile.following.all()] profile_upload_path = PathAndRename("") -class Account(models.Model): +class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=63, blank=False) last_name = models.CharField(max_length=63, blank=False) @@ -113,9 +113,9 @@ class Account(models.Model): ) is_verified = models.BooleanField(default=False) - full_account = models.BooleanField(default=False) + full_profile = models.BooleanField(default=False) - objects = AccountManager() + objects = ProfileManager() profile_image = models.ImageField( upload_to=profile_upload_path, blank=True, null=True ) @@ -155,16 +155,19 @@ def profile_image_thumb_url(self): return "/static/img/no_image_md.png" + def __init__(self, *args, **kwargs): + super(Profile, self).__init__(*args, **kwargs) + def save(self, *args, **kwargs): - """Image crop/resize and thumbnail creation""" + """ Image crop/resize and thumbnail creation """ # New Profile image -- if self.profile_image: self.resize_profile_image() - self.full_account = self.is_full_account() + self.full_profile = self.is_full_profile() - super(Account, self).save(*args, **kwargs) + super(Profile, self).save(*args, **kwargs) def resize_profile_image(self): """ @@ -213,7 +216,7 @@ def resize_profile_image(self): None, ) - def is_full_account(self): + def is_full_profile(self): if self.first_name and self.last_name: return True else: diff --git a/project/accounts/views.py b/project/accounts/views.py index 9b9abc148..18e6dd33b 100644 --- a/project/accounts/views.py +++ b/project/accounts/views.py @@ -17,15 +17,15 @@ from django.urls import reverse_lazy from django.template.response import TemplateResponse -from accounts.models import Account +from accounts.models import Profile from core.custom_decorators import login_required -from .forms import AccountRegistrationForm, UpdateAccount +from .forms import ProfileRegistrationForm, UpdateProfile from .models import User from .authentication import send_activation_email -class AccountActivationTokenGenerator(PasswordResetTokenGenerator): +class ProfileActivationTokenGenerator(PasswordResetTokenGenerator): """Token Generator for Email Confirmation""" key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" @@ -46,7 +46,7 @@ class RegisterView(FormView): """ template_name = "accounts/register/register.html" - form_class = AccountRegistrationForm + form_class = ProfileRegistrationForm success_url = "/" def _create_user(self, form): @@ -56,7 +56,7 @@ def _create_user(self, form): user = User.objects.create_user(username, email, password) - account = Account(user=user) + account = Profile(user=user) account.save() user.is_active = True @@ -105,8 +105,8 @@ class PasswordResetCompleteView(auth_views.PasswordResetCompleteView): def settings_view(request): account = request.user.account_set.first() if request.method == "POST": - instance = Account.objects.get(user=request.user) - form = UpdateAccount( + instance = Profile.objects.get(user=request.user) + form = UpdateProfile( request.POST, initial={"username": request.user.username, "email": request.user.email}, instance=instance, @@ -114,7 +114,7 @@ def settings_view(request): if form.is_valid(): form.save() else: - form = UpdateAccount( + form = UpdateProfile( initial={ "username": request.user.username, "email": request.user.email, diff --git a/project/api/forms.py b/project/api/forms.py index 82e3a766e..26ff90360 100644 --- a/project/api/forms.py +++ b/project/api/forms.py @@ -1,7 +1,7 @@ from django import forms from django.core.files.images import get_image_dimensions from django.contrib.auth import get_user_model -from accounts.models import Account +from accounts.models import Profile User = get_user_model() @@ -56,7 +56,7 @@ class UpdateProfileImage(forms.ModelForm): """ class Meta: - model = Account + model = Profile fields = ["profile_image"] profile_image = forms.ImageField() diff --git a/project/api/models/activity.py b/project/api/models/activity.py index 4d8c45d8d..6679ad3ff 100644 --- a/project/api/models/activity.py +++ b/project/api/models/activity.py @@ -5,7 +5,7 @@ from django.db import models -from accounts.models import Account +from accounts.models import Profile from .civi import Civi from .thread import Thread @@ -25,7 +25,7 @@ def votes(self, civi_id): class Activity(models.Model): account = models.ForeignKey( - Account, default=None, null=True, on_delete=models.PROTECT + Profile, default=None, null=True, on_delete=models.PROTECT ) thread = models.ForeignKey( Thread, default=None, null=True, on_delete=models.PROTECT diff --git a/project/api/models/civi.py b/project/api/models/civi.py index eb3d9c561..23570e03e 100644 --- a/project/api/models/civi.py +++ b/project/api/models/civi.py @@ -14,7 +14,7 @@ from django.db import models from django.conf import settings -from accounts.models import Account +from accounts.models import Profile from .thread import Thread from taggit.managers import TaggableManager from .thread import Thread @@ -57,7 +57,7 @@ def serialize(self, civi, filter=None): return json.dumps(data, cls=DjangoJSONEncoder) def serialize_s(self, civi, filter=None): - # Get account profile image, or set to default image + # Get profile profile image, or set to default image profile_image_or_default = ( civi.author.profile_image.url or "/media/profile/default.png" ) @@ -97,7 +97,7 @@ def thread_sorted_by_score(self, civis_queryset, req_acct_id): class Civi(models.Model): objects = CiviManager() author = models.ForeignKey( - Account, related_name="civis", default=None, null=True, on_delete=models.PROTECT + Profile, related_name="civis", default=None, null=True, on_delete=models.PROTECT ) thread = models.ForeignKey( Thread, related_name="civis", default=None, null=True, on_delete=models.PROTECT @@ -186,10 +186,10 @@ def score(self, request_acct_id=None): scores_sum = vneg_score + neg_score + pos_score + vpos_score if request_acct_id: - account = Account.objects.get(id=request_acct_id) + profile = Profile.objects.get(id=request_acct_id) scores_sum = ( 1 - if self.author in account.following.all().values_list("id", flat=True) + if self.author in profile.following.all().values_list("id", flat=True) else 0 ) else: diff --git a/project/api/models/notification.py b/project/api/models/notification.py index 2fc42360f..801f81a51 100644 --- a/project/api/models/notification.py +++ b/project/api/models/notification.py @@ -5,14 +5,14 @@ from django.db import models -from accounts.models import Account +from accounts.models import Profile from .civi import Civi from .thread import Thread class Notification(models.Model): account = models.ForeignKey( - Account, default=None, null=True, on_delete=models.PROTECT + Profile, default=None, null=True, on_delete=models.PROTECT ) thread = models.ForeignKey( Thread, default=None, null=True, on_delete=models.PROTECT diff --git a/project/api/models/rebuttal.py b/project/api/models/rebuttal.py index 77d5e8b4b..15658e013 100644 --- a/project/api/models/rebuttal.py +++ b/project/api/models/rebuttal.py @@ -1,17 +1,17 @@ """ Rebuttal model -Extends local Account and Response model +Extends local Profile and Response model """ from django.db import models -from accounts.models import Account +from accounts.models import Profile from .response import Response class Rebuttal(models.Model): author = models.ForeignKey( - Account, default=None, null=True, on_delete=models.PROTECT + Profile, default=None, null=True, on_delete=models.PROTECT ) response = models.ForeignKey( Response, default=None, null=True, on_delete=models.PROTECT diff --git a/project/api/models/response.py b/project/api/models/response.py index b555f5a8b..d6305e279 100644 --- a/project/api/models/response.py +++ b/project/api/models/response.py @@ -5,13 +5,13 @@ from django.db import models -from accounts.models import Account +from accounts.models import Profile from .civi import Civi class Response(models.Model): author = models.ForeignKey( - Account, default=None, null=True, on_delete=models.PROTECT + Profile, default=None, null=True, on_delete=models.PROTECT ) civi = models.ForeignKey(Civi, default=None, null=True, on_delete=models.PROTECT) diff --git a/project/api/models/thread.py b/project/api/models/thread.py index 06c04cb48..e6e5d1cea 100644 --- a/project/api/models/thread.py +++ b/project/api/models/thread.py @@ -10,7 +10,7 @@ from django.conf import settings from django.db import models -from accounts.models import Account +from accounts.models import Profile from .category import Category from .fact import Fact from taggit.managers import TaggableManager @@ -71,7 +71,7 @@ def filter_by_category(self, categories): class Thread(models.Model): author = models.ForeignKey( - Account, default=None, null=True, on_delete=models.PROTECT + Profile, default=None, null=True, on_delete=models.PROTECT ) category = models.ForeignKey( Category, default=None, null=True, on_delete=models.PROTECT diff --git a/project/api/permissions.py b/project/api/permissions.py index d3c1dd841..3247f1ce6 100644 --- a/project/api/permissions.py +++ b/project/api/permissions.py @@ -11,18 +11,18 @@ def has_object_permission(self, request, view, obj): ) -class IsAccountOwnerOrReadOnly(BasePermission): +class IsProfileOwnerOrReadOnly(BasePermission): """ Custom API permission to check if request user is the owner of the account """ def has_object_permission(self, request, view, obj): return (request.method in SAFE_METHODS) or (obj.user == request.user) -class IsAccountOwnerOrDuringRegistrationOrReadOnly(IsAccountOwnerOrReadOnly): +class IsProfileOwnerOrDuringRegistrationOrReadOnly(IsProfileOwnerOrReadOnly): """ """ def has_object_permission(self, request, view, obj): if obj.full_account: return super( - IsAccountOwnerOrDuringRegistrationOrReadOnly, self + IsProfileOwnerOrDuringRegistrationOrReadOnly, self ).has_object_permission(request, view, obj) return True diff --git a/project/api/read.py b/project/api/read.py index c7b64c5b5..52ceed76d 100644 --- a/project/api/read.py +++ b/project/api/read.py @@ -3,7 +3,7 @@ from django.forms.models import model_to_dict from .models import Thread, Civi, Activity -from accounts.models import Account +from accounts.models import Profile from .utils import json_response User = get_user_model() @@ -16,10 +16,10 @@ def get_user(request, user): """ try: u = User.objects.get(username=user) - a = Account.objects.get(user=u) + a = Profile.objects.get(user=u) return JsonResponse(model_to_dict(a)) - except Account.DoesNotExist as e: + except Profile.DoesNotExist as e: return HttpResponseBadRequest(reason=str(e)) @@ -30,14 +30,14 @@ def get_card(request, user): """ try: u = User.objects.get(username=user) - a = Account.objects.get(user=u) - result = Account.objects.card_summarize( - a, Account.objects.get(user=request.user) + a = Profile.objects.get(user=u) + result = Profile.objects.card_summarize( + a, Profile.objects.get(user=request.user) ) return JsonResponse(result) except User.DoesNotExist: return HttpResponseBadRequest(reason=f"User with username {user} not found") - except Account.DoesNotExist as e: + except Profile.DoesNotExist as e: return HttpResponseBadRequest(reason=str(e)) except Exception as e: return HttpResponseBadRequest(reason=str(e)) @@ -50,8 +50,8 @@ def get_profile(request, user): """ try: u = User.objects.get(username=user) - a = Account.objects.get(user=u) - result = Account.objects.summarize(a) + a = Profile.objects.get(user=u) + result = Profile.objects.summarize(a) result["issues"] = [] voted_solutions = Activity.objects.filter( @@ -87,7 +87,7 @@ def get_profile(request, user): result["issues"].append(my_issue_item) if request.user.username != user: - ra = Account.objects.get(user=request.user) + ra = Profile.objects.get(user=request.user) if user in ra.following.all(): result["follow_state"] = True else: @@ -95,7 +95,7 @@ def get_profile(request, user): return JsonResponse(result) - except Account.DoesNotExist as e: + except Profile.DoesNotExist as e: return HttpResponseBadRequest(reason=str(e)) @@ -123,7 +123,7 @@ def get_thread(request, thread_id): try: t = Thread.objects.get(id=thread_id) civis = Civi.objects.filter(thread_id=thread_id) - req_a = Account.objects.get(user=request.user) + req_a = Profile.objects.get(user=request.user) # TODO: move order by to frontend or accept optional arg c = civis.order_by("-created") @@ -149,8 +149,8 @@ def get_thread(request, thread_id): "category": model_to_dict(t.category), "created": t.created, "contributors": [ - Account.objects.chip_summarize(a) - for a in Account.objects.filter( + Profile.objects.chip_summarize(a) + for a in Profile.objects.filter( pk__in=civis.distinct("author").values_list("author", flat=True) ) ], @@ -173,8 +173,8 @@ def get_thread(request, thread_id): return json_response(data) except Thread.DoesNotExist: return HttpResponseBadRequest(reason=f"Thread with id:{thread_id} does not exist") - except Account.DoesNotExist: - return HttpResponseBadRequest(reason=f"Account with username:{request.user.username} does not exist") + except Profile.DoesNotExist: + return HttpResponseBadRequest(reason=f"Profile with username:{request.user.username} does not exist") except Exception as e: return HttpResponseBadRequest(reason=str(e)) @@ -209,7 +209,7 @@ def get_responses(request, thread_id, civi_id): This is used to get responses for a Civi """ try: - req_acct = Account.objects.get(user=request.user) + req_acct = Profile.objects.get(user=request.user) c_qs = Civi.objects.get(id=civi_id).responses.all() c_scored = [] for res_civi in c_qs: @@ -222,8 +222,8 @@ def get_responses(request, thread_id, civi_id): civis = sorted(c_scored, key=lambda c: c["score"], reverse=True) return JsonResponse(civis, safe=False) - except Account.DoesNotExist: - return HttpResponseBadRequest(reason=f"Account with user:{request.user.username} does not exist") + except Profile.DoesNotExist: + return HttpResponseBadRequest(reason=f"Profile with user:{request.user.username} does not exist") except Civi.DoesNotExist: return HttpResponseBadRequest(reason=f"Civi with id:{civi_id} does not exist") except Exception as e: diff --git a/project/api/serializers.py b/project/api/serializers.py index b876075eb..8eaf8cf7e 100644 --- a/project/api/serializers.py +++ b/project/api/serializers.py @@ -2,13 +2,13 @@ from api.forms import UpdateProfileImage from api.models import Civi, Thread, Category, CiviImage, Activity -from accounts.models import Account +from accounts.models import Profile from core.constants import CIVI_TYPES WRITE_ONLY = {"write_only": True} -class AccountCommonSerializer(serializers.ModelSerializer): +class ProfileCommonSerializer(serializers.ModelSerializer): """ Common serializer for specific account serializers""" username = serializers.ReadOnlyField(source="user.username") @@ -19,13 +19,13 @@ def get_is_following(self, obj): # Check for authenticated user if request and hasattr(request, "user") and request.user.is_authenticated: - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) if obj in account.following.all(): return True return False -class AccountSerializer(AccountCommonSerializer): +class ProfileSerializer(ProfileCommonSerializer): """ General seralizer for a single model instance of a user account """ @@ -48,7 +48,7 @@ class AccountSerializer(AccountCommonSerializer): is_staff = serializers.ReadOnlyField(source="user.is_staff") class Meta: - model = Account + model = Profile fields = ( "username", "first_name", @@ -83,7 +83,7 @@ def validate_profile_image(self, value): if validation_form.is_valid(): # Clean up previous images - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) account.profile_image.delete() account.profile_image_thumb.delete() @@ -92,7 +92,7 @@ def validate_profile_image(self, value): raise serializers.ValidationError(validation_form.errors["profile_image"]) -class AccountListSerializer(AccountCommonSerializer): +class ProfileListSerializer(ProfileCommonSerializer): """ Serializer for multiple account model instances """ @@ -105,7 +105,7 @@ class AccountListSerializer(AccountCommonSerializer): profile_image_thumb_url = serializers.ReadOnlyField() class Meta: - model = Account + model = Profile fields = ( "username", "first_name", @@ -129,7 +129,7 @@ class Meta: class CiviSerializer(serializers.ModelSerializer): """ """ - author = AccountListSerializer() + author = ProfileListSerializer() type = serializers.ChoiceField(choices=CIVI_TYPES, source="c_type") images = serializers.SlugRelatedField( many=True, read_only=True, slug_field="image_url" @@ -175,13 +175,13 @@ def get_score(self, obj): if user.is_anonymous(): return 0 else: - account = Account.objects.get(user=user) + account = Profile.objects.get(user=user) return obj.score(account.id) class CiviListSerializer(serializers.ModelSerializer): """ """ - author = AccountListSerializer() + author = ProfileListSerializer() type = serializers.CharField(source="c_type") created = serializers.ReadOnlyField(source="created_date_str") @@ -218,13 +218,13 @@ def get_preferred(self, obj): if user.is_anonymous(): return True - account = Account.objects.get(user=user) + account = Profile.objects.get(user=user) return obj.id in account.categories.values_list("id", flat=True) class ThreadSerializer(serializers.ModelSerializer): """ """ - author = AccountListSerializer(required=False) + author = ProfileListSerializer(required=False) category = CategoryListSerializer() civis = serializers.HyperlinkedRelatedField( @@ -262,7 +262,7 @@ class Meta: class ThreadListSerializer(serializers.ModelSerializer): """ """ - author = AccountListSerializer(required=False) + author = ProfileListSerializer(required=False) category = CategoryListSerializer() created = serializers.ReadOnlyField() @@ -292,7 +292,7 @@ class Meta: class ThreadDetailSerializer(serializers.ModelSerializer): """ """ - author = AccountListSerializer(required=False) + author = ProfileListSerializer(required=False) category = CategoryListSerializer() civis = CiviSerializer(many=True) @@ -333,10 +333,10 @@ class Meta: def get_contributors(self, obj): """This function gets the list of contributors for Civiwiki""" issue_civis = Civi.objects.filter(thread__id=obj.id) - contributor_accounts = Account.objects.filter( + contributor_accounts = Profile.objects.filter( pk__in=issue_civis.values("author").distinct() ) - return AccountListSerializer(contributor_accounts, many=True).data + return ProfileListSerializer(contributor_accounts, many=True).data def get_user_votes(self, obj): """This function gets the user votes""" diff --git a/project/api/urls.py b/project/api/urls.py index 762bad804..42c971ece 100644 --- a/project/api/urls.py +++ b/project/api/urls.py @@ -6,7 +6,7 @@ router = DefaultRouter(trailing_slash=False) router.register(r"threads", views.ThreadViewSet) router.register(r"categories", views.CategoryViewSet) -router.register(r"accounts", views.AccountViewSet) +router.register(r"accounts", views.ProfileViewSet) router.register(r"civis", views.CiviViewSet) urlpatterns = [ diff --git a/project/api/utils.py b/project/api/utils.py index c80c3328d..79308716b 100644 --- a/project/api/utils.py +++ b/project/api/utils.py @@ -6,17 +6,17 @@ from django.shortcuts import get_object_or_404 -from accounts.models import Account +from accounts.models import Profile def get_account(user=None, pk=None, username=None): """ gets author based on the user """ if user: - return get_object_or_404(Account, user=user) + return get_object_or_404(Profile, user=user) elif pk: - return get_object_or_404(Account, pk=pk) + return get_object_or_404(Profile, pk=pk) elif username: - return get_object_or_404(Account, user__username=username) + return get_object_or_404(Profile, user__username=username) else: raise Http404 diff --git a/project/api/views/__init__.py b/project/api/views/__init__.py index 0e58e1569..733e0c3fe 100644 --- a/project/api/views/__init__.py +++ b/project/api/views/__init__.py @@ -1,4 +1,4 @@ -from accounts.api import AccountViewSet +from accounts.api import ProfileViewSet from .category import CategoryViewSet from .civi import CiviViewSet from .thread import ThreadViewSet diff --git a/project/api/write.py b/project/api/write.py index 9c617d8f4..4fd31798b 100644 --- a/project/api/write.py +++ b/project/api/write.py @@ -22,7 +22,7 @@ from api.forms import UpdateProfileImage from api.models import Thread from .models import Activity, Category, Civi, CiviImage -from accounts.models import Account +from accounts.models import Profile from core.custom_decorators import require_post_params from core.constants import US_STATES @@ -40,7 +40,7 @@ def new_thread(request): - Title, Summary, Category, Author, Level, State """ try: - author = Account.objects.get(user=request.user) + author = Profile.objects.get(user=request.user) new_thread_data = dict( title=request.POST["title"], summary=request.POST["summary"], @@ -56,8 +56,8 @@ def new_thread(request): new_t.save() return JsonResponse({"data": "success", "thread_id": new_t.pk}) - except Account.DoesNotExist: - return HttpResponseServerError(reason=f"Account with user:{request.user.username} does not exist") + except Profile.DoesNotExist: + return HttpResponseServerError(reason=f"Profile with user:{request.user.username} does not exist") except Exception as e: return HttpResponseServerError(reason=str(e)) @@ -72,10 +72,10 @@ def createCivi(request): :return: (200, ok) (400, missing required parameter) (500, internal error) """ - a = Account.objects.get(user=request.user) + a = Profile.objects.get(user=request.user) thread_id = request.POST.get("thread_id") data = { - "author": Account.objects.get(user=request.user), + "author": Profile.objects.get(user=request.user), "title": request.POST.get("title", ""), "body": request.POST.get("body", ""), "c_type": request.POST.get("c_type", ""), @@ -112,7 +112,7 @@ def createCivi(request): else: # not a reply, a regular civi c_qs = Civi.objects.filter(thread_id=thread_id) - accounts = Account.objects.filter( + accounts = Profile.objects.filter( pk__in=c_qs.values("author").distinct() ) data = { @@ -145,7 +145,7 @@ def rateCivi(request): """ Use this function to rate a Civi """ civi_id = request.POST.get("civi_id", "") rating = request.POST.get("rating", "") - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) voted_civi = Civi.objects.get(id=civi_id) @@ -218,7 +218,7 @@ def editCivi(request): civi_image = CiviImage.objects.get(id=image_id) civi_image.delete() - a = Account.objects.get(user=request.user) + a = Profile.objects.get(user=request.user) return JsonResponse(c.dict_with_score(a.id)) except Exception as e: return HttpResponseServerError(reason=str(e)) @@ -309,11 +309,11 @@ def uploadphoto(request): @login_required def editUser(request): """ - Edit Account Model + Edit Profile Model """ request_data = request.POST user = request.user - account = Account.objects.get(user=user) + account = Profile.objects.get(user=user) data = { "first_name": request_data.get("first_name", account.first_name), @@ -331,7 +331,7 @@ def editUser(request): account.refresh_from_db() - return JsonResponse(Account.objects.summarize(account)) + return JsonResponse(Profile.objects.summarize(account)) @login_required @@ -341,7 +341,7 @@ def uploadProfileImage(request): form = UpdateProfileImage(request.POST, request.FILES) if form.is_valid(): try: - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) # Clean up previous image account.profile_image.delete() @@ -359,8 +359,8 @@ def uploadProfileImage(request): response = {"profile_image": account.profile_image_url} return JsonResponse(response, status=200) - except Account.DoesNotExist: - response = {"message": f"Account with user {request.user.username} does not exist", + except Profile.DoesNotExist: + response = {"message": f"Profile with user {request.user.username} does not exist", "error": "ACCOUNT_ERROR"} return JsonResponse(response, status=400) except Exception as e: @@ -379,15 +379,15 @@ def clearProfileImage(request): """ This function is used to delete a profile image """ if request.method == "POST": try: - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) # Clean up previous image account.profile_image.delete() account.save() return HttpResponse("Image Deleted") - except Account.DoesNotExist: - return HttpResponseServerError(reason=f"Account with id:{request.user.username} does not exist") + except Profile.DoesNotExist: + return HttpResponseServerError(reason=f"Profile with id:{request.user.username} does not exist") except Exception: return HttpResponseServerError(reason=str("default")) else: @@ -509,9 +509,9 @@ def requestFollow(request): return HttpResponseBadRequest(reason="You cannot follow yourself, silly!") try: - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) target = User.objects.get(username=request.POST.get("target", -1)) - target_account = Account.objects.get(user=target) + target_account = Profile.objects.get(user=target) account.following.add(target_account) account.save() @@ -529,7 +529,7 @@ def requestFollow(request): ) return JsonResponse({"result": data}) - except Account.DoesNotExist as e: + except Profile.DoesNotExist as e: return HttpResponseBadRequest(reason=str(e)) except Exception as e: return HttpResponseServerError(reason=str(e)) @@ -551,9 +551,9 @@ def requestUnfollow(request): try: username = request.POST.get("target") if username: - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) target = User.objects.get(username=username) - target_account = Account.objects.get(user=target) + target_account = Profile.objects.get(user=target) account.following.remove(target_account) account.save() @@ -564,7 +564,7 @@ def requestUnfollow(request): except User.DoesNotExist: return HttpResponseBadRequest(reason=f"User with username {username} does not exist") - except Account.DoesNotExist as e: + except Profile.DoesNotExist as e: return HttpResponseBadRequest(reason=str(e)) except Exception as e: return HttpResponseServerError(reason=str(e)) @@ -578,7 +578,7 @@ def editUserCategories(request): """ try: - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) categories = [int(i) for i in request.POST.getlist("categories[]")] account.categories.clear() for category in categories: @@ -590,7 +590,7 @@ def editUserCategories(request): or "all_categories" } return JsonResponse({"result": data}) - except Account.DoesNotExist as e: + except Profile.DoesNotExist as e: return HttpResponseBadRequest(reason=str(e)) except Exception as e: return HttpResponseServerError(reason=str(e)) diff --git a/project/core/custom_decorators.py b/project/core/custom_decorators.py index 1c12b7837..a02a9a7a2 100644 --- a/project/core/custom_decorators.py +++ b/project/core/custom_decorators.py @@ -1,6 +1,6 @@ from functools import wraps from django.http import HttpResponseBadRequest, HttpResponseRedirect -from accounts.models import Account +from accounts.models import Profile """ USAGE: @@ -28,7 +28,7 @@ def inner(request, *args, **kwargs): def full_account(func): @wraps(func) def inner(request, *args, **kwargs): - account = Account.objects.get(user=request.user) + account = Profile.objects.get(user=request.user) if not account.full_account: return HttpResponseRedirect("/setup") return func(request, *args, **kwargs) diff --git a/project/frontend_views/views.py b/project/frontend_views/views.py index a247bc79f..2a2806581 100644 --- a/project/frontend_views/views.py +++ b/project/frontend_views/views.py @@ -10,8 +10,8 @@ from api.models import Category, Thread, Civi, Activity -from accounts.models import Account -from accounts.forms import UpdateAccount +from accounts.models import Profile +from accounts.forms import UpdateProfile from api.forms import UpdateProfileImage from core.constants import US_STATES from core.custom_decorators import login_required, full_account @@ -25,7 +25,7 @@ def base_view(request): if not request.user.is_authenticated: return TemplateResponse(request, "static_templates/landing.html", {}) - a = Account.objects.get(user=request.user) + a = Profile.objects.get(user=request.user) if "login_user_image" not in request.session.keys(): request.session["login_user_image"] = a.profile_image_thumb_url @@ -77,7 +77,7 @@ def user_profile(request, username=None): except User.DoesNotExist: return HttpResponseRedirect("/404") - form = UpdateAccount( + form = UpdateProfile( initial={ "username": user.username, "email": user.email, @@ -98,7 +98,7 @@ def user_profile(request, username=None): @login_required def user_setup(request): - a = Account.objects.get(user=request.user) + a = Profile.objects.get(user=request.user) if a.full_account: return HttpResponseRedirect("/") # start temp rep rendering TODO: REMOVE THIS @@ -116,7 +116,7 @@ def issue_thread(request, thread_id=None): if not thread_id: return HttpResponseRedirect("/404") - req_acct = Account.objects.get(user=request.user) + req_acct = Profile.objects.get(user=request.user) t = Thread.objects.get(id=thread_id) c_qs = Civi.objects.filter(thread_id=thread_id).exclude(c_type="response") c_scored = [c.dict_with_score(req_acct.id) for c in c_qs] @@ -140,8 +140,8 @@ def issue_thread(request, thread_id=None): "last_name": t.author.last_name, }, "contributors": [ - Account.objects.chip_summarize(a) - for a in Account.objects.filter(pk__in=c_qs.values("author").distinct()) + Profile.objects.chip_summarize(a) + for a in Profile.objects.filter(pk__in=c_qs.values("author").distinct()) ], "category": {"id": t.category.id, "name": t.category.name}, "categories": [{"id": c.id, "name": c.name} for c in Category.objects.all()],