Skip to content

Commit

Permalink
Merge pull request #201 from bounswe/kaan-image
Browse files Browse the repository at this point in the history
Adding image to profile and post
  • Loading branch information
kaanguneyli authored May 11, 2024
2 parents aca791f + 4dea9e3 commit e8af4db
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 56 deletions.
Binary file added backend/media/post_images/BoJack_Horseman.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions backend/nba_app/migrations/0003_post_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.4 on 2024-05-09 20:06

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('nba_app', '0002_post'),
]

operations = [
migrations.AddField(
model_name='post',
name='image',
field=models.BinaryField(blank=True, null=True),
),
]
18 changes: 18 additions & 0 deletions backend/nba_app/migrations/0004_alter_post_image.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.4 on 2024-05-09 23:41

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('nba_app', '0003_post_image'),
]

operations = [
migrations.AlterField(
model_name='post',
name='image',
field=models.ImageField(blank=True, null=True, upload_to='post_images/'),
),
]
5 changes: 3 additions & 2 deletions backend/nba_app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ def __str__(self):

class Post(models.Model):
post_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=500, blank=False)
#image = models.ImageField(upload_to='post_images/', blank=True, null=True)
#image = models.BinaryField(blank=True, null=True)
image = models.ImageField(upload_to='post_images/', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
Expand Down
8 changes: 4 additions & 4 deletions backend/nba_app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['user_id', 'username', 'email', 'bio']

model = User #
fields = ['user_id', 'username', 'email', 'bio', 'image']
#

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['username', 'content', 'created_at']
fields = ['user_id', 'content', 'created_at', 'image']
9 changes: 7 additions & 2 deletions backend/nba_app/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from django.urls import path
from . import views

from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
path('signup/', views.sign_up, name='signup'),
Expand All @@ -19,7 +22,9 @@
path('player/', views.player, name='player'),
path('csrf_token/', views.csrf_token, name='csrf_token'),
path('session/', views.session, name='session'),
path('log_out/', views.log_out, name='log_out'),
path('log_out/', views.log_out, name='log_out')
path('post/<int:post_id>/', views.post_detail, name='post_detail'),
path('post/<int:post_id>/comment/', views.create_comment, name='create_comment')
]
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
67 changes: 27 additions & 40 deletions backend/nba_app/views.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.middleware.csrf import get_token
from django.http import JsonResponse, HttpResponse
from django.urls import reverse
from .models import User, Post, Comment, Follow
import requests
from django.db import models

def sign_up(request):
if request.method == "POST":
Expand All @@ -16,7 +16,9 @@ def sign_up(request):
username = request.POST.get("username")
email = request.POST.get("email")
password = request.POST.get("password")

#
profile_picture = request.FILES.get("image")
#
print("username: ", username, "email: ", email, "password: ", password)

if User.objects.filter(email=email).exists():
Expand All @@ -27,9 +29,9 @@ def sign_up(request):
# Return an error httpresponse if username is already taken
return HttpResponse("Username already taken.", status=400)

# Create and save user
user = User.objects.create_user(username=username, email=email, password=password)
print("user created and saved: ", user)
# Create and save user #
user = User.objects.create_user(username=username, email=email, password=password, profile_picture=profile_picture)
print("user created and saved: ", user) #

login(request, user)
print("user_logged in: ", user)
Expand Down Expand Up @@ -61,32 +63,15 @@ def log_out(request):
request.session.flush()
return HttpResponse("Logged out successfully", status=200)

"""

@login_required
def post(request):
if request.method == "POST":
user = request.user
content = request.POST.get("content")
post = Post.objects.create(user=user, content=content)
#if username == "":
# # handle if the user is not logged in
# print("not logged in")
# # return redirect('signup')
text = request.POST.get("post")
print(text)
return render(request, 'post.html')
"""
@login_required
def post(request):
if request.method == "POST":
user = request.user
content = request.POST.get("content")
post = Post.objects.create(user=user, content=content)
#if username == "":
# # handle if the user is not logged in
# print("not logged in")
# # return redirect('signup')
image = request.FILES.get("image")
post = Post.objects.create(user=user, content=content, image=image)
#text = request.POST.get("post")
return HttpResponseRedirect(f'/post/{post.post_id}/')
return render(request, 'post.html')

