Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
any django app that can store sessions ip,browser ..etc and not delete it after the user logout?
i want to store the session history for users in my application , any app can be used ? if not how some thing like that can be made ? i want to have complete history for IPS , browsers , location ..etc i have tried to used Django-sessions app from jassband but it the session is deleted after the user logout thanks -
Django static files don't load in Heroku
I've been hitting my head against the wall with this one. I am trying to deploy a django app to Heroku but css files are not being loaded. What should I do? I get this error message in console Refused to apply style from 'https://sleepy-wildwood-57073.herokuapp.com/static/network/css/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Aside from that heroku logs --tail doesn't seem to show any errors. My settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'network/static'), ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), # Add to this list all the locations containing your static files ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' django_heroku.settings(locals()) MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] One thing is that I am writing styles with scss and then turning them into css with django-sass script. I am not commiting the css files to the repo. Just the scss files. And the page loads, the js scripts load but all the styles won't load! I have no idea what I should do. Please help! Thank you in advance -
how can I access to chatmessage_thread field using Django Rest
How can i access to to chatmessage_thread using Django Rest Framework this is my queryset class ThreadViewSet(viewsets.GenericViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer def list(self, request): objectSerializer = self.serializer_class(Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread').order_by('timestamp'), many=True) return Response(objectSerializer.data) this is my serialize : from rest_framework import serializers from chat.models import Thread from datetime import date class ThreadSerializer(serializers.ModelSerializer): class Meta: model = Thread fields = '__all__' depth = 1 should i add something is my Serializer ? -
Apache/2.4.46 (Ubuntu) Server at Port 80 Error
I have uploaded 2 django projects before and worked perfectly fine to the server, but now for some reason I am receiving this error. I have revisited a tutorial word by word and revised it several times, I am not sure why I keep receving this error: Error for 403 Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at Port 80 Here is the config file: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ahesham/Portfolio/static <Directory /home/ahesham/Portfolio/static> Require all granted </Directory> Alias /media /home/ahesham/Portfolio/media <Directory /home/ahesham/Portfolio/media> Require all granted </Directory> <Directory /home/ahesham/Portfolio/Portfolio> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ahesham/Portfolio/Portfolio/wsgi.py WSGIDaemonProcess Portfolio python-path=/home/ahesham/Portfolio python-home=/home/ahesham/Portfolio/venv WSGIProcessGroup Portfolio </VirtualHost> My question is what am I doing wrong and how to fix it? Please let me know if there are further information required to help assist fixing it -
ManyToMany vs. Intermediary Model for Follower-Following Relationship for Django Rest Framework
I'm working on a blog application with Django Rest Framework (very original I know) and I'm trying to add a followers/following relationship between Users. Currently my UserProfile is implemented as follows: from django.db import models from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver User = get_user_model() class UserProfile(models.Model): """Model For Extending Default Django User Model""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') username = models.CharField(max_length=150, blank=True, null=True) bio = models.TextField(blank=True, null=True) avatar = models.ImageField(blank=True, null=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' @property def full_name(self): return f'{self.user.first_name} {self.user.last_name}' @property def posts_list(self): return self.user.posts.filter(author=self.user) @property def comments_list(self): return self.user.comments.filter(author=self.user) @receiver(post_save, sender=User) def create_profile(sender, instance, created, *args, **kwargs): """Automatically Create A User Profile When A New User IS Registered""" if created: user_profile = UserProfile(user=instance) setattr(user_profile, 'username', instance.username) user_profile.save() My goal is to create a way to link UserProfiles via a Follower/Following relationship. My first idea was to create a ManyToMany relationship like the following: followers = models.ManyToManyField('self', symmetrical=False, blank=True) This makes sense to me, since a UserProfile can have multiple followers and follow multiple people. If I want to serialize this model, then I can use something like the following: class UserProfileDetailsSerializer(serializers.ModelSerializer): posts_list = SerializerMethodField(source="get_posts_list") followers = SerializerMethodField(source="get_followers") class Meta: model = … -
Handling File Upload Errors in Django with DO/S3
I'm using django-storages with DO/S3 to upload a file from curl (later to be a Java client): curl -F some_file=@some_file.txt -F name=some_file --referer https://localhost:8000 -k -i https://localhost:8000/file/request Storage backend configured: storages.backends.s3boto3.S3Boto3Storage My model field: some_file = models.FileField('Some file', blank=True, null=True, upload_to=some_file_path) All this is working fine. I can send a POST request with a file and it uploads to the right place. What I'm trying to figure out is error handling. Since I'm relying on a third party CDN (DO) and library (boto3) to seamlessly upload files, how do I handle errors if the upload fails? I searched Django, DO, django-storages, and AWS docs and couldn't find a good answer. I'd like to handle failed uploads in a user friendly manner, but I'm not even sure how to test this scenario either. If I was calling this file upload in a view, handling the errors in a try block would be straight forward. But since this storage backend is only configured in settings to be the repository for all my uploaded files, how do I handle errors? Do I have to write a custom backend? Any help appreciated. -
Django - Would I be able to use template tags for rendering HTML given URL path conditionals?
I have a blog page with the path /articles/. I would like to use conditional statements to reflect HTML renders. For example, my blog uses a paginator for blog posts. The paginator uses a URL query to retrieve the next page of post objects like so: /articles/?page=2 I would like for the next page to stylize the HTML template differently, hence my reasoning for using a conditional statement. Here is my template that I use: {% if request.path == '/articles/' %} # Render HTML only meant for the above path {% elif request.path != '/articles/'%} # Render HTML for paths that are NOT the exact match above, such as pagination URLs, # search querys, categories filtering, etc... {% endif %} My current bug is that I'm only rendering the first statement: if request.path == '/articles/' for everything, even non exact matches. So this URL path: /articles/?page=2 is rendering: {% if request.path == '/articles/' %} when it should be rendering the elif {% elif request.path != '/articles/'%} due to the not equals sign. Is the above possible to do with only HTML template tags? I know I can use urls.py and edit views but I'm using wagtail CMS and playing with … -
how can i get chatmessage_thread ( i'm using Django Rest Framework )
I'm working on a small project (chat) using Django Rest Framework / Channels I have a small issue, I can't get chatmessage_thread i'm getting this error message : 'QuerySet' object has no attribute 'chatmessage_thread' this is my serialize : from rest_framework import serializers from chat.models import Thread from datetime import date class ThreadSerializer(serializers.ModelSerializer): class Meta: model = Thread fields = '__all__' depth = 1 This is my view: # Rest Framework import datetime from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import viewsets, status, generics, filters from rest_framework.parsers import JSONParser from rest_framework.decorators import action # Model + Serializer from .serializers import ThreadSerializer from chat.models import Thread import pprint class ThreadViewSet(viewsets.GenericViewSet): queryset = Thread.objects.all() serializer_class = ThreadSerializer def list(self, request): objectSerializer = self.serializer_class(Thread.objects.by_user(user=request.user).prefetch_related('chatmessage_thread').order_by('timestamp'), many=True) return Response(objectS this is my model : from django.db import models from django.contrib.auth import get_user_model from django.db.models import Q User = get_user_model() # Create your models here. class ThreadManager(models.Manager): def by_user(self, **kwargs): user = kwargs.get('user') lookup = Q(first_person=user) | Q(second_person=user) qs = self.get_queryset().filter(lookup).distinct() return qs class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = ThreadManager() class Meta: unique_together = ['first_person', … -
How to entering to URLs in Django?
Well I just started today working with the Django app but when I follow his tutorial https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=18317s at 5:20:20 The machine won't let me go to the URL of 127.0.0.1:8000/products/ pyshop\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) products\urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') def new(request): HttpResponse('New Products') -
Django how to show user profile picture publicly?
right now authenticated user can only see his own profile pic. I want every user can see each others profile picture. how to visible profile picture publicly: here is my code: models.py: class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") slug = models.SlugField(max_length=2000,unique=True,blank=True,null=True) profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) my class based views.py data['user_profile']= UserProfile.objects.filter(user=self.request.user) I want to show every user profile pic publicly for my comment section. html {% for i in user_profile %} {{i.first_name}} <img {%if i.profile_pic%}src="{{ i.profile_pic.url }}" {%else%}src="https://www.bootdey.com/img/Content/avatar/avatar7.png"{%endif%} alt="Image" class="img-thumbnail img-circle thumb96" style="max-width: 100px;margin-left: 100px;border-radius: 50%;"> {%endfor%} -
Django simple app causes a circular import error, followed by a definition error
I'm having a seemingly simple definition error whereby the class Automation is not defined. I've created a very simple app called automations which seems to have caused a problem despite barely changing it. Note that there's also another app called messages, with a many:many relationship with the new automations. Automations is just an app with this simple models.py file: from django.db import models from accounts.models import Account from messages.models import Message class Automation(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) messages = models.ManyToManyField(Message) def __str__(self): return self.name And messages is a separate app with this models.py file: from django.db import models from accounts.models import Account # from automations.models import Automation # < FAILS from automations.models import * # < WORKS # from apps.get_model(email_messages, Message) # < FAILS # from django.apps get_model(email_messages, Message) # < FAILS # from django.apps import apps # < FAILS # Automations = apps.get_model('email_messages', 'Messages') # < FAILS class Message(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=128) text = models.TextField() account = models.ForeignKey(Account, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) automations = models.ManyToManyField(Automation) # < PROBLEMATIC LINE def __str__(self): return self.name I initially had this import from automations.models import Automation which caused this … -
Defining the initial values of a ModelForm in Django admin using the contents of the request
I'm trying to pre-fill a ModelForm for the admin interface of my Django application. I'm storing some values in request.session and I'd like to use them to define the initial parameter of my ModelForm. I'm able to retrieve these values in ModelAdmin.render_change_form(self, request, context, *args, **kwargs), but I'm not sure how to pass them to the form. Is it possible to do this? I guess I should use a class factory (taking inspiration from this answer) but I'm not sure where to call it, as ModelAdmin.form is a class attribute, not an instance attribute. Below is a short version of the code I'm using. ## admin.py @admin.register(Game) class GameAdmin(admin.ModelAdmin): # ... # This is where I'd like to pass the value of request.session["prefill_data"] form = GameAdminForm() # inherits forms.ModelForm() def render_change_form(self, request, context, *args, **kwargs): self.change_form_template = 'my_app/admin_game.html' extra_context = {} if "prefill_data" in request.session: # I'm able to access this data here extra_context["something_available_for_the_template"] = something_i_did_with prefill_data # Once I've done what I need I can safely delete the session variable del request.session["prefill_data"] return super(GameAdmin, self).render_change_form(request, context | extra_context, *args, **kwargs) # This is actually the view that populates request.session def admin_prefill(self, request): # [something something] request.session["prefill_data"] = foo # … -
Django Channels: Saving logged in user to session
According to the docs: If you are in a WebSocket consumer, or logging-in after the first response has been sent in a http consumer, the session is populated but will not be saved automatically - you must call scope["session"].save() after login in your consumer code: However, I am having some trouble implementing this. I start by getting my user: def login(form_data): try: user = User.objects.get(username=form_data['username']) except User.DoesNotExist: return "This account doesn't exist." password = form_data['password'] if check_password(password, user.password): return user else: return "Incorrect Password." And then following the directions like so: user = login(form_data) async_to_sync(login)(self.scope, user) self.scope["session"].save() self.send(text_data=to_json({ 'operation': 'set_user', 'success': True, 'message': "Loading User Data", 'object': {'username': user.username} })) And it works to deliver the user to the page and set it up for the life of the consumer. However, it seems that the user is not being saved to the user's session, because when I reload the page, self.scope['user'] once again returns an AnonymousUser object. This is how I've got my asgi.py set up: application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) Likewise, navigating to other pages confirms that I am indeed not logged in. What could I be missing? -
Fetch auto-populated data from a ForeignKey model and use in the form
I am facing one Issue in Django: Below are my codes, In create_support I have created a form, to submit a ticket, I want the Profile to be auto populated post user login and should not display in the drop down, I was able to remove from the drop down by adding exclude in the forms.py, but post form submission profile is still blank, how to resolve this ? How do i fetch logged-in user profile during support ticket submission. models.py class Support(models.Model): profiles = models.ForeignKey(Profile, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=50) email = models.EmailField(null=True) subject = models.CharField(max_length=255, null=True) comments = models.TextField(null=True, blank=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) views.py def support(request): support = request.user.profile.support_set.all() context = { 'support': support } return render(request, 'support.html', context) def createsupport(request): support = request.user.profile.support form = SupportForm(instance=support) if request.method == 'POST': form = SupportForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your Support Query has reached us, will get back to you shortly. ') return redirect('blog:articles') context = { 'form': form } return render(request, 'create_support.html', context) create_supportsupport.html <div class="col-md-9"> <div class="card card-body"> <h5>Create New Ticket:</h5> <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <table border="0"> {{ … -
can you send a subExpand in django?
As you can see, I am making a request to get to viewset ServicioRealizadosOrdenTrabajoTipoViewSet. if you look at the serializer "Servicioserializer", There are 3 expandable_fields that I am using in the frontend endpint sefl._list.... ".....&expand=tecnico&expand=orden_trabajo". lor what I want is to be able to pass a subExpand to "&expand=Orden_trabajo(expand=vehiculo)" something like that. Resume: expand "vehicle" from "Serializer order" from the end point. through the viewSet ServicioPalizadasOrdenTrabajoTipoViewSet class OrdenSerializer(BaseSerializer): foto_derecha = Base64ImageField(required=False, use_url=False) foto_izquierda = Base64ImageField(required=False, use_url=False) foto_frente = Base64ImageField(required=False, use_url=False) foto_atras = Base64ImageField(required=False, use_url=False) foto_panel = Base64ImageField(required=False, use_url=False) class Meta: model = Orden fields = '__all__' expandable_fields = { 'vehiculo': (Vehiculoserializer, { 'many': False }), 'asesor': (Tecnicoserializer, { 'many': False }), 'servicio_orden_registro': (Orden_registroserializer2, { 'many': True }) } class Orden_trabajo(BaseModel): ORDENTIPO = ( (1, 'estandar'), (2, 'garantia'), (3, 'cortesia') ) STATETIPO = ( (1, 'abierta'), (2, 'bodega'), (3, 'revisada'), (4, 'correo'), (5, 'aceptada'), (6, 'parcial'), (7, 'rechazada'), (8, 'orden'), (9, 'incompleto'), (10, 'completo') ) NIVELCOMBUSTIBLE = ( (1, 'Vacio'), (2, 'Primer cuarto'), (3, 'Segundo cuarto'), (4, 'Tercer cuarto'), (5, 'Lleno') ) def number(): no = Orden_trabajo.objects.count() if no == None: return 1 else: return no + 1 vehiculo = models.ForeignKey(Vehiculo, on_delete=models.CASCADE, related_name="vehiculo", null=True) tercero = models.IntegerField(blank=True, null=True) tercero_nombre = models.CharField(max_length=150,default='') … -
Django Rest Framework can't identify serializer field name
This is the problem: I have a serializer field pointing to another serializer. I sending an allright request to server and I get this response: { "purchase_header": [ "This field is required." ] } But the field was sended by POST request (in debugger I can see it). I finded this code in html.py (from DRF): def parse_html_dict(dictionary, prefix=''): """ Used to support dictionary values in HTML forms. { 'profile.username': 'example', 'profile.email': 'example@example.com', } --> { 'profile': { 'username': 'example', 'email': 'example@example.com' } } """ ret = MultiValueDict() regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) for field in dictionary: match = regex.match(field) if not match: continue key = match.groups()[0] value = dictionary.getlist(field) ret.setlist(key, value) return ret Well, when debuging I can see that prefix variable contain "purchase_header" and field variable contain the same "purchase_header" string but de match fail returning None. Very rare... dictionary parameter contain all keys and values. But If you can helpme I appreciate much. This is the rest of significant code: urls.py router = DefaultRouter() router.register(r'cancel-requests', PurchaseCancellationsRequestViewSet, basename='purchase-cancel-requests') router.register(r'invoices', PurchaseViewSet, basename='purchase') urlpatterns = router.urls urlpatterns += [path('payment-headers/', PaymentHeadersListAPIView.as_view( ), name='PaymentHeadersListAPIView')] api.py class PurchaseViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing purchases instances. """ serializer_class = PurchaseSerializer queryset = … -
Django Lambda with Microservices, Breaking Django Project in Lambda functions
I've just started to implement serverless architecture using Django and AWS lambda and It's working perfectly fine now. My project consist of two apps user_onboarding and user_training and structure is as follows : MainApp - user_onboarding - models.py - urls.py - views.py - user_training - models.py - urls.py - views.py - MainApp - urls.py - settings.py - wsgi.py - manage.py - lambda_handler.py - serverless.yml model/s are shared between both the apps, contains one to many, Foreign Key relations and working perfectly fine on Lambda. now, I want to split the apps into two different lambda functions. i.e. user_onboarding in seperate lambda function and user_training in seperate lambda function. what will be the best approach to achieve this? My Questions while I was thinking of it: how my models are going to be shared with lambda functions? does lambda layers is the best option? i) I've tried making layers of both the apps's models like this structure: ``` > python/user_onboarding_models/models.py > python/user_training_models/models.py ``` and when I tried to import models so that I can use to query in ORM like this : from user_onboarding_models.models import *. It gives me error - RuntimeError: Model class user_onboarding_models.models.xxx doesn't declare an explicit app_label and … -
Return a string representation of a model in another model DJango
So I have two models, and if I try the get method on postman for the products, I can only see the product category by ID and I want to see it as text. Any ideas on how to do that? I tried using the def save and then setting the self.name to Product_category.name and then saving it but still getting the same thing.Thanks in advance. class Product_category(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) default_price = models.FloatField(max_length=10) product_category = models.ManyToManyField(Product_category, related_name="products") -
How I limit cart creation to (specific url) "/api/cart/" URL only?
The following class was designed for creating cart and add items to it class CartAPIView(TokenMixin, CartUpdateAPIMixin, APIView): cart = None # get the cart from token otherwise create new cart def get_cart(self): # if the token exist get it from the request token_data = self.request.GET.get('token') # create dummy cart object cart_obj = None # if the get request has token, decode it, get cart_id, return cart object if token_data: # token_dict = ast.literal_eval(base64.standard_b64decode(token_data.encode("utf-8")).decode("utf-8")) token_dict = self.parse_token(token=token_data) cart_id = token_dict.get("cart_id") print(cart_id) try: cart_obj = Cart.objects.get(id=cart_id) except: pass self.token = token_data # If no cart passed in the request it will create new cart object if cart_obj == None: cart = Cart() cart.tax_percentage = 0.075 if self.request.user.is_authenticated: cart.user = self.request.user cart.save() data = { "cart_id": cart.id, } # use the create_token from the mixins to create the token for the new cart self.create_token(data) cart_obj = cart return cart_obj # The entry point for /cart/ API to create & update cart def get(self, request, format=None): # First either i will get the cart data or i wil create new one cart = self.get_cart() self.cart = cart # if the get call has cart and has item it will update the cart self.update_cart() # … -
How to edit the value of a field for a given object? Django
I have a number of votes, and i wont that every time somone clicks on a button that number goes up by one. How to do that? -
generate html page in document pdf multipage django
Good evening everyone if there your help needs I have an html page that I want to convert to PDF in several copies but in the same document. But when I do this it’s the last line of my file that generate then I wanted to have a PDF document so the number of pages is the size of my database -
Serialize Django User in template: Object of type Group is not JSON serializable
I've a Django CBV DetailView that has an embedded Vue app. In the view, I get some of the data and pass it to the template so Vue can access it appropriately. The view data looks like this: def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context["summative"] = get_object_or_404( Summative, id=self.kwargs["summative_id"] ) context["json_requestor"] = model_to_dict(self.request.user) context["json_evaluation"] = model_to_dict(self.object) return context In the template I add it like this: {{ json_requestor|json_script:"requestor-data" }} {{ json_evaluation|json_script:"evaluation-data" }} json_evaluation comes across fine. However the json_requestor is where the error pops up. It gives this error: Object of type Group is not JSON serializable Any thoughts on how to best fix this issue? -
Create a method to update value of fields in django model based on another model
Code I want to update value of Betslip.settled_status to 'Lost', if bet.settlement_status is 'lost' -
ValidationError getting thrown when cascading the deletion of an object
A user always has one default dashboard for each company they are associated with. We prevent the deletion of the last dashboard/ default dashboard by using the below. @receiver(pre_delete, sender=Dashboard) def check_if_default(sender, instance, **kwargs): if instance.is_default: raise ValidationError( 'Default dashboard for a company can not be deleted.') However with this code in place the users can't be deleted as Django tries to cascade this to the model and it raises this ValidationError. Is there some way to prevent this check or to check in the check_if_default if the user is beeing deleted? -
When i put new image to an empty image source it gives me error "ValueError: The 'image' attribute has no file associated with it"
I am using django rest framework, Everything is fine in my code. I can update my file. My main problem is that when i put new image on empty image source it gives me an error like ValueError: The 'image' attribute has no file associated with it. But when i update image with image source it works fine.I want to update my image on empty image source but gives me error like ValueError: The 'image' attribute has no file associated with it Please help me how i solve that error Here is my code: My models.py file: It includes my models fields from django.db import models from django.utils import timezone from .validators import validate_allfile_extension from sessionauthapp.models import User from django.dispatch import receiver import os # from datetime import datetime class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="") user = models.ForeignKey(User, on_delete=models.CASCADE) # time = models.DateTimeField(default=datetime.now) # image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) def __str__(self): return self.title @receiver(models.signals.pre_save, sender=Blog) def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ # if not …