raise ImproperlyConfigured(msg) - django

raise ImproperlyConfigured(msg)
In "additional_app", in "models.py":
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id_user = models.IntegerField()
bio = models.TextField(max_length=500, blank=True)
profileimg = models.ImageField(upload_to='profile_images', default='btm-banner.png')
location = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.user.username
I have created 'media_folder' in "additional_app" and put into img 'btm-banner.png' to django load it if user dont load self picture in profile.
Also i write in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also in 'main_app', in urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now i want make 'migration'
In Terminal:
S:\Programms\Projects\social_app\main_app> py manage.py makemigration
Enter
Result:
django.core.exceptions.ImproperlyConfigured:
additional_app.apps.AdditionalAppConfig.default_auto_field refers to the module 'django.db.media
.BigAutoField' that could not be imported.
img
img

Related

Django is showing me a 404 error instead of my image

my friends, this is my first question here.
So, I follow the Django documentation and some questions here, but the problem keep happening.
I did what was said on other similar questions, like this one, for examaple:
Issue with image in django
But the problem persists.
So, my model looks like this:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True)
picture = models.ImageField(blank = True, null = True, upload_to = user_directory_path)
whatsapp = models.PositiveIntegerField(blank = True, null = True)
My settings looks like this:
MEDIA_ROOT = f"{BASE_DIR}/media"
MEDIA_URL = '/media/'
I added
+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
to the end of my urls.py file:
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import UserList, FeedbackList, DayList, AttractionList, UserDetail, UserProfileList, ProfileDetail
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('users/', UserList.as_view()),
path('user/<str:username>', UserDetail.as_view()),
path('profiles/', UserProfileList.as_view()),
path('profile/<str:user__username>', ProfileDetail.as_view()),
path('feedbacks/', FeedbackList.as_view()),
path('days/', DayList.as_view()),
path('attractions/', AttractionList.as_view()),
path('token/', TokenObtainPairView.as_view()),
path('token/refresh/', TokenRefreshView.as_view()),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
The folder and images are being created on my file system when I add them via the admin, but when I click to see them over there I recieve a 404.
Request URL: http://192.168.15.21:8000/media/uploads/profile_pictures/1-417ee0cb-cd83-4ea6-a692-a4af3b4afcce-eu.jpg
Using the URLconf defined in evento.urls, Django tried these URL patterns, in this order:
event_app/
admin/
The current path, media/uploads/profile_pictures/1-417ee0cb-cd83-4ea6-a692-a4af3b4afcce-eu.jpg, didn’t match any of these.
This is my file structure
I am making a mobile app and serving my data using Django Rest Framework, the images are the only thing giving me a headache right now.
Herer i have change your upload_to = profile_pictures
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True)
picture = models.ImageField(blank = True, null = True, upload_to = profile_pictures)
whatsapp = models.PositiveIntegerField(blank = True, null = True)
I have also change settings as given below
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In your main project app you can add urlpatterns as given below if you have to
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

Dynamic reverse URL name supplied from model Django

I'm trying to reverse(just the way reverse_lazy works) the url_name stored in the SubMenu.link
Here is my code
My Model
class SubMenu(models.Model):
menu = models.ForeignKey(MainMenu, on_delete=models.CASCADE, related_name="submenus")
title = models.CharField(max_length=50)
link = models.CharField(max_length=50, null=True, default="null")
def __str__(self):
return self.title
My root urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('bodys.urls')),
path('blog', include('blogs.urls')),
path('contact', include('contacts.urls')),
path('services/', include('services.urls')),
]

Uploaded dynamic file cannot be found

I uploaded a dynamic picture named "IMG_4606.png" through admin page and when loading it through another app, it is not being found.
setting.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'project_headshots')
MEDIA_URL = '/project_headshots/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")`
models.py
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.ImageField(null=True, blank=True, upload_to="iad")
`
html code
img class="card-img-top" src="{{project.image.url}}" alt=""
ERROR:
`Not Found: /projects/project_headshots/iad/IMG_4606.png
[25/Sep/2019 16:28:34]
"GET /projects/project_headshots/iad/IMG_4606.png HTTP/1.1" 404'

How can i set image path while saving it