Expand Down Expand Up @@ -376,12 +361,13 @@ def team(request):
url = 'https://www.wikidata.org/w/api.php'
response = requests.get(url, params = {'action': 'wbgetentities', 'format': 'json', 'ids': id, 'language': 'en'})
data = response.json()
data_entitites_id = data['entities'][id]
try:
name = data['entities'][id]['labels']['en']['value']
name = data_entitites_id['labels']['en']['value']
except:
name = None
try:
venue_temp = data['entities'][id]['claims']['P115']
venue_temp = data_entitites_id['claims']['P115']
venue_id = venue_temp[len(venue_temp)-1]['mainsnak']['datavalue']['value']['id']
response_ven = requests.get(url, params = {'action': 'wbgetentities', 'format': 'json', 'ids': venue_id, 'language': 'en'})
data_ven = response_ven.json()
Expand All @@ -396,12 +382,12 @@ def team(request):
except:
venue = None
try:
coach_id = data['entities'][id]['claims']['P286'][0]['mainsnak']['datavalue']['value']['id']
coach_id = data_entitites_id['claims']['P286'][0]['mainsnak']['datavalue']['value']['id']
coach = get_label(coach_id)
except:
coach = None
try:
division_id = data['entities'][id]['claims']['P361'][0]['mainsnak']['datavalue']['value']['id']
division_id = data_entitites_id['claims']['P361'][0]['mainsnak']['datavalue']['value']['id']
response_div = requests.get(url, params = {'action': 'wbgetentities', 'format': 'json', 'ids': division_id, 'language': 'en'})
data_div = response_div.json()
division = data_div['entities'][division_id]['labels']['en']['value']
Expand All @@ -414,7 +400,7 @@ def team(request):
division = None
conference = None
try:
image_name = data['entities'][id]['claims']['P154'][0]['mainsnak']['datavalue']['value']
image_name = data_entitites_id['claims']['P154'][0]['mainsnak']['datavalue']['value']
image_url = f'https://commons.wikimedia.org/w/index.php?title=Special:Redirect/file/{image_name}&width=300'
except:
image_url = None
Expand Down Expand Up @@ -445,29 +431,30 @@ def player(request):
url = 'https://www.wikidata.org/w/api.php'
response = requests.get(url, params = {'action': 'wbgetentities', 'format': 'json', 'ids': id, 'language': 'en'})
data = response.json()
data_entitites_id = data['entities'][id]
try:
name = data['entities'][id]['labels']['en']['value']
name = data_entitites_id['labels']['en']['value']
except:
name = None
try:
height = data['entities'][id]['claims']['P2048'][0]['mainsnak']['datavalue']['value']['amount']
height = data_entitites_id['claims']['P2048'][0]['mainsnak']['datavalue']['value']['amount']
except:
height = None
try:
date_of_birth = data['entities'][id]['claims']['P569'][0]['mainsnak']['datavalue']['value']['time']
date_of_birth = data_entitites_id['claims']['P569'][0]['mainsnak']['datavalue']['value']['time']
except:
date_of_birth = None
try:
insta = data['entities'][id]['claims']['P2003'][0]['mainsnak']['datavalue']['value']
insta = data_entitites_id['claims']['P2003'][0]['mainsnak']['datavalue']['value']
except:
insta = None
try:
position_lst = data['entities'][id]['claims']['P413']
position_lst = data_entitites_id['claims']['P413']
positions = list_wikidata_property(position_lst)
except:
positions = []
try:
team_lst = data['entities'][id]['claims']['P54']
team_lst = data_entitites_id['claims']['P54']
teams = {}
for item in team_lst:
team_id = item['mainsnak']['datavalue']['value']['id']
Expand All @@ -484,7 +471,7 @@ def player(request):
except:
teams = []
try:
award_lst = data['entities'][id]['claims']['P166']
award_lst = data_entitites_id['claims']['P166']
awards = {}
for item in award_lst:
award_id = item['mainsnak']['datavalue']['value']['id']
Expand All @@ -497,7 +484,7 @@ def player(request):
except:
awards = []
try:
image_name = data['entities'][id]['claims']['P18'][0]['mainsnak']['datavalue']['value']
image_name = data_entitites_id['claims']['P18'][0]['mainsnak']['datavalue']['value']
image_url = f'https://commons.wikimedia.org/w/index.php?title=Special:Redirect/file/{image_name}&width=300'
except:
image_url = None
Expand Down
7 changes: 5 additions & 2 deletions backend/nba_project/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@
]

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:3000', 'http://localhost:3000', 'http://' + os.getenv('DEPLOY_MACHINE_IP') + ':3306', 'http://' + os.getenv('DEPLOY_MACHINE_IP') + ':3000']
CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:3000', 'http://localhost:3000', 'http://' + str(os.getenv('DEPLOY_MACHINE_IP')) + ':3306', 'http://' + str(os.getenv('DEPLOY_MACHINE_IP')) + ':3000']
ALLOWED_HOSTS = ['*', os.getenv('DEPLOY_MACHINE_IP')]
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000', 'http://localhost:3000', 'http://' + os.getenv('DEPLOY_MACHINE_IP') + ':3306', 'http://' + os.getenv('DEPLOY_MACHINE_IP') + ':3000']
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000', 'http://localhost:3000', 'http://' + str(os.getenv('DEPLOY_MACHINE_IP')) + ':3306', 'http://' + str(os.getenv('DEPLOY_MACHINE_IP')) + ':3000']

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
Expand Down Expand Up @@ -151,3 +151,6 @@
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
14 changes: 8 additions & 6 deletions backend/templates/post.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Post</title>
</head>
<body>
<h2>Create Post</h2>
<form method="post">
<h1>Create Post</h1>

<!-- Form for creating new posts -->
<form method="post" enctype="multipart/form-data" action="{% url 'post' %}">
{% csrf_token %}
{{ form.as_p }}
<label for="content">Post:</label><br>
<input type="text" id="content" name="content"><br>
<button type="submit">Submit</button>
<textarea name="content" rows="4" cols="50" placeholder="Enter your post content"></textarea><br>
<input type="file" name="image"><br>
<button type="submit">Post</button>
</form>
</body>
</html>

0 comments on commit e8af4db

Please sign in to comment.