Attempting to migrate an Django ImageField, but failing to migrate

53 views Asked by At

I am currently facing a problem with trying to migrate a Django Image field from a folder named media_root located inside a folder named static_cdn inside of my current project here is what my current file structure looks like as that may help;

veganetworkmain

-----profiles

-------static_cdn

---------media_root

----------test.png

Test.png is a png file that is generated using a picture generation algorithm using Pillow, here is what Test.png actually looks like: enter image description here However what actually happens when I try to implement the code to get the picture into my program using a Django Image Field is that it just becomes white as seen here: enter image description here I had tried methods like using python manage.py makemigrations, python manage.py migrate, changing the static by changing url_patterns and setting and even python ./manage.py makemigrations profiles. Here are the links to each method that I had tried:

Django - makemigrations - No changes detected

Page not found 404 Django media files

And finally here is my code that I am currently working with during this time:

models.py

from django.db import models
from django.shortcuts import reverse
from django.contrib.auth.models import User
from .utils import get_random_word
from django.template.defaultfilters import slugify
from django.db.models import Q
--------------------------------------------------
class Profile(models.Model):
    first_name = models.CharField(max_length=200, blank=True)
    last_name = models.CharField(max_length=200, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(default="no bio here...", max_length=300)
    email = models.EmailField(max_length=200, blank=True)
    country = models.CharField(max_length=200, blank=True)
    test = models.ImageField(default='test.png', upload_to='test/')
    avatar = models.ImageField(default='avatar.png', upload_to='avatars/')
    
    connections = models.ManyToManyField(User, blank=True, related_name='connections')
    slug = models.SlugField(unique=True, blank=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    objects = ProfileManager()

    def get_connections(self):
        return self.connections.all()
    
    def get_connections_num(self):
        return self.connections.all().count()

    def get_posts_num(self):
        return self.posts.all().count()

    def fetch_all_author_posts(self):
        return self.posts.all()
    
    def get_absolute_url(self):
        return reverse("profiles:profile-detail-view", kwargs={"slug":self.slug})

    def get_likes_given_num(self):
        likes = self.like_set.all()
        total_liked = 0
        for item in likes:
            if item.value=='Like':
                total_liked += 1
        return total_liked

    def get_likes_received_num(self):
        posts = self.posts.all()
        total_liked = 0
        for item in posts:
            total_liked += item.liked.all().count()
        return total_liked


    def __str__(self):
        return f"{self.user.username}-{self.created.strftime('%d-%m-%Y')}"
    
    __initial_first_name = None
    __initial_last_name = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__initial_first_name = self.first_name
        self.__initial_last_name = self.last_name
        

    def save(self, *args, **kwargs):
        x = False
        to_slug = self.slug
        if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug == '':
            if self.first_name and self.last_name:
                newSlug = slugify(str(self.first_name) + ' ' + str(self.last_name))
                x = Profile.objects.filter(slug=newSlug).exists()
                while x:
                    newSlug = slugify(newSlug + " " + str(get_random_word()))
                    x = Profile.objects.filter(slug=newSlug).exists()
            else:
                newSlug = str(self.user)
        self.slug = newSlug
        super().save(*args, **kwargs)

STATUS_CHOICES = (('send', 'send'),
                  ('accepted', 'accepted')
)

forms.py

from django import forms
from .models import Profile

class ProfileModelForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('first_name', 'last_name', 'bio', 'avatar', 'test')

myprofile.html

{% extends 'base.html' %}

{% block title %}
My Profile
{% endblock title %}

{% block content %}
<!-- MODAL -->
<div class="ui modal profile mymodal">
  <i class="close icon"></i>
  <div class="header button">
    Update your Profile
  </div>
  <div class="image content">
    <div class="ui medium image">
      <img src="{{profile.avatar.url}}">
    </div>
    <div class="description">
      <div class="ui header">Provide some additional/newest info about you </div>
     <form action="" method="POST" class="ui form" enctype='multipart/form-data'>
        {% csrf_token %}
        {{form.as_p}}
    </div>
  </div>
  <div class="actions">
    <button type='submit' class="ui positive right labeled icon button">
      Update
      <i class="checkmark icon"></i>
    </button>
    </form>
  </div>
</div>

<div class="ui modal theory mymodal">
  <i class="close icon"></i>
  <div class="header">
    Create a Theory through a chat prompt.
  </div>
  <div class="image content">
    <div class="ui medium image">
      <img src="{{profile.avatar.url}}">
    </div>
    <div class="description">
      <div class="ui header">Please input the required information that you would like to simulate your theory from, you will also be able to see your theory being simulated inside of the window below, thank you and have a good day today:</div>
      <img src="{{profile.test.url}}" width="700" height="400">
      <br>
      <button class="ui purple">Create Theory</button>
    </div>
  </div>
  <div class="actions">
    <button type="submit" class="ui positive button">
      Save
    </button>
  </div>
</div>


<div class="ui segment">
    {% if confirm %}
        <div class="ui green message">Your profile has been updated</div>
    {% endif %}
    <h3>my profile: {{request.user}}</h3>
    <div class="ui grid">
        <div class='row'>
            <div class='six wide column'>
                <img class="ui small rounded image" src={{profile.avatar.url}}>
                <div class="row mt-5">
                    <br>
                    <button class='ui secondary' id='modal-btn-1'>Update Profile</button>
                </div>
                <div class="row mt-5">
                    <br>
                    <button class="ui secondary" id="modal-btn-2">Create Theory</button>
                </div>
            </div>
            <div class="ten wide column">
                <table class="ui table">
                    <tbody>
                        <tr>
                            <td>username</td>
                            <td>{{profile.user}}</td>
                        </tr>
                        <tr>
                            <td>first name</td>
                            <td>{{profile.first_name}}</td>
                        </tr>
                        <tr>
                            <td>last name</td>
                            <td>{{profile.last_name}}</td>
                        </tr>
                        <tr>
                            <td>bio</td>
                            <td>{{profile.bio}}</td>
                        </tr>
                        <tr>
                            <td>number of connections</td>
                            <td>{{profile.get_connections_no}}</td>
                        </tr>
                        <tr>
                            <td>number of connections</td>
                            <td>
                                <ul>
                                    {% for connection in profile.get_connections %}
                                        <li>{{connection}}</li>
                                    {% endfor %}
                                </ul>
                            </td>
                        </tr>
                        <tr>
                            <td>number of posts</td>
                            <td>{{profile.get_posts_no}}</td>
                        </tr>
                        <tr>
                            <td>number of likes given</td>
                            <td>{{profile.get_likes_given_no}}</td>
                        </tr>
                        <tr>
                            <td>number of likes received</td>
                            <td>{{profile.get_likes_recieved_no}}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

{% endblock content %}

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = True

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'posts',
    'profiles',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'veganetworkmain.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'profiles.context_processors.profile_pic',
                'profiles.context_processors.invatations_received_num',
            ],
        },
    },
]

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static_project')
]

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "media_root")

Is there something specific that I'm doing wrong, and if I'm doing nothing wrong what functions or methods should I add to this code, so I can fix this troublesome bug? Thank you all very much for your time, any help is appreciated.

1

There are 1 answers

0
Kiarash Gh On

the problem might be in urls.py

your urls.py should looks like this:

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

urlpatterns = [
    # your patterns
]

if settings.DEBUG:     
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I hope this helps you.