Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django quiz application with different types of questions
I am building Django quiz application that will contain questions of 3 types of answers: Single option answer; Multiple option answer; Text answer; I am not sure how should I design django models for such pattern. At the moment my models look like this: class Question(CoreModel, models.Model): TYPES = ( (1, 'radio'), (2, 'checkbox'), (3, 'text'), ) type = models.CharField(max_length=8, choices=TYPES, default='radio') text = models.CharField(max_length=2048, null=False, blank=False) class Choice(CoreModel, models.Model): question = models.ForeignKey(Question, on_delete=models.DO_NOTHING) text = models.CharField(max_length=2048, null=False, blank=False) correct = models.BooleanField(default=False) class Answer(CoreModel, models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) question = models.ForeignKey(Question, on_delete=models.DO_NOTHING) choice = models.ForeignKey(Choice, on_delete=models.DO_NOTHING) text = models.CharField(max_length=2048, null=False, blank=False) created = models.DateTimeField(auto_now_add=True) But it looks like it will not work as expected. I really don't like 'choice' and 'text' fields at the same time in my Answer model but that’s all I could think of. Any ideas or suggestions? Maybe I need some more other models for further logic? -
using CKEditor with Django and an inlineformset_factory with empty_form
When I render the empty form it is not attaching any media to it. i.e. the CKEditor is not displayed. The element looks like it is missing the css/js - it's like it doesn't get set up properly. Note : the other sections are displayed correctly. Where to start? Problem with Django's Empty Form method? Problem with CKEditor? Me :) <div class="container"> <button type ="button" class="btn-info btn-lg" id="add_section">Add Section</button> {{form.media }} {{form|crispy }} {{sections.media}} <div> {{sections.empty_form}} </div> <div id = 'section_management'> {{ sections.management_form }} </div> {% for section in sections %} {{ section|crispy }} {% endfor %} <button class="btn btn-info ml-2" type="submit">Update</button> <a href="{{ view.get_success_url }}" class="btn btn-secondary">Cancel</a> </div> Here's my Forms class SectionForm(forms.ModelForm): content = RichTextFormField() class Meta: model = Section fields = ('content',) empty_permitted=True def __init__(self, *args, **kwargs): print('section form called') super().__init__(*args, **kwargs) class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('title','category','span') def __init__(self, *args, **kwargs): self.is_superuser = kwargs.pop('is_superuser', None) super().__init__(*args, **kwargs) if self.is_superuser == False: self.fields.pop("span") -
I cannot solve django.urls.exceptions.NoReverseMatch: 'XXX' is not a registered namespace with Django3
I cannot solve "django.urls.exceptions.NoReverseMatch: 'XXX' is not a registered namespace" problem with Django3.1.1. I have seen similar issues on many websites, I cannot solve mine. The error message on browser is NoReverseMatch at / 'shiharaisaisokumoushitatesho' is not a registered namespace The error message on terminal is django.urls.exceptions.NoReverseMatch: 'shiharaisaisokumoushitatesho' is not a registered namespace I just want to show index.html on "http://127.0.0.1:8000/" page. ./conf/settings.py """ Django settings for conf project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'index.apps.IndexConfig', 'shiharaisaisokumoushitatesho.apps.ShiharaisaisokumoushitateshoConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'conf.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { … -
Django requires to restart the application server for each update - is there any way to do that with no restart?
I have a Django application deployed on the production server that is Windows in EC2. I am using Apache as a web server application. Everything is good except I have to restart Apache manually in each update. Is there any way to update my changes without restarting the web application server? -
CSS best practices while using Django
I've been working in a project for about 6 months, and I've been adding more urls each time. Right now, I'm coming into the problem that when I'm using extend 'base.html' into another pages, the CSS overlap, and I'm getting a mess. My question is: Which are the best practices when using extend for CSS files? Should every html file I create have it's own css? Or should I have one css that is called in the base.html file and from there all of the other html files take their styling from? This is what my base.html looks like: <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> </script> </head> <style> * { margin: 0; box-sizing: border-box; } html { font-size: 10px; font-family: sans-serif; } a { text-decoration: none; color: #ea0a8e; font-size: 18px; } header { width: 100%; height: auto; background: #121212; background-size: cover; position: relative; overflow: hidden; } .container { max-width: 120rem; width: 90%; margin: 0 auto; } .menu-toggle { position: fixed; top: 2.5rem; right: 2.5rem; color: #eeeeee; font-size: 3rem; cursor: pointer; z-index: 1000; display: none; } nav { padding-top: … -
using pandoc to generate pdf for Heroku
On my Django site I have a button that will create a word document and covert it into pdf file to show it to the user in a new window. Now this is done by reading a word document using docx and then docx2pdf to make the conversation. My problem is that when I launch it on Heroku to make it live, because heroku runs on linux this means that my document wont be created because im trying to generate it with docx. I think it may be possible to use pandoc. However I am have trouble implementing it. below is the word document generation and pdf generation without trying to implement pandoc. how can I implement pandoc with the code below: import docx def making_a_doc_function(request): doc = docx.Document() doc.add_heading("hello") doc.save('thisisdoc.docx') convert("thisisdoc.docx", "output.pdf") pdf = open('output.pdf', 'rb') response = FileResponse(pdf) return response pandoc documentation: https://pypi.org/project/pyandoc/ -
Django form wizard: Method to munipulate request before validating
I have been reading the Form Wizard docs trying to look for a method that can change the request.POST before validating the form. It seems like there are only methods for dealing with data after is_valid() is called -
Django retreive time when the post whas liked
I need to make a report showing analytics(time and user) of post likes and un-likes. model.py class Post(models.Model): user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) likes = models.ManyToManyField(User, related_name="post_like") def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def total_likes(self): return self.likes.count() views.py ... def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get("post_id")) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse("posts:single", args=[str(post.user), str(pk)])) ... How can I get this data? -
How to iterate by query results and send it to template
I want to get random words from the database and create flashcards with them. For this moment I get a record from the database, send it to the template, and check if user's answer is correct. Look at the below code. In the end result, I want to rand 10 words and send it to the template (maybe in for loop) and after answer send information if it was correct (after each word). But I don't know how can I do it with store information in the learn() function about correct and wrong answers. learn.html {% block content %} {% if not result %} <form method="POST"> {% csrf_token %} <div class="row h-100 justify-content-center align-items-center"> <div class="card w-75 bg-light mb-3"> <div class="card-body"> <h5 class="d-flex flex-row-reverse">English - vocabulery</h5> <p class="d-flex flex-row-reverse">more information</p> <div class="form-group"> <label class="font-weight-bold" for="exampleFormControlInput1">{{word}}</label> <input class="form-control" name="wordAnswer" id="wordInput"translation placeholder="word translation"> </div> <div class="form-group"> <label class="font-weight-bold" for="exampleFormControlInput1">{{example}}</label> <input class="form-control" name="exampleAnswer" id="wordInput"translation placeholder="example translation"> </div> <button type="submit" class="btn btn-success" value="POST">Check</button> </div> </div> </div> </form> {% else %} Not correct answer {% endif %} {% endblock %} views.py def learn(request): words = Word.objects.get(id=1) if request.method == "POST": answer = request.POST['wordAnswer'] if answer == words.translation: return render(request, 'learn.html', { 'result': True, }) return … -
Make Django User model accessible as API endpoint
I'm running into the issue of my 'manager not having a get_by_natural_key()'error when I try logging in now to my site. I changed the default manager on my User model so I could get access to all the fields in my API, but now when I attempt to login (I'm using Djoser + Vue on the frontend for Auth), I think the the User manager and Djoser are in conflict. I'm pretty sure that the natural_key is tied to the fields I have on my login page, but I'm not 100% confident, can someone confirm? My question is: can I expose the User model as an endpoint and navigate around the get_by_natural_key error? Models.py class User(AbstractUser): user = models.Manager() GROUP_CHOICES = ( ('general','GENERAL'), ('director', 'DIRECTOR'), ) user_groups = models.CharField(max_length=10, choices=GROUP_CHOICES, default='GENERAL', null=False) Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: exclude = ["id"] model = User Views.py class UserViewSet(viewsets.ModelViewSet): model = User User = get_user_model() queryset = User.user.all() serializer_class = UserSerializer login.vue local: { endpoints: { login: { url: '/auth/token/login/', method: 'post', propertyName: 'auth_token' }, -
Django put values from database record into an array
I'd like to put my db record's values into my array (dates) which is defined outside my method, like this: dates = [] Code: dates_queryset = Profile.objects.all().filter(user=request.user) num = 1 for qr in dates_queryset: dates.append(qr.date) num += 1 -
New to Django - get list of users with the most posts
First post and new to python and django. I am trying to add context to a ListView so that I can display a list of top 5 most commented posts and also a list of top 5 most active users (users with most posts). I have got the first list working however can't work out the second list. Using the values method (i think it's a method) i've managed to query the database and get back a dictionary of user_id and posts count. My problem is that I want to display the username rather than the user_id. For some reason this query results in a dictionary rather than the full object. I've posted the code from views.py below. class PostListView(ListView): queryset = Article.objects.filter(published=True) template_name = 'articles/index.html' #address of non default template context_object_name = 'articles' #variable name passed to template ordering = ['-pub_date'] #get query results for popular posts and most active users side bar def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['most_commented'] = Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count')[:5] context['most_active'] = Article.objects.all().values('author').annotate(active=Count('author')).order_by('-active')[:5] return context Thank you for your help! Nick -
How to get user object using username in django template
I am trying to get user's profile picture in a template using their username. What I have tried: templatetags/users_extras.py: from django import template from django.contrib.auth.models import User register = template.Library() @register.filter(name="get_user", is_safe=True) def get_user(username): return User.objects.filter(username=username).first() My template: {% load users_extras %} <img src="{{ username|get_user.profile.image.url }}"> My Profile view: class Profile(ListView): model = Post template_name = "users/profile.html" context_object_name = 'posts' ordering = ['-datePosted'] def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-datePosted') def get_context_data(self, **kwargs): context = super(Profile, self).get_context_data(**kwargs) context['username'] = self.kwargs['username'] return context The url for profile page is like path('profile/<str:username>/', Profile.as_view(), name='profile') But that gives error Could not parse the remainder: '.profile.image.url' from 'username|get_user.profile.image.url' How can I fix this error or how can I get user object using username in django template? -
Javascript recommendations on creating PSD files from a set of images in browser
I'm working with a web app that is built with Reactjs and Django, and I was wondering what recommendations other devs have for creating a psd file from a set of images? I see that there are few libraries to parse psd files, but I'm not seeing any that will create a psd file from a set of images on the client-side. Didn't know if anyone had stumbled across a library or if I was going crazy. -
Celery -> Attribute Error -> DatabaseScheduler
I am trying to use docker - celery pair in one of my projects. The problem that I have is when I run (venv) C:\Users\yusuf\PycharmProjects\proje>docker-compose up I get error depicted below. Bu when I import DatabaseScheduler from django console, it can import. What may be the problem? How can I solve that? My project is on hold due to that error. Any help will be appreciated. Thanks. -
Django Admin Sidebar Bug
I've been having this weird issue with my Django site for a few weeks now that I can't quite figure out. Whenever I go to the admin page on my local machine (DEBUG=True) it's completely unusable because the sidebar is filling the entire screen as pictured below: This began happening when I upgraded to Django 3.1 if that matters (this project started on 2.1) This does not happen on my live/production site. When I switch DEBUG=False on my local machine it works as expected as well however I can't figure out for the life of me what's causing this. I've tried other browsers as well to no avail. -
Django: issue with template path for tenant
I have an app where depending on its category, a tenant is either directed to the app (and templates) at /dashboard/templates/dashboard or /dashboard2/templates/dashboard2. somehow, for dashboard2, the app is not found by django and it tries to find those templates under dashboard. here is a dashboard2/views.py @method_decorator(login_required, name='dispatch') class SupplierPage2(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) print(query) context = {} #if query and request.method == 'GET': Supplier = supplier2.objects.filter(supplier = query) print(Supplier) labels = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] print(labels) default_items = Item2.objects.filter(fournisseur = query).values_list('number_of_sales', flat=True)[:10] print(default_items) label1s = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] print(label1s) default_item1s = Item2.objects.filter(fournisseur = query).values_list('number_of_orders_placed', flat=True)[:10] print(default_item1s) context.update({'Supplier' : Supplier, 'labels':labels, 'default_items':default_items,'label1s':label1s, 'default_item1s':default_item1s}) return render(request, 'Supplier2.html',context) and the error: TemplateDoesNotExist at /Supplier2.html Supplier2.html Request Method: GET Request URL: https://uname.website.net/Supplier2.html Django Version: 3.0.5 Exception Type: TemplateDoesNotExist Exception Value: Supplier2.html and the traceback: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/ubuntu/website/dashboard/templates/dashboard/dashboard2/templates/dashboard2/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/customers/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/django/contrib/auth/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/dashboard/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/tenantlogin/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/uploadfiles/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/django_tenants/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/rest_framework/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/django_tables2/templates/Supplier2.html … -
GraphQL queries naming when performing CRUD operations on Django models
When performing CRUD operations on Django models will it best practice to name queries like createModelName, updateModelName, deleteModelName? -
Error importing Path from unipath in Django
I am making a program with Django and following some tutorials, unipath is used for the routes and when calling it in the python configuration file it sends me the following error from unipath import Path ValueError: source code string cannot contain null bytes I still do not understand why, if when verifying that it is installed, it does appear in the environment and it seems that the error appears in that line when importing -
Using django objects.filter to filter on db with a datetime field but for date only and based on local time not UTC
I have a model that created a simple table, the checkin date and the checkout date are datetime fields that store items in UTC format from a django form. I want to send a report later on of everyone who checked in or checked out for the whole day (Send out the report like at 11:55pm local time) the problem is that a full day local time is two days in UTC (there is a roll over) not sure how to handle that nad get the data I need using django: What I am trying to do: def select_users(): currentTime = timezone.now() loggedIn = OnSiteLog.objects.filter(autoCheckin=False, checkIn = currentTime, checkOut = currentTime).count() #just a countfor now to test print(str(loggedIn)) The problem is two fold: I believe that timezon.now() is getting a time also of like midnight. So my equals will fail. I really want to filter on day only and ignore time stamp. (Without changing the model though) I want that data still just not for this report. I had something almost similar working in SQLite where I could cast the field to just a DATE not sure how to do that in django. Then the second issue is that 5am … -
Web development, start parsing from web site
everyone. I am new in web development.I have question. Imagine, I have work web site written om Django. I would like to make new app for parsing other web site. When task ends result sends to user via email. Is it possible and ok, if server will parse it? How it will work when several users start parsing in one moment of time? Every task will be handled parallel? Or should I create something like queue and every task will be handled one after another. What's better and correct? Could you suggest good solve or ideas for it? -
I'm getting an File not found error in the command pyRAPL.setup() while using the pyRAPL library in python
I'm trying to install and use the pyRAPL package library in Python in-order to measure the power, energy CO2 emission of a code on my laptop. I'm getting a FileNotFoundError: [Errno 2] No such file or directory: '/sys/devices/system/cpu/present' while using the pyPAPL.setup() command. What may be the problem ? I have installed the pyRAPL package in through my Jupiter Notebook. The package is installed, it can be imported as well but I'm getting an error. Please let me know where I'm going wrong ?. !pip install pyRAPL import pyRAPL pyRAPL.setup() FileNotFoundError Traceback (most recent call last) in ----> 1 pyRAPL.setup() ~\anaconda3\lib\site-packages\pyRAPL\pyRAPL.py in setup(devices, socket_ids) 37 :raise PyRAPLBadSocketIdException: if the given socket in parameter doesn't exist 38 """ ---> 39 pyRAPL._sensor = Sensor(devices=devices, socket_ids=socket_ids) ~\anaconda3\lib\site-packages\pyRAPL\sensor.py in init(self, devices, socket_ids) 57 for device in tmp_device: 58 try: ---> 59 self._device_api[device] = DeviceAPIFactory.create_device_api(device, socket_ids) 60 self._available_devices.append(device) 61 except PyRAPLCantInitDeviceAPI: ~\anaconda3\lib\site-packages\pyRAPL\device_api.py in create_device_api(device, socket_ids) 184 """ 185 if device == Device.PKG: --> 186 return PkgAPI(socket_ids) 187 if device == Device.DRAM: 188 return DramAPI(socket_ids) ~\anaconda3\lib\site-packages\pyRAPL\device_api.py in init(self, socket_ids) 135 136 def init(self, socket_ids: Optional[int] = None): --> 137 DeviceAPI.init(self, socket_ids) 138 139 def _open_rapl_files(self): ~\anaconda3\lib\site-packages\pyRAPL\device_api.py in init(self, socket_ids) 66 :raise PyRAPLBadSocketIdException: the machine where is … -
Django 3.1.1 NOT NULL constraint failed with Date
I'm getting this error on Django 3.1.1 while trying to define a model with an optional date field: class Tickets(models.Model): subject = models.CharField(max_length=255) content = models.TextField(blank=True) category = models.ForeignKey("TicketCategories", on_delete=models.PROTECT, related_name='ticket_category') openDate = models.DateTimeField(auto_now_add=True) closeDate = models.DateTimeField(blank=True, null=True) class Meta: verbose_name_plural = "Tickets" def __str__(self): return f"{self.id} {self.subject}" In this case closeDate should accept null and the user should be able to leave it empty on the admin panel. Unfortunately I am getting this error: NOT NULL constraint failed: api_tickets.closeDate Am I doing something wrong? -
Registration - sequence item 0: expected str instance, NoneType found
Django Version: 3.0.8 - Python Version: 3.7.8 I discovered an error on my Django site recently. When a user wants to create an account it returns this error: sequence item 0: expected str instance, NoneType found Operation: account creation (check if username does not already exist on the DB) creation user Active = False sends an email for confirmation of account creation. Error appears in the first step, the account is created (Active = False), no email is sent and error displayed. Traceback (most recent call last): File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/eodj89/DjangoPro/user/views.py", line 45, in signup user.save() File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/eodj89/DjangoPro/user/models.py", line 479, in create_user_profile UserProfile.objects.create(user=instance) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 433, in create obj.save(force_insert=True, using=self.db) File "/home/eodj89/DjangoPro/user/models.py", line 346, in save … -
How can I upload profile picture in user extended model in Django
I am not getting any error while uploading cover image to the Django's User extended model but I cannot see what is wrong I'm doing because it's not giving any error and not even updating my model. Here I am giving the source code forms.py class UpdateCoverImageForm(forms.ModelForm): class Meta: model = Memer fields = ['cover'] views.py def profile(request, username): try: user = User.objects.get(username=username) user_ = User.objects.filter(username=username) memer = Memer.objects.filter(user=user_[0].id) except User.DoesNotExist: raise Http404("Memer does not exist.") context = { 'user_': user_, 'memer': memer, } if request.method == "POST": bioForm = EditBioForm(data=request.POST, instance=request.user.memer) coverImageForm = UpdateCoverImageForm(data=request.FILES, instance=request.user.memer) if bioForm.is_valid(): memer_ = bioForm.save(commit=False) memer_.save() messages.success(request, "Bio successfully updated your profile") return redirect('/profile/'+user_[0].username) elif coverImageForm.is_valid(): memer_ = coverImageForm.save(commit=False) memer_.save() messages.success(request, "Cover Image has been updated successfully!") # print(coverImageForm) return redirect('/profile/'+user_[0].username) else: messages.error(request, "Something wrong happend") return redirect('/profile/'+user_[0].username) return render(request, 'profile.html', context) profile.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ UpdateCoverImageForm }} <input type="submit" value="save"> </form>