Failed - No file Downloading uploaded files in Django - django

I have a model here in Django in which an entity can have several uploaded files:
from django.db import models
from model_utils.models import TimeStampedModel
from .managers import ProviderManager
class Provider(TimeStampedModel):
full_name = models.CharField('Nombre', max_length=100, unique=True)
phone1 = models.CharField("Teléfono", max_length=50, blank=True, null=True)
phone2 = models.CharField("Teléfono", max_length=50, blank=True, null=True)
email1 = models.EmailField("Email", max_length=100,
blank=True, null=True)
email2 = models.EmailField("Email", max_length=100,
blank=True, null=True)
bank_info = models.TextField(
"Info Banco", max_length=250, blank=True, null=True)
objects = ProviderManager()
class Meta:
verbose_name = "Proveedor"
verbose_name_plural = "Proveedores"
ordering = ["full_name"]
def __str__(self):
return "Nombre: "+self.full_name
def get_provider_files_names(self):
provider_files = self.provider_files.all()
file_list = []
for f in provider_files:
# print(f.file.name.split('/')[-1])
file_list.append(f.file.name.split('/')[-1])
return file_list
def get_provider_files_urls(self):
provider_files = self.provider_files.all()
file_list = []
for f in provider_files:
file_list.append(f.file.url)
return file_list
class ProviderFiles(TimeStampedModel):
file = models.FileField(upload_to="provider_files/%Y/%m/%d")
provider = models.ForeignKey(
Provider, on_delete=models.CASCADE, related_name='provider_files')
class Meta:
verbose_name = "Archivos Proveedor"
verbose_name_plural = "Archivos Proveedores"
def __str__(self):
return "Nombre Proveedor: "+self.provider.full_name
So then in my html I would like to access entity files and give the user links to download this files:
<td>
Download File
</td>
So then when download starts, it fails with error Failed - No file (file exists)
Also important, if I access admin, and check uploaded files and open them, page says not found
http://localhost:8000/media/provider_files/2021/02/24/Catalogo_2021_R0oiQHD.png

