Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django FIlter Alll Children Categories
I have models.py class Category(models.Model): headline = models.CharField(max_length=100) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, related_name='children', null=True, blank=True) admin.py main_cat = Category.objects.filter(pk=1) And now im trying to filter all children categories of main_cat how am i going to do that? -
How do I get translated word in template in django-parler?
On my frontend detail page, in templates I want to get translated words. Since translated fields is located inside translations block class UsefulLinks(TranslatableModel, BaseModel): translations = TranslatedFields( name=models.CharField(verbose_name=_('Useful Link Name'), max_length=255) ) icon = models.ImageField(verbose_name=_('Link Icon'), upload_to='') I don't know how to get translated words in template. <input value="{{ object.name.en }}" name="title_uz" type="text" class="form-control" id="exampleInputEmail1"> I tried to get like with above method, but this doesn't seem to work. Are there any ways to get translated words directly in template just by specifity language code? The only solution I tried is on the backend to use get_context_data in order to get translated words by specifying langauge code like this def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj_id = self.object.id lang_uz = Menu.objects.language('uz').get(id=obj_id) context['title_uz'] = lang_uz.title and passed word to frontend template. But I want to get translated words directly from template just by specifying langauge code. -
Run a django app inside a docker container
I am running succesfully a django app that is hosted inside a docker container. I change something on my code on purpose in order for my code to break. What I need is somehow to see the log of the running code as if I was running this locally on my computer. For example I forgot to import a library and when I run this locally I get a message on the terminal like "ModuleNotFoundError: No module named 'somemodule'". But when i run the same code from inside the container I get no log, just the container fails to start. My question is: How can I get a log for my script from inside the container, so I can debug my code? -
How ListCreateAPIView works?
I am just a new in Django Rest Framework, and i want to clearly understand how ListCreateAPIView works. We just can provide a queryset, serializer_class and it will create read-write end point. I was looking for info on official doc, but didnt`d find what i want. Any information will be helpful for me. -
How to perform Django email threading?
Can someone please share how I can do threading to send an email on a shared hosting service for my Django app? I have tried python threading which works perfectly on localhost but doesn't send an email on cloud hosting. Moreover, I tried looking for celery broker but couldn't find anything on the shared hosting. Can someone suggest how to send an email on the Django app in the background so that the user doesn't have to wait? N.B: Changing the hosting service is not an option. Currently using Namecheap shared hosting. -
Get or Create function, not working in Django
maca = Maca.objects.get_or_create(maca_id=request.POST['maca_id'], defaults={ "maca1": request.POST['maca1'], "maca_id": request.POST['maca_id'], }) this create my object but when I try to access the object created like this maca.id I don't get the id. I want to access the id of the object that is got or that is created. Can someone help me please? -
Make Django ORM automatically fetch properties
Say I have a Post model like this: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text_content = models.CharField() @property def comment_count(self): return self.comments.count() Say I need to get all the data for the post with ID 3. I know that I can retrieve the user along with the post in one query, by doing Post.objects.select_related('user').get(pk=3), allowing me to save a query. However, is there a way to automatically fetch comment_count as well? I know I could use Post.objects.annotate(comment_count=Count('comments')) (which will require me to remove the property or change the name of the annotation, as there would be an AttributeError), however is it possible to make the ORM do that part automatically, since the property is declared in the model? Although I could just add the .annotate, this can get very tedious when there are multiple properties and foreign keys that need to be fetched on multiple places. -
Django URL pattern to manage creation and update in the same view - NoReverseMatch error
I'm facing a 'NeReverseMatch' error that I'm not able to solve, even if I'm quite convinced it's probably a stupid error, something I missed... as I reproduce a pattern I implemented earlier in the same app. The context is the following: I have the same view for creating and updating an object. The difference is that in the second case, I have the id. Thus, related urls look like this (I put the whole file to ensure there is no mismatch with other urls): app_name = "polls" urlpatterns = [ path("", views.index, name="index"), path("get_chart_data/", views.get_chart_data, name="chart_data"), path("set_proxy/", views.set_proxy, name="set_proxy"), path("accept_proxy/", views.accept_proxy, name="accept_proxy"), path("cancel_proxy/", views.cancel_proxy, name="cancel_proxy"), path("sign_up/", views.new_user, name="sign_up"), path("login/", views.login_user, name="login"), path("logout/", views.logout_user, name="logout"), path("<slug:comp_slug>/", views.company_home, name="company_home"), path("<slug:comp_slug>/admin_users/", views.adm_users, name="adm_users"), path("<slug:comp_slug>/admin_load_users/", views.adm_load_users, name="adm_load_users"), path("<slug:comp_slug>/admin_profile/", views.adm_user_profile, name="adm_create_user"), path("<slug:comp_slug>/admin_profile/<int:usr_id>", views.adm_user_profile, name="adm_user_profile"), path("<slug:comp_slug>/change_password/", views.change_password, name="change_password"), path("<slug:comp_slug>/admin_delete_user/<int:usr_id>", views.adm_delete_user, name="adm_delete_user"), path("<slug:comp_slug>/admin_events/", views.adm_events, name="adm_events"), path("<slug:comp_slug>/admin_create_event/", views.adm_event_detail, name="adm_create_event"), path("<slug:comp_slug>/admin_update_event/<int:evt_id>/", views.adm_event_detail, name="adm_event_detail"), path("<slug:comp_slug>/admin_delete_event/<int:evt_id>", views.adm_delete_event, name="adm_delete_event"), path("<slug:comp_slug>/admin_groups/", views.adm_groups, name="adm_groups"), # ===== THE 2 FOLLOWING LINES ARE THE ISSUE ===== path("<slug:comp_slug>/admin_group_detail/", views.adm_group_detail, name="adm_create_group"), path("<slug:comp_slug>/admin_group_detail/<int:grp_id>/", views.adm_group_detail, name="adm_group_detail"), path("<slug:comp_slug>/admin_delete_group/<int:grp_id>", views.adm_delete_group, name="adm_delete_group"), path("<slug:comp_slug>/admin_options/", views.adm_options, name="adm_options"), path("<slug:comp_slug>/<slug:event_slug>/", views.event, name="event"), path("<slug:comp_slug>/<slug:event_slug>/<int:question_no>", views.question, name="question"), path("<slug:comp_slug>/<slug:event_slug>/<int:question_no>/vote", views.vote, name="vote"), path("<slug:comp_slug>/<slug:event_slug>/results", views.results, name="results"), ] The pattern is the same for users management (adm_user_profile view) with no issue. Here is … -
Override a model's DELETE method from real delete to setting a property in Django RESTful framework
We are using a django-rest-framework as our backend. I have a model Product which is the Foreign Key of another Order model, which acts as both a order and an audit log. Now suppose we are not going to sell this Product anymore. We need to apply DELETE method on the Product; and we still want to preserve everything in Order. However, if the Product is really deleted and the on_delete method on it is SET_NULL, then all info that is related to Product is lost. Which is not what I wanted. class Order(models.Model): product = models.ForeignKey(Product, blank=True, null=True, on_delete=models.SET_NULL) So my question is: A common practice in other framework is using soft-delete, i.e. adding a "delete=0" property on Product. And the DELETE method only change the property to "delete=1" rather than real delete. Is it do-able when using django-rest-framework? And how? Is there any other good practices to realize this requirement, i.e. to delete the foreign key while perserving the foreign key's metadata? -
Django Form retrieve data from database
I have a form in Django that enables me to post data to the database. I'd like to create a dropdown button that shows me the previous entries from the database, which I can select re-render the data in the original form, allowing me to update and post back to the database. I'm just starting out with Python, which I think is amazing, but I've not really grasped it yet. So I'm probably doing it completely wrong but here goes. I'm starting with just populating the dropdown. So within my models.py, I have. class Investor(models.Model): investor_name = models.CharField(max_length=255, blank=False) investor_website = models.URLField(max_length=255, blank=False) investor_portfolio = models.URLField(max_length=255, blank=False) investor_comment = models.TextField() def __str__(self): return str(self.investor_name) class showInvestor(models.Model): investorName=models.CharField(max_length=100) class Meta: db_table="apps_investor" Then within my views.py def showInvestor(request): results=showInvestor.objects.all() return render(request,"add_investor.html",{"showInvestor":results}) And then within my HTML template, i have: <div class="col-lg-2"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">Update Existing Investor <i class="mdi mdi-chevron-down"></i></button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for results in showInvestor %} <option> {{results.investor_name}} </option> {% endfor %} </div> </div> </div><!-- end col --> but when I click the drop-down I don't get any entries. What am I doing wrong here? Thanks -
Object doesn't exist in DB after consequential calls
I have the following flow for object creation: A user wants to create an object on a webservice. In order to do it - I check if the user is eligible to pay a fee for it. We make a request to know how much the user should pay. If 0 - user will see the regular Create button, if >0 he will see the PayPal button. User fills in data and in the second case presses the PayPal button. We make 2 consequential API requests: Create an object with the parameter is_draft=True. Return its id. Create an order object and use the id from the previous step. Sometimes we cannot create an order, because the object doesn't exist in DB yet. Django setting: DATABASES["default"]["ATOMIC_REQUESTS"] = True Django models: class Object1(models.Model): name = models.CharField() ... class Object2(models.Model): name = models.CharField() ... class Order(models.Model): user = models.ForeignKey(User) amount = models.DecimalField() #naive polymorphism object1 = models.ForeignKey(Object1) object2 = models.ForeignKey(Object2) # An object will be created after PayPal's call to the webhook endpoint class OrderPayment(models.Model): ... order = models.ForeignKey(Order) The problem is that I cannot call transaction.commit() after any object creation (Object1 or Object2) because I use atomic request and it leads to … -
Import ckeditor could not be resolved
I am trying to use RichTextFields through ckeditor in my django project. What I initially thought would be an easy task has caused me nightmares. I am able to pip install django-ckeditor easily. I have followed all the required steps as per https://pytutorial.com/django-ckeditor including adding to settings.py, adding MEDIA_ROOT etc etc. I have collected static and ran migrations and still nothing seems to be working. I get to the final step where I am importing in my models.py but I get a squiggly yellow underline that says "Import "ckeditor_uploader.fields" could not be resolved". settings.py file: INSTALLED_APPS = [ 'projects.apps.ProjectsConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = "uploads/" urls.py: from projects.views import projects 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 ('projects.urls')), path('users/', include ('users.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] urlpatterns += static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: from django.db import models import uuid from users.models import Profile from *ckeditor_uploader.fields* import RichTextUploadingField class Project (models.Model): owner = models.ForeignKey( Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) … -
get_queryset in ListAPIView retuns blank list
In my app I have two types of users i.e. company and employees. I am trying to filter the queryset based on this like the following: class ProductListAPIView(generics.ListAPIView): serializer_class = ProductSerializer # pagination_class = StandardResultsSetPagination permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): if self.request.user.is_company == 'True': user_company = self.request.user.id emp = list(Employee.objects.filter(company=user_company).values_list('pk', flat=True)) emp.append(user_company) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset elif self.request.user.is_employee == 'True': com = Company.objects.filter(pk=self.request.user.id).pk emp = list(Employee.objects.filter(company=com).values_list('pk', flat=True)) emp.append(com) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset I tried the URL with both employee and company credentials but it always return an empty list but when I use the company code independently it works perfectly. -
How to call file-send API which use FileUploadParser
I am using file upload API with this document https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser I made the class in view.py class FileUploadView(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) and then make url in urls.py urlpatterns += [ re_path(r'^upload/(?P<filename>[^/]+)$', FileUploadView.as_view()) ] Now I can access http://localhost:8008/upload/test.mp3 OK GET is not allowed , but there is not file upload form, how can I test this?? or is there any way to send post request with file by curl or something ?? -
What is best from creating API from mongoDb [closed]
So i have to create a Api from existing mongo Database where we send json request to it like {"dateFrom": "2021-10-01 00:00:00", "dateTo": "2021-10-15 23:59:59", "STATUS":"Pending","AMOUNT":"100"} and api should filter data from mongodb on base of request. and then respond with matching json data back sometime i have to send sum of all the AMOUNT and total results back too as json data. i was using django + pymongo. but i am having issue with speed. i am not sure that django + python + mymongo is right tools for it . i wanna know what else options do i have.i have make +50 api from more then hundred thousand entry's. someone told me express.js is also a good option. but i am confused. -
Error: redefinition of group name 'pk' as group 2; was group 1 at position 38
Using Django Rest Framework, I am creating endpoints for doctor model in my app app_api using ModelViewSet. I am encountering the following error on adding an extra action for updating the is_verified field with verify method having @action decorator. error at /app_api/viewset/doctor/6/ redefinition of group name 'pk' as group 2; was group 1 at position 38 Please find the code below. urls.py router = DefaultRouter() router.register('doctor', views.DoctorViewSet, basename='doctor') urlpatterns = [ path('viewset/', include(router.urls)), path('viewset/<int:pk>', include(router.urls)), ] model.py # Doctor Model class Doctor(models.Model): name = models.CharField(max_length=100) designation = models.CharField(max_length=100) description = models.TextField(blank=True, default='') is_verified = models.BooleanField(default=False, blank=True) serializer.py # Doctor Model Serializer class DoctorModelSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' read_only_fields = ('is_verified',) # Doctor Partial Update Model Serializer class DoctorUpdateVerifyModelSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ('id', 'name', 'is_verified') read_only_fields = ('name',) views.py class DoctorViewSet(viewsets.ModelViewSet): serializer_class = DoctorModelSerializer queryset = Doctor.objects.all() def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'PATCH' and self.action == 'verify': serializer_class = DoctorUpdateVerifyModelSerializer return serializer_class @action(methods=['patch'], detail=True) def verify(self, request, pk=None): serializer = self.get_serializer(self.get_object(), data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) Now when I am adding an extra action for routing the method verify with the @action decorator, I am getting the following error … -
Django ORM group by date and get total value
This is the model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=10, decimal_places=2) This is the query: end_date = timezone.now() start_date = end_date - timedelta(days=7) Transaction.objects.filter( date__range=[start_date, end_date], ) .values("date__date") .annotate(expenditure=Sum("amount")) .values("expenditure", date=F("date__date")) .order_by("date") This is the output: [ { "expenditure": 70.0, "date": "2021-10-28" }, { "expenditure": 20.0, "date": "2021-10-30" } ] But I want something like this as the output: [ { "expenditure": 0.0, "date": "2021-10-26" }, { "expenditure": 0.0, "date": "2021-10-27" } { "expenditure": 70.0, "date": "2021-10-28" }, { "expenditure": 0.0, "date": "2021-10-29" }, { "expenditure": 20.0, "date": "2021-10-30" }, { "expenditure": 0.0, "date": "2021-10-31" }, { "expenditure": 0.0, "date": "2021-11-01" }, ] I know I can process the data after the query but I wanted to know if it is possible to get this output using Django ORM? -
How to make uWSGI main thread not serve requests for the Django web application?
In my Django application, in the __init__.py, I have a class which spins up an event loop. class X: def __init__(self): self.__loop = asyncio.get_event_loop() async def foo(self): ... def do_stuff(self): # some logic here self.__loop.run_until_complete(foo()) In the __init__.py I just have x = X() In my Django views, I do from myapp import x def example_view(request): result = x.do_stuff() return JsonResponse({"result": result}) But the problem is that with uWSGI, if the thread that serves the request is same as that was used during initialization, I get the Django's SynchronousOnlyOperation exception as it detects a running event loop in that particular thread. So my question is, is there a way not to use that initializing thread for serving requests or some other alternative to fix this issue? uwSGI is configured to run multiple processes and multiple threads, with --enable-threads -
django registerForm.is_valid() Does not allow the rest of my code to work
My custom user uses the mobile number as username But when the user wants to get the verification code for his number again, he encounters an error I do not even know where this error came from because I did not write this error views def account_register(request): if request.user.is_authenticated: return redirect("store:home") registerForm = RegistrationForm(request.POST) if request.method == "POST": print(registerForm) if registerForm.is_valid(): registerForm.save(commit=False) username = registerForm.cleaned_data["user_name"] phone_number = registerForm.cleaned_data["phone_number"] password = registerForm.cleaned_data["password"] user = User.object.filter(phone_number=phone_number) if user.count() == 0: new_user = User(phone_number=phone_number) new_user.username = username new_user.phone_number = phone_number new_user.set_password(password) new_user.is_active = False new_user.save() otp_user = f"{new_user.otp}" print(otp_user) send_sms(otp_user, new_user.phone_number) elif not user.phone_number_verified: otp_user = f"{user.otp}" print(otp_user) send_sms(otp_user, user.phone_number) return render(request, "account/verificationpage.html", {"form": registerForm}) else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm}) forms class RegistrationForm(forms.ModelForm): user_name = forms.CharField( min_length=4, max_length=50, help_text='Required' ) phone_number = forms.CharField(max_length=11, help_text='Required', validators=[RegexValidator(regex=r'09(\d{9})$')], ) password = forms.CharField(widget=forms.PasswordInput) def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if User.objects.filter(phone_number=phone_number, is_active=False).exists(): raise forms.ValidationError( 'Please use another phone number, that is already taken') return phone_number error User with this Phone number already exists -
how to split a model field into two additional fields in django
I have a simple model like this: class Place(models.Model): location = LocationField( map_attrs={"style": "mapbox://styles/mightysharky/cjwgnjzr004bu1dnpw8kzxa72", "center": (17.031645, 51.106715)}) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) the location field gets a latitude,longitude of a selected loction using a mapbox api. when, submitted, it gets saved like this: location = (43.12,54,12) I want to split this output and save it into latitude and longitude field. how do I write a pre_save method in order to do this? -
Upload file on Django REST framework default view
I am using Django REST framework. It makes UI easily api_view like this @api_view(['POST', 'GET']) def uploadFile(request): data = {'meta':'upload','status':1} return Response(response) There appears form automatically. Is it possible to add file upload form on this?? I have found samples of Django REST framework and some frontend, however couldn't find the form using default view. -
DRF Serializer doesn't recieve value from request for ManyToMany field
My Model is class ChatRoom(models.Model): name = models.CharField(max_length=55, verbose_name='Имя чата', unique=True) users = models.ManyToManyField( CustomUser, verbose_name='Пользователи', related_name='user_chatrooms', null=True ) My Serializer for this model class ChatRoomSerializer(serializers.ModelSerializer): users = UserInfoSerializer(many=True, read_only=False) class Meta: model = ChatRoom fields = [ 'name', 'users' ] View looks @api_view(['POST']) @permission_classes([IsAuthenticated]) def api_create_chat(request): if request.method == 'POST': serializer = ChatRoomSerializer(data=request.data) data = {} if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I do request (here is body) <QueryDict: {'name': ['benny'], 'users': ['11,1']}> In this case I recieve Error {'users': [ErrorDetail(string='This field is required.', code='required')]} And I can't understand what is wrong here. When I change parameter to read_only=True in UserInfoSerializer it works, but it doesn't add user to new Chat object. { "name": "benny", "users": [] } -
Unable to execute .sh file from docker container in Windows
I am using Windows 10, and working on a Django Project with Docker. If I run a python command from inside docker container, it runs perfectly. E:\path>docker exec -it my_docker_container bash root@701z00f607ae:/app# python manage.py makemigrations authentication No changes detected in app 'authentication'enter code here But when I try to run same command using a .sh file, it gives different output. root@701z00f607ae:/app# cat ./migration_script.sh python manage.py makemigrations authentication root@701z00f607ae:/app# ./migration_script.sh '. installed app with label 'authentication Note: Executing ./migration_script.sh works perfectly on Linux based system. -
Django "NotImplementedError: `to_internal_value()` must be implemented" when sending a patch request
I'm trying to get an updated normalized resource when I update a resource using patch. (Using APIRequestFactory in my TestCase tests e.g self.factory.patch) LoadBaseSerializer inherits BaseSerializer and using to_representation. I'm doing this to return a customized serializer. However, I keep getting that annoying error. The patch request contains {'carrier' : 2 }. I expect to return the whole serialized resource, but I guess this only works for GET requests. How am I able to get this work for PATCH/POST methods? View: class LoadUDView(RetrieveUpdateDestroyAPIView): serializer_class = NormalizedLoadSerializer queryset = Load.objects.all() My serializer looks like this: # custom serializer class NormalizedLoadSerializer(LoadBaseSerializer): # not working, still get error def to_internal_value(self, data): load_data = data['carrier'] return super().to_internal_value(load_data) def to_representation(self, instance): # dict values serialized using ModelSerializer data = dict( contacts=self.get_driver_contacts(instance.carrier), drivers=self.get_drivers(instance.carrier), income = IncomeSerializer(instance.income, read_only=True).data, expense = ExpenseSerializer(instance.expense, read_only=True).data, stops = StopSerializer(instance.stops, many=True, read_only=True).data, load=LoadSerializer(instance, read_only=True).data, income_line_items= self.get_income_line_items(instance), expense_line_items= self.get_expense_line_items(instance), addresses=self.get_addresses(instance) ) return data LoadBaseSerializer: # inherit BaseSerializer and added helper functions class LoadBaseSerializer(serializers.BaseSerializer): def get_income_line_items(self, instance): income = instance.income.income_line_items.all() return IncomeLineItemSerializer(income, many=True).data def get_expense_line_items(self, instance): expense = instance.expense.expense_line_items.all() return ExpenseLineItemSerializer(expense, many=True).data def get_addresses(self, instance): data = [stop.address for stop in instance.stops.all()] return AddressSerializer(data, many=True).data def get_driver_contacts(self, carrier): data = [driver.contact for driver in … -
why isn't django creating my media directory through my update form ,but works fine when is use admin panel?
im trying to upload a profile picture and it works fine when using the admin panel but when is use my template form it give the wrong path(i know this because i displayed it to check the url) like so... <p>{{user.userprofile.profile_image.url}}</p> output on html page: /media/check.png when it should instead be: /media/images/check.png Note: everything else works fine on my form and it even shows that the image url was update in the admin panel but only shows the image name and not (images/img_name.png) as it should form: <form method="post" action="{%url 'profile-view' username=user.username%}" enctype="multipart/form-data" class="myOverlayForm"> {%csrf_token%} <label for="id_profile_image">Profile Image: <i class="fa fa-upload" style="font-size: 30px;"></i></label> <input type="file" name="profile_image" accept="image/*" id="id_profile_image"> <div class="form-group"> <label for="bioInput">Bio: </label> {%if form.errors%} <div class="alert alert-warning alert-dismissible fade show my_error" role="alert"> <strong>{{form.errors.bio}}</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {%endif%} <div class="form-group"> </div> <input type="text" class="form-control" name="bio" maxlength="150" minlength="25" id="id_bio"> <small id="bioHelp" class="form-text text-muted">Please avoid to putting out very personal information.</small> </div> <div class="form-group"> <label for="bioInput">Age:</label> <input type="number" class="form-control" name="age" placeholder="Enter Age"> <small id="ageHelp" class="form-text text-muted">Note that this has nothing to do with age restriction, CLASSY is available to everyone☺.</small> </div> <button type="submit" name="update_profile_details" class="btn btn-block btn_update">Update</button> </form> view function: views.py def profile_view(request,username): try: profileForm = …