when i upload the image from the form it is just saving name of in database not saving the image and uploading to the path, but when i upload the image from database it stores perfectly
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('students.urls')),
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
# Create your models here.
class student_registration(models.Model):
registration_number = models.CharField(primary_key=True,max_length=100)
student_name = models.CharField(max_length=100)
student_father_name = models.CharField(max_length=100)
student_image=models.FileField(default='default.jpg', upload_to='media', blank=True)
views.py
from django.shortcuts import render
from .models import student_registration
from django.contrib import messages
from django.conf import settings
# Create your views here.
def student_registeration(request):
if ("registration_no" in request.POST and "student_name" in request.POST
and "student_fname" in request.POST and "student_image" in request.POST):
registration_no = request.POST["registration_no"]
student_name = request.POST["student_name"]
student_fname = request.POST["student_fname"]
student_image = (settings.MEDIA_URL + request.POST["student_image"],
'JPEG')
s = student_registration(registration_no,student_name, student_fname,
student_image)
s.save()
messages.success(request, f'Your account has been created! You are now
able to log in')
return render(request,'students/student_registration.html')
else:
return render(request, 'students/student_registration.html')
The file upload is stored in request.FILES not request.POST. You can retrieve it in the same way and assign it to the student_image field:
s = student_registration(
registration_number=registration_no,
student_name=student_name,
student_father_name=student_fname,
student_image=request.FILES['student_image'] # Retrieve from request.FILES
)
s.save()
You should also make sure that your form is set to enctype="multipart/form-data.

Django video in template, seems to detect media but not working

Please i have been working on this for a while but don't seem to find the problem. I am trying to get a video from the uploaded files to work on the template,but all i keep getting is a blank video, although when i view the page source or inspect the video element, it seems to be pointing to the right video, and all solutions i have tried to make this work proved abortive.
Below are my codes:
MY MODEL:
class Sermon(models.Model):
topic = models.CharField('Topic', max_length=50)
pub_date = models.DateField('Sermon Date')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
last_edited = models.DateTimeField(auto_now_add=False, auto_now=True)
type = models.CharField('Type', max_length=50, choices=sermon_chioices)
audio = models.FileField(upload_to='audios', default="Not Available", blank=True, validators=[validate_audio_extension], null=True)
video = models.FileField(upload_to='videos', default="Not Available", blank=True)#can be changed if the video will recide in the system
outlines = models.FileField(upload_to="outlines", default="Not Available", blank=True,)
user = models.ForeignKey(User, verbose_name="User", editable=False)
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.topic
def get_absolute_url(self):
#return reverse('sermon_detail', kwargs={'pk': self.pk})
return reverse('sermon_detail', args=[str(self.id)])
MY VIEW:
class SermonDetails(DetailView):
model = Sermon
template_name = 'agonopa/sermon_details.html'
context_object_name = 'sermon'
def get_context_data(self, **kwargs):
context = super(SermonDetails, self).get_context_data(**kwargs)
#context['sermons'] = Sermon.objects.all()
return context
#Sunday Service List
class SundayServiceSermonList(ListView):
model = Sermon
template_name = 'agonopa/sermon.html'
context_object_name = 'sermon_list' #'ss_sermon_list'
queryset = Sermon.objects.filter(type__exact="SUNDAY SERVICE")
def get_context_data(self, **kwargs):
context = super(SundayServiceSermonList, self).get_context_data(**kwargs)
context['title'] = 'Sunday Service'
return context
MY TEMPLATE:
{% if sermon %}
<h3>{{ sermon.topic}}</h3>
{{sermon.outline}}
{{ sermon.pub_date}}
{% endif %}
<video loop class="embed-responsive-item thumbnails" controls>
<source src="{{ MEDIA_URL}}{{sermon.video.url}}" type="video/mp4">
</video>
MY MEDIA SETTINGS:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = os.path.dirname(BASE_DIR)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR,'churchsite_static_root','media_root')
The Server returns things like this in the terminal:
[28/Nov/2015 11:38:10]"GET /agonopa/sermon/3/ HTTP/1.1" 200 377
[28/Nov/2015 11:38:10]"GET /media/videos/wowo_Boyz_5gQAbzG.mp4 HTTP/1.1" 404 2344
Thanks for your help in advance, and for further clarification on the question pls do let me know.
It should be noted, that i have tried many solutions from stakeoverflow, and several blogs but none seems to works, so i had to post it here.
It seems to me that your MEDIA_ROOT is way too high (as in no longer within your project). When I use the settings you use, I get a media root directory of ../../../churchsite_static_root/media_root/ relative to your settings.py file. I would expect churchsite_static_root to be one directory up from settings.py (or at the same level as manage.py).
Go into Django shell and check the media root path to see if it seems reasonable (and confirm that your files are actually there):
python manage.py shell
>>> from django.conf import settings
>>> settings.MEDIA_ROOT
Try the following in your settings.py and let me know if it helps:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'churchsite_static_root', 'media_root')
Be sure you have something like this in your site's urls.py if using python manage.py runserver:
# For Django>=1.8:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# For Django<1.8:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
I simply imported settings, and then static, and also added the if Debug: to my urls.py, thus the program looked as below:
Urls.py:
from django.conf.urls import include, url, patterns
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from agonopa.views import SermonMonthArchiveView, SermonYearArchiveView
urlpatterns = [
# Examples:
# url(r'^$', 'churchsite.views.home', name='home'),
url(r'^$', 'agonopa.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^agonopa/', include('agonopa.urls')),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
That's all to it. Thanks to Mike Covington in all.
Also note, that the media settings, template and other files above didn't change for the whole stuff to work.