Adding the last line to main urls.py solved the problem:
from django.contrib import admin
from django.urls import path, re_path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
# users app
re_path('', include('applications.users.urls')),
re_path('', include('applications.home.urls')),
re_path('', include('applications.clients.urls')),
re_path('', include('applications.providers.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

URL for Django filtering get requests

I'm making a filtering function for a database I'm working with. I'm wondering how I can access the request url.
Here is the code for the models.
from django.db import models
class User(models.Model):
username = models.CharField(max_length=20, null=True)
account_type = models.CharField(max_length=30, null=True)
first_name = models.CharField(max_length=30, null=True)
last_name = models.CharField(max_length=30, null=True)
email = models.EmailField(max_length=254, null=True)
class Interest(models.Model):
interest = models.CharField(max_length=200, null=True)
listing_account = models.ForeignKey(ListingAccount, related_name='interests', on_delete=models.CASCADE, null=True)
def __str__(self):
return f"{self.interest}"
Below is the filtering function in views.py. How can I find the URL path to this?
class AccountFilterViewSet(generics.ListAPIView):
queryset = ListingAccount.objects.all()
serializer_class = ListingAccountSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['first_name']
URL patterns are defined in the urls.py. To find the URL path to the AccountFilterViewSet view, you need to locate urls.py that maps to the view. If not found, you must define it.
Example:
from django.urls import path
from .views import AccountFilterViewSet
urlpatterns = [
path('accounts/', AccountFilterViewSet.as_view(), name='accounts'),
]
Assum you in localhost and use port 8000.
URL path of this is: localhost:8000/accounts/

Django rest framework not returning all fields

I am trying to make a model that stores favorite shows for users, and I have been using viewsets. I have a users and shows viewset that work just like I expect them to, and I have another model that simply stores relationships between users and shows. When I add that as a viewset though, I get the id, and user, and I don't get a show.
Here are the results for the favorites:
[
{
"id":2,
"user":{
"username":"poduck",
"first_name":"",
"last_name":"",
"email":"poduck#gmail.com",
"image":null,
"url":"http://0.0.0.0:8000/api/users/poduck/?format=json"
}
}
]
There isn't even a show field. It's not like the data isn't there either. I have been able to use queries on the data with no trouble. I have access to both the show and the user from the favorite.
I thought that maybe that the fact that the show points to a user, and the favorite points to a user that there may be some circular conflict there, but beyond excluding the user field from the Show serializer, I don't know what to do to fix that, and yes, I did try excluding it from the Show serializer.
shows.models:
from django.db import models
from django.utils.translation import gettext_lazy as _
from localflavor.us.models import USStateField, USZipCodeField
from users.models import User
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Show(models.Model):
# Information
title = models.CharField(_("Title"), blank=False, max_length=255)
location = models.CharField(_("Location Name"), blank=False, max_length=255)
image = models.ImageField(upload_to='show_images', blank=True)
description = models.TextField(_("Description"), blank=False)
start_date = models.DateField(_("Start Date"), blank=False)
end_date = models.DateField(_("End Date"), blank=False)
registration_start = models.TimeField(_("Registration Start Time"), blank=False)
registration_end = models.TimeField(_("Registration End Time"), blank=False)
start_time = models.TimeField(_("Spectator Start Time"), blank=False)
end_time = models.TimeField(_("Spectator End Time"))
address = models.CharField(_("Show Address"), blank=False, max_length=255)
city = models.CharField(_("City"), blank=False, max_length=255)
state = USStateField(_("State"), blank=False, max_length=2)
zip = USZipCodeField(_("Zip Code"), blank=False)
contact_name = models.CharField(_("Contact name"), blank=True, max_length=255)
contact_email = models.EmailField(_("Contact Email"), blank=True, max_length=255)
contact_phone = PhoneNumberField(_("Contact Phone"), blank=True)
website = models.URLField(_('Official website'), blank=True)
entry_fee = models.DecimalField(_('Entry fee'), default=0.00, blank=False, decimal_places=2, max_digits=10)
spectator_entry_fee = models.DecimalField(_('Spectator entry fee'), default=0.00, blank=False, decimal_places=2, max_digits=10)
trophies = models.BooleanField(_("Trophies or Ribbons Awarded"), default=False)
dash_plaques = models.BooleanField(_("Dash Plaques Given"), default=False)
dash_plaque_quantity = models.IntegerField(_("Quantity of dash plaques to be given"), null=True, blank=True)
door_prizes = models.BooleanField(_("Door Prizes"), default=False)
judging = models.BooleanField(_("Professional Judging"), default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.title}"
class Favorite(models.Model):
show = models.ForeignKey(Show, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.show.title}"
shows.api.serializers:
from rest_framework import serializers
from shows.models import Show, Favorite
from users.api.serializers import UserSerializer
class ShowSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Show
fields = '__all__'
class FavoriteSerializer(serializers.ModelSerializer):
show = ShowSerializer(many=True, read_only=True)
user = UserSerializer()
class Meta:
model = Favorite
fields = '__all__'
shows.api.viewsets:
from car_show_helper.shows.models import Show
from .serializers import ShowSerializer, FavoriteSerializer
from rest_framework import viewsets
class ShowViewSet(viewsets.ModelViewSet):
queryset = Show.objects.all()
serializer_class = ShowSerializer
class FavoriteViewSet(viewsets.ModelViewSet):
queryset = Show.objects.all()
serializer_class = FavoriteSerializer
And finally the api_router:
from django.conf import settings
from rest_framework.routers import DefaultRouter, SimpleRouter
from car_show_helper.users.api.views import UserViewSet
from car_show_helper.shows.api.viewsets import ShowViewSet, FavoriteViewSet
if settings.DEBUG:
router = DefaultRouter()
else:
router = SimpleRouter()
router.register("users", UserViewSet)
router.register("shows", ShowViewSet, basename="shows")
router.register("favorites", FavoriteViewSet, basename="favorites")
app_name = "api"
urlpatterns = router.urls
Any help would be appreciated.
First, change queryset inside FavoriteViewSet
class FavoriteViewSet(viewsets.ModelViewSet):
queryset = Show.objects.all()
serializer_class = FavoriteSerializer
to
queryset = Favorite.objects.all()
Second, remove many=True from:
show = ShowSerializer(read_only=True, many=True)

Django admin page with summer note editor causing toggle to expand making it look odd

I currently installed django summer note on a blog. It loads fine, and I see no errors in console, but it looks like this ..
The main admin loads fine, it's just the create post page.
My admin.py file in the blog looks like this
from django.contrib import admin
from .models import Post, Newsletter
from django_summernote.admin import SummernoteModelAdmin
class PostAdmin(SummernoteModelAdmin):
list_display = ('title', 'slug', 'status', 'created_on')
list_filter = ('status', 'created_on')
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
summernote_fields = ('content',)
admin.site.register(Post, PostAdmin)
class NewsletterAdmin(admin.ModelAdmin):
list_display = ('email', 'confirmed')
admin.site.register(Newsletter, NewsletterAdmin)
And the post models are
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="blog_posts"
)
updated_on = models.DateTimeField(auto_now=True)
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ["-created_on"]
def __str__(self):
return self.title
def get_absolute_url(self):
from django.urls import reverse
return reverse("post_detail", kwargs={"slug": str(self.slug)})
class Newsletter(models.Model):
email = models.EmailField(null=False, blank=True, max_length=200, unique=True)
conf_num = models.CharField(max_length=15)
confirmed = models.BooleanField(default=False)
def __str__(self):
return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)"
For some reason my admin CSS wasn't fully copied. So make sure when you collect static that you pass it to the static if you are using nginx correctly.

Django media files not loading when debug is False on Cpanel

I am trying to show my media files for over a week and tried all stackoverflow solutions yet nothing. My project is hosted on Cpanel, i tried giving the media the absolute path, tried to put them on the public_html folder, nothing. Plus my static files are served without issue, but the media files doesn't even show in the source in developer tools (in normal case there should be one there), when debug is true it works perfectly fine but when debug is false it does not. Any ideas please?
part of my settings.py
import os
from django.contrib.messages import constants as messages
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
CSRF_COOKIE_SECURE = config('CSRF_COOKIE_SECURE')
SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE')
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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',
'whitenoise.middleware.WhiteNoiseMiddleware'
]
STATIC_URL = '/static/'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
CKEDITOR_UPLOAD_PATH = 'uploads/'
MEDIA_URL ='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
INTERNAL_IPS = ['127.0.0.1', '::1', '0.0.0.0']
project urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('panier/', include('cart.urls', namespace='cart')),
path('commande/', include('orders.urls', namespace='orders')),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('coupon/', include('coupons.urls', namespace='coupons'))
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
if settings.DEBUG == True:
import debug_toolbar
urlpatterns += [path('__debug__/', include(debug_toolbar.urls)),]
some of my models
from django.db import models
from django.urls import reverse
from django.utils import timezone
import datetime
from django.db.models import F
from django.conf import settings
import os
from django.utils.deconstruct import deconstructible
from django.core.validators import MinValueValidator
from ckeditor.fields import RichTextField
from django.utils.safestring import mark_safe
PRODUCT_STATUS = (
('N', 'Nouveau'),
('P', 'Promotion'),
('S', 'Sans Status')
)
#deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
filename = 'product_{0}_{1}'.format(instance.user.id, filename)
# return the whole path to the file
return os.path.join(self.path, filename)
def solution_directory_path(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/solutions/YEAR/MONTH/DAY/solution_id_<filename>
solution_sub_path = 'solutions/{0}/{1}/{2}/solution_{3}_{4}'.format(year, month, day, instance.id, filename)
solution_full_path = os.path.join(settings.MEDIA_ROOT, solution_sub_path)
if os.path.exists(solution_full_path):
os.remove(solution_full_path)
return solution_sub_path
def product_directory_path(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/produits/YEAR/MONTH/DAY/produit_<produit_id>_<filename>
product_sub_path = 'produits/{0}/{1}/{2}/product_{3}_{4}'.format(year, month, day,instance.product_id, filename)
product_full_path = os.path.join(settings.MEDIA_ROOT, product_sub_path)
if os.path.exists(product_full_path):
os.remove(product_full_path)
return product_sub_path
def product_directory_path_second_picture(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/produits/YEAR/MONTH/DAY/produit_<produit_id>_<filename>
product_sub_path = 'produits/{0}/{1}/{2}/product_{3}_photo_2_{4}'.format(year, month, day,instance.product_id, filename)
product_full_path = os.path.join(settings.MEDIA_ROOT, product_sub_path)
if os.path.exists(product_full_path):
os.remove(product_full_path)
return product_sub_path
def product_file_directory_path(instance, filename):
date_fields = str(datetime.date.today()).split('-')
year = date_fields[0]
month = date_fields[1]
day = date_fields[2]
# file will be uploaded to MEDIA_ROOT/produits/YEAR/MONTH/DAY/produit_<produit_id>_<filename>
product_sub_path = 'fichers/{0}/{1}/{2}/product_{3}_{4}'.format(year, month, day,instance.product_id, filename)
product_full_path = os.path.join(settings.MEDIA_ROOT, product_sub_path)
if os.path.exists(product_full_path):
os.remove(product_full_path)
return product_sub_path
# custom product manager : have to use it for search filtering
class ProductManager(models.Manager):
def get_queryset(self):
return super(ProductManager, self).get_queryset()\
.filter(stock__gte=1, available=True)
class Solution(models.Model):
name = models.CharField( max_length=50)
slug = models.SlugField( max_length=70)
photo = models.ImageField(verbose_name='Photo de la solution', upload_to=solution_directory_path, blank=True)
photo_2 = models.ImageField(verbose_name='Photo 2 de la solution', upload_to=solution_directory_path, blank= True)
description = RichTextField(verbose_name='Text en plus', blank= True, null=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("produit", args=[self.slug])
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'Catégorie'
verbose_name_plural = 'Catégories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("product-by-cat", args = [self.slug])
class Product(models.Model):
product_id = models.CharField(max_length= 50, blank=False, null= False, unique=True, default='',verbose_name='Numéro du Produit')
name = models.CharField(max_length=50, verbose_name = 'Nom du Produit', db_index=True)
slug = models.SlugField(max_length=70, verbose_name= 'Slug')
solution = models.ForeignKey(Solution, on_delete=models.SET_NULL, verbose_name='Solution', default='', null=True)
category = models.ForeignKey(Category, on_delete= models.CASCADE, related_name="products" ,verbose_name='Catégorie')
sub_title = models.CharField(max_length=100, verbose_name=("Sous titre"), blank= True)
description = RichTextField(verbose_name='Description', blank= True, null=True)
sup_info = RichTextField(verbose_name='Informations Supplémentaires', blank= True, null=True)
photo = models.ImageField(verbose_name='Photo du Produit', upload_to= product_directory_path, blank=True)
photo_2 = models.ImageField(verbose_name='Photo du Produit 2', upload_to= product_directory_path_second_picture, blank=True)
file_1 = models.FileField(verbose_name='Fiche Technique', upload_to=product_file_directory_path, blank= True)
price = models.DecimalField(verbose_name='Prix', max_digits=10, decimal_places=2, validators = [MinValueValidator(0)], blank=False, null=False)
available = models.BooleanField(verbose_name='Disponibilité', default=True)
status = models.CharField(choices= PRODUCT_STATUS, max_length=50, default='S' , blank=False, null = False, verbose_name="Status")
created = models.DateTimeField(verbose_name='Date de Création', auto_now_add=True)
updated = models.DateTimeField(verbose_name='Date de dernière mise à jour', auto_now=True)
stock = models.PositiveIntegerField(verbose_name='Stock', validators= [MinValueValidator(0)], default=0, blank=False, null=False )
objects = models.Manager() # The default manager.
show = ProductManager() # Our custom manager
class Meta:
ordering = ('name',)
verbose_name = 'Produit'
verbose_name_plural = 'Produits'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("produits", args=[self.slug])
def get_description(self):
return mark_safe(self.description)
def get_sup_info(self):
return mark_safe(self.sup_info)
class ContactForm(models.Model):
name = models.CharField(verbose_name='Nom complet', max_length=100)
phone = models.CharField(verbose_name="Téléphone" , max_length=25)
email = models.EmailField(verbose_name="Email", null=True, blank = True)
subject = models.CharField(verbose_name="Sujet", max_length=50, blank=False)
message = models.TextField(verbose_name="Sujet", blank=False, null=False)
date_sent = models.DateTimeField(verbose_name="Date", auto_now_add=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Formulaire de Contact'
class Post(models.Model):
titre = models.CharField(max_length=200)
slug = models.SlugField(max_length=100)
intro = models.CharField(max_length=200, blank=True)
image = models.ImageField(verbose_name='Image' ,upload_to='slides/', blank= True)
text = RichTextField(verbose_name='Article', blank= True, null=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.titre
You can't use whitenoise to serve your media files: https://github.com/evansd/whitenoise/issues/62 You'll need to configure your server to have apache or nginx or something similar serve those media files from your media directory.

Django models: Fields name clashes

I am facing an error in one of my Django practice projects.
Following are my apps and respective models:
Project name: django03
app: home
home/model.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
User = settings.AUTH_USER_MODEL
HOME_TYPE = (
('1','1'),
('2','2'),
('3','3'),
)
class Home(models.Model):
home_owner = models.ForeignKey(User,null=False, verbose_name='Owner')
hometype= models.CharField(max_length=100, null=False, default=1,
choices=HOME_TYPE, verbose_name='Home Type')
licenseid= models.CharField(max_length=200, null=False, unique=True,
verbose_name='License ID')
archive = models.BooleanField(default=False)
def __str__(self):
return self.licenseid
app: furniture
furniture/model.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
# Create your models here.
User = settings.AUTH_USER_MODEL
FURNITURE_DATA_IMPORT_SOURCE= (
('0', '0'),
('1', '1'),
('2', '2'),
)
class Furniture(models.Model):
furniture_owner = models.ForeignKey(User, verbose_name='User')
furniture_imported_via = models.CharField(max_length=200, default="0", null=False, choices=FURNITURE_DATA_IMPORT_SOURCE, verbose_name='Source of import')
furniture_title = models.CharField(max_length=100, null=False, verbose_name='Furniture title')
furniture_description = models.TextField(max_length=250, verbose_name='Furniture description')
archive = models.BooleanField(default=False)
def __str__(self):
return self.furniture_title
app:mappings
mappings/model.py
from __future__ import unicode_literals
from django.db import models
from home.models import Home
from furniture.models import Furniture
class HomeFurnitureMapping(models.Model):
home = models.OneToOneField(
Home,
on_delete=models.CASCADE,
null=False,
unique=True,
verbose_name='Home'
)
furniture = models.OneToOneField(
Furniture,
on_delete=models.CASCADE,
null=False,
unique=True,
verbose_name='Furniture'
)
app: furnitureupdates
furnitureupdates/model.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from mappings.models import HomeFurnitureMapping
# Create your models here.
class FurnitureUpdate(models.Model):
mapping_id = models.OneToOneField(
HomeFurnitureMapping,
on_delete=models.CASCADE,
null=False,
unique=True,
verbose_name='Mapping ID'
)
update_status = num_pages = models.IntegerField(null=False, default=1)
update_date = models.DateField(auto_now_add=True, null=False, verbose_name='Update date')
update_time = models.TimeField(auto_now_add=True, null=False, verbose_name='Update time')
def __str__(self):
return self.mapping_id
When I try to migrate the FurnitureUpdate model, I get the following error:
ERRORS:
furnitureupdates.FurnitureUpdate.num_pages: (models.E006) The field 'num_pages' clashes with the field 'num_pages' from model 'furnitureupdates.furnitureupdate'.
I am not understanding from where the num_pages field is appearing. Please guide me, how to resolve this issue.
You need to update this;
update_status = num_pages = models.IntegerField(null=False, default=1)
to
update_status = models.IntegerField(null=False, default=1)
or;
num_pages = models.IntegerField(null=False, default=1)