Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I could not return soap response
I need to write a soap service which gets soap request and return soap response. I could handle sending soap request with zeep client library, everythin correct. But i couldnt send any soap response it shows the same error:) import logging from datetime import datetime from spyne import Application, rpc, ServiceBase, AnyDict from spyne.protocol.soap import Soap11 from spyne.server.django import DjangoApplication from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from invoice.api.russian_webservice.complex_models import Consignor, Request1Type, Request31Type, Request91Type, CertificateMaximumType, CertificateMinimumType, Response91Type from exim.models import ExportFSS, ImportFSS class RussianIntegrationApiView(ServiceBase): @rpc(Request91Type, _returns=AnyDict, _out_variable_name="Response91") def getResponse91(ctx, request91type): try: logging.info( f'Initialized objects {str(Request91Type).encode("utf-8")}') error_message = None error_code = None import_fss = ImportFSS.objects.create( number=request91type.certificate.number, given_date=datetime.strptime( request91type.certificate.date, '%d.%m.%Y'), exporter_name=request91type.certificate.consignor.name, exporter_country=request91type.certificate.departure_country, exporter_address=request91type.certificate.consignor.place, importer_name=request91type.certificate.consignee.name, importer_country=request91type.certificate.destination_country, importer_address=request91type.certificate.consignee.place, transport_method=request91type.certificate.transport.declared_type, transport_number=request91type.certificate.transport.number, disinfected_date=datetime.strptime( request91type.certificate.disinfection.date, '%d.%m.%Y'), treatment_method=request91type.certificate.disinfection.method, chemical=request91type.certificate.disinfection.chemical, duration_and_temperature=request91type.certificate.disinfection.temperature_times, concentration=request91type.certificate.disinfection.concentration, extra_info=request91type.certificate.additional_info, ) return { "GUID": CertificateMinimumType.guid_generate(), "SendDateTime": "2022-04-11T19:50:11 ", "Certificate": CertificateMinimumType.generate(), "Status": "Выдан", "StatusCode": "1601", "Inspector": "" } except Exception as e: logging.info(f'Exception occurred: {str(e)}') def on_method_return_string(ctx): ctx.out_string[0] = ctx.out_string[0].replace(b'soap11env', b'soapenv') ctx.out_string[0] = ctx.out_string[0].replace(b'tns', b'mun') ctx.out_string[0] = ctx.out_string[0].replace(b'GUID', b'm:GUID') ctx.out_string[0] = ctx.out_string[0].replace( b'SendDateTime', b'm:SendDateTime') ctx.out_string[0] = ctx.out_string[0].replace(b'Act', b'm:Act') ctx.out_string[0] = ctx.out_string[0].replace(b'Date', b'm:Date') ctx.out_string[0] = ctx.out_string[0].replace(b'Number', b'm:Number') ctx.out_string[0] = ctx.out_string[0].replace(b'Blanc', b'm:Blanc') ctx.out_string[0] = ctx.out_string[0].replace(b'OldDate', b'm:OldDate') ctx.out_string[0] = ctx.out_string[0].replace( b'CountryCode', b'm:CountryCode') ctx.out_string[0] = ctx.out_string[0].replace( b'ExpirationDate', b'm:ExpirationDate') ctx.out_string[0] = … -
Can I use ContentType.objects.get in templatetags?
I kept get this error while attempting to use contenttype in the templatetags. django.contrib.contenttypes.models.ContentType.DoesNotExist: ContentType matching query does not exist. I am trying to get an object by passing the modelname and pk as string to the simple_tag. Below is the codes. I have other custom filters in the same file that work fine. # in templatetags\srrp_tags.py from django import template from django.contrib.contenttypes.models import ContentType register = template.Library() @register.simple_tag def get_object(modelname, id): ctype = ContentType.objects.get(model=modelname) # this line trigger the error model = ctype.model_class() return model.objects.get(pk=id) In my html, model and primary are both string value # in templates\srrp\index.html {% load srrp_tags %} ... {% get_object modelname|title primary %} I have use the exact same code for the Contenttype in the view.py and it retrieve the required model with no issue. # in view.py class srrpListView(LoginRequiredMixin, PermissionRequiredMixin, ListView): ... def get_queryset(self): modelname = self.kwargs.get('modelname') ctype = ContentType.objects.get(model=modelname) # same code self.model = ctype.model_class() return self.model.objects.select_related().values() Any advice is much appreciated. Thank you -
How to prefetch or use select related in reverse generic relation in django?
Assume i have two models: class A: content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True, blank=True) object_id = models.PositiveIntegerField(null=True, blank=True) attached_object = fields.GenericForeignKey('content_type', 'object_id') class B: some_field = GenericRelation(class A) Now I have a scenario where i need to list all of class B instances, and in that result list, i need to include some of class A which is related to class B. While trying to do that, obviously it is leading to as many query hits as there are instances of class B. I have searched all online forums to try and reduce queries in this case. instances_of_b = B.objects.all() for instance in instances_of_b: some_list.append(instance.related_instance_of_class_A.some_field_of_class_A) To get related_instance_of_class_A, i am using ContentType.objects.get_for_model(content_object) Is there any way to use select_related/prefetch related in this case? -
Add view in admin panel with same design as others
I'm trying to create a documentation part in my admin panel, and for that I created a custom admin site. I've overriden the get_app_list and get_urls methods in order to display a new line in the navigation bar and the dashboard, and I created a view to which this line redirects : class MyAdminSite(admin.AdminSite): def get_app_list(self, request): app_list = super().get_app_list(request) app_list += [ { "name": "Documentation", "app_label": "my_test_app", "models": [ { "name": "Scripts modification", "object_name": "Scripts modification", "admin_url": "/admin/documentation/modif/", "view_only": True, } ], } ] return app_list def get_urls(self): urls = super().get_urls() my_urls = [ path('documentation/modif/', self.admin_view(self.modif)), ] return my_urls + urls def modif(self, request): context = { 'title':"Documentation", } return render(request, "documentation/scripts_modification.html", context) Everything works correctly and when clicking on the new line, I'm redirected to the new view I created. However, I want my view to have the same design as the rest of the admin panel, which I didn't how to do. I extended admin/base_site.html but I only get the top of the page, and not the view site log out panel nor the navigation sidebar : I have no idea what I should change/configure in order to have the same display as the other admin pages. … -
Django/apache NLTK Permission denied: '/var/www/nltk_data'
I'm using NLTK with my Django/Apache application, however when loading a page it returns Permission denied: '/var/www/nltk_data' error. I made my user (not root) the owner of /var/www and gave permissions with sudo chmod -R 770 /var/www/. What else can I do to remove this error? -
How to write unit test for user-detail with router.register base name
this error appears when I write a test for user-detail, I thought the error from response = self.client.get(reverse('user-detail',kwargs={'pk':1})), I used router.register to config ulrs base name, and that makes me confused when writing the test. So in this case, where the point in my code was wrong? Thank you so much! def test_list_user_detail(self): """ List user detail """ self.client.post(self.url, self.data, format='json') resp = self.client.post( '/auth/token/login/', data={'email': 'Foo@gmail.com', 'password': 'Boo'}, format='json') token = resp.data['auth_token'] self.client.credentials(HTTP_AUTHORIZATION='token '+token) response = self.client.get(reverse('user-detail',kwargs={'pk':1})) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) ====================================================================== FAIL: test_list_user_detail (sellHouse.tests.UserTest) List user detail ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\code\restfullapi\example\sellHouse\tests.py", line 68, in test_list_user_detail self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 ---------------------------------------------------------------------- try print response.data : {'detail': ErrorDetail(string='Not found.', code='not_found')} -
FormatException: Invalid character (at character 12) in flutter after changing the URL from http to https
I have a project; frontend using Flutter and the Backend using the Django framework. The project was working for a long time very well, but now I had to change the URL from HTTP to HTTPS and I got the following error: Now I have a couple of questions? first, why am I getting this error? second, should I change all URLs in my code for example http.Url('url') to https.Url('url'), and what should I do in the following example: final response = await http.get( url, // url is hammbwdsc02/visoon-backend headers: {"Authorization": "Bearer $authToken"}, ); Should I change again HTTP to HTTPS? -
Periodic Tasks Django that update state
I created a Django server. I have a class instance that loads its data from the database, once it is loaded (i.e. once the Django dev server starts). What I want to achieve is that there is a recurring task, such that the instance reloads from the database, once every day. I.e. <instance>.load_db() should be called, once a day. I tried to configure a cron job that calls the function once a day using crontab package. However, this only spawns a new instance of the server, does a reload there, but does not update the state of the running instance of the server. I would need the server to simply execute the tasks itself, not spawn a new instance of the server. Any ideas on how you can achieve this? -
Django Graphene filter date field with startswith using year and month
I am using Django and Graphene and have created a GraphQL query to return purchase orders from my database. All orders have a date field associated with it to represent when the order was created. The values in this column are formatted like 2022-05-01 08:38:17+01 - I know this is a datetime field and will rename the column at some point. I am trying to create a filter for the user to only return data from a particular month in a given year. The filter value is represented like 2022-05 for year and month. I would like the GraphQL to filter the data returned for that year and month. I am trying to use the startswith value to do this but getting an error that it is not a date. I understand that it is not a valid date, but I can't figure out how to filter the date field using only the year and month. Schema class Purchases(DjangoObjectType): id = graphene.ID(source='pk', required=True) class Meta: model = purchase_orders interfaces = (relay.Node,) filter_fields = {'date': ['startswith']} connection_class = ArtsyConnection GraphQL Query { Purchases(first: 15, after: "", date_Startswith: "2022-05") { ... Response { "errors": [ { "message": "Argument \"date_Startswith\" has invalid value … -
Django update user POST HTTP/1.1 302 0
Help me, please. What am I doing wrong? I'm trying to update the user, I send a request, but I get 302 in response. My request: https://skr.sh/sEYdKhpyf1w [21/Jun/2022 10:54:24] "GET /clients/client_1/update HTTP/1.1" 200 8884 [21/Jun/2022 10:54:29] "POST /clients/client_1/update HTTP/1.1" 302 0 [21/Jun/2022 10:54:29] "GET /clients/client_1 HTTP/1.1" 200 11527 views.py class UpdateClient(UpdateView): model = Profile form_class = ClientForm template_name = 'admins/admin_update_client.html' context_object_name = 'client' def get_context_data(self, **kwargs): cl = Profile.objects.get(pk=self.kwargs['pk']) c = json.loads(cl.CategoryVU) ctx = super(UpdateClient, self).get_context_data(**kwargs) ctx['cats'] = c return ctx def post(self, request, pk): lis = request.POST.getlist('CategoryVU') res = dict((i, lis.count(i)) for i in lis) data = json.dumps(res) form = ClientForm(request.POST) cl = Profile() if (form.is_valid()): cl= Profile.update_client(cl, request, pk, data) return redirect('admin_client', pk) forms.py class ClientForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'phone', 'email') -
Access javascript variables in python function file(views.py) using django
I want to access javascript array variable into python function file(views.py). I stored data in array using javascript and want to get that data into python function for further process. show.html function getvalues() { var val = []; $(':checkbox:checked').each(function (i) { val[i] = $(this).val(); }); } views.py def show(request): selected = val[i] return render(request, "show.html", {}) I want to use val[i] into views.py show() function. If I need to use AJAX then how I can use AJAX? or there is some other way to access data -
Django template if expression not correct?
My Django template returns error as: (error at line 26 )Unused 'item' at end of if expression. I checked the reported lines as below and didn't where's the error in my code. Could anyone help me? In which line 26 is {%if cur_prj and item == cur_prj %} The whole snippet is as: {%for item in PROJS %} {%if cur_prj and item == cur_prj %} <option value={{item}} selected>{{item}}</option> {%elif not cur_prj item == my_case.project_name%} <option value={{item}} selected>{{item}}</option> {%else%} <option value={{item}}>{{item}}</option> {%endif%} {%endfor%} -
Page not found (404) in Django Output
my url.py urlpatterns = [ path("", views.index, name="blogHome"), path("blogpost/<int:id>/", views.blogpost, name="blogHome") ] my views.py django.shortcuts import render from .models import Blogpost # Create your views here. def index(request): return render(request, 'blog/index.html') def blogpost(request, id): post.Blogpost.objects.filter(post_id = id)[0] print(post) return render(request, 'blog/blogpost.html') my models.py from django.db import models class Blogpost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) head0 = models.CharField(max_length=500, default="") chead0 = models.CharField(max_length=10000, default="") head1 = models.CharField(max_length=500, default="") chead1 = models.CharField(max_length=10000, default="") head2 = models.CharField(max_length=500, default="") chead2 = models.CharField(max_length=10000, default="") pub_date = models.DateField() thumbnail = models.ImageField(upload_to='blog/images', default="") def __str__(self): return self.title Error Error Image which i see in output Error in cmd Not Found: /blog/blogpost [21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" 404 2678 Please help me to solve this problem as soon as possible -
Django: Get average rating per user
Given the following, how can I make a query which returns a list of the average rating per user in friendlist? models.py class Beer(models.Model): id = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=150) ... class Checkin(models.Model): id = models.IntegerField(primary_key=True) rating = models.FloatField(blank=True, null=True) ... class FriendList(models.Model): user = models.OneToOneField(User, on_delete=CASCADE, primary_key=True) friend = models.ManyToManyField(User, related_name="friends") database (postgresql) user beer rating 1 1 4.2 1 1 3.5 1 1 4.0 2 1 4.1 2 1 3.7 My current query to get all friends checkins: Checkin.objects.filter(beer=1, user__in=friends.friend.all()) Which gives me something like: [{user: 1, rating: 4.2}, {user: 1, rating: 3.5},...,{user: 2, rating: 4.1}...] What I want is: [{user: 1, avg_rating: 4.1}, {user: 2, avg_rating: 3.8}] -
Python group a list of years, months to remove duplication of years
I have a table that contains orders, in which contains the date column. I am getting back the aggregate of the years, and months from that column so that I can use that data in a filter on the front end. I have managed to get this data back, however it is not formatted in the way I would like. Python years = purchase_orders.objects.filter(user_id=info.context.user.id).annotate(year=ExtractYear('date'), month=ExtractMonth('date'),).order_by().values_list('year', 'month').order_by('year', 'month').distinct() Data Returned <QuerySet [(2020, 3), (2021, 4), (2022, 1), (2022, 2), (2022, 3), (2022, 4), (2022, 5)]> Ideal Format <QuerySet [(2020, (3)), (2021, (4)), (2022, (1, 2, 3, 4, 5))]> -
NoReverseMatch at / Reverse for 'register_request' not found. 'register_request' is not a valid view function or pattern name
this is a shopping website my login and registration form is not working it is showing that no reverse path found error. this is my navbar template <div class="container py-5"> <p class="text-center">If you already have an account, <a href="{% url 'sweet:register_request' %}">login</a> instead.</p> </div> <div class="container py-5"> <p class="text-center">Don't have an account? <a href="/register">Create an account</a>. </p> </div> login.html this is my login template {% extends "base.html" %} {% load static %} {% block content %} {% csrf_token %} {{ login_form }} Login {% endblock %} home.html this is my registration template {% extends "base.html" %} {% load static %} {% block content %} Register {% csrf_token %} {{register_form}} {% endblock %} views.py register_request is function defined to register the form and login_request is to login into my website def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful.") return redirect('login_request') messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render(request,"home.html",{"register_form": form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}.") return redirect("base.html") … -
chrome makes null endpoint request in django service
My env is django backend , vuejs from vite frontned. also using django-vite package in backend and nginx for proxy server. But when I depolyed all code to server, now I am getting null endpoint request. I can only see it in chrome browser. It doesn't appear in IE edge. Why does it happend? Do you guys have any idea? I left screenshot and service url http://3.35.61.148/ Can it be related to not using SSL(https) ? -
django allauth multiple custom forms for social sign up
I want to build 2 different custom forms, one for google sign up accounts, and one for facebook sign up accounts. Yet allauth only allow one custom form for all social sign up via the settings.py: SOCIALACCOUNT_FORMS = {'signup': 'accounts.forms.SignupFormSocial'} Is there a way to this ? Like pass in two different form to the overriden forms so I can choose which one to show based on the current provider. -
How to add extra per-Feed fields to a Django Feed (Specifically, a Django-iCal feed)
I am generating a per-user calendar feed. As part of the URL, I'm allowing event filters. I am struggling to figure out how to save that filter (or any arbitrary variable) to the specific Feed I am generating from the specific call. The method I thought would work is (coming from a C++ world) making a static variable that is shared amongst all Feed callers, which would lead to inconsistency when Feeds are being generated simultaneously. What is the proper way to do this? Reading through the Feed libraries, I see methods like feed_extra_kwargs() and item_extra_kwargs(), but I can't find examples or documentation on them that show how to use them. My URL: re_path(r'^ics/(?P<user_id>\d+)/(?P<params>[\w=;]+)/ical.ics$', EventFeed(), name='ics'), My Feed attempt: class EventFeed(ICalFeed): """ A simple event calender """ product_id = '-//icevite.com//Schedule//EN' timezone = 'UTC' file_name = "icevite.ics" filter = [] alarms = [] def get_object(self, request, user_id, params, *args, **kwargs): self.filter = [] try: split = params.split(";") for s in split: item = s.split("=") match item[0]: case "f": self.filter = list(item[1]) case "n": mins = int(item[1]) if mins: self.alarms.append(mins) return Player.objects.get(id=user_id) except: return None def items(self, player): responses = Response.objects.filter(mate__player=player) if self.filter: filtered = responses.exclude(response__in=self.filter) else: filtered = responses return filtered.select_related('game', … -
having trouble with saving the value of "gender" in update page
and I amd making a CRUD project,I have used radio button's for genders:male /female. I am able to successfully add the genders while adding new employee, however while updating the details, the gender which I selected isnt saved in the 'update' page. below is the code for gender in the 'Insert' page <tr> <td>gender</td> <td> <input type="radio" value="male" name="gender">male | <input type="radio" value="female" name="gender">female </td> </tr> below is the code for my 'Edit' page Male:<input type="radio" value="{{EmpModel.gender}}"> Female: <input type="radio" value="{{EmpModel.gender}}"> Since I am not sure what value I am supposed to put here, I added EmpModel.gender for both please help -
Pagination for Django search results (python)
I want to add pagination to my search results in django. This is my search function form views.py for the relevant (Jobs) module: def search(request): queryset_list = Job.objects.order_by('-publishing_date') if 'keywords'in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) if 'state' in request.GET: state = request.GET['state'] if state: queryset_list = queryset_list.filter(location__iexact=state) if 'job_type' in request.GET: job_type = request.GET['job_type'] if job_type: queryset_list = queryset_list.filter(job_type__iexact=job_type_choices) if 'industry' in request.GET: industry = request.GET['industry'] if industry: queryset_list = queryset_list.filter(industry__icontains=industry_choices) if 'salary' in request.GET: salary = request.GET['salary'] if salary: queryset_list = queryset_list.filter(salary__lte=salary) context = { 'location_choices':location_choices, 'salary_choices':salary_choices, 'job_type_choices':job_type_choices, 'industry_choices':industry_choices, 'jobs':queryset_list, 'values':request.GET, } return render(request, 'jobs/search.html', context) This is pagination function from the same file: def index(request): jobs = Job.objects.order_by('-publishing_date').filter(is_published=True) paginator = Paginator(jobs, 6) page = request.GET.get('page') paged_jobs = paginator.get_page(page) context = { 'jobs': paged_jobs } return render(request, 'jobs/jobs.html', context) Both of them work (search returns results and pagination works on listing page) however I want to have pagination too for my search results. I am very new to python and django, and assume there is more elegant way of writing my search function, so please do not hesitate to let me know your thoughts. -
How to configure my django settings.py for production using postgresql
I'm already deploying my django app. However, I don't know what I should place in my host instead of using localhost. note: this works perfectly if I run it locally. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'trilz', 'USER': 'postgres', 'PASSWORD': 'franz123', 'HOST': 'localhost', 'PORT': '5432', } } -
Unable to run index migration in OpenSearch
I have a docker compose running where a django backend, opensearch & opensearch dashboard are running. I have connected the backend to talk to opensearch and I'm able to query it successfully. I'm trying to create indexes using this command inside the docker container. ./manage.py opensearch --rebuild Reference: https://django-opensearch-dsl.readthedocs.io/en/latest/getting_started/#create-and-populate-opensearchs-indices I get the following error when I run the above command root@ed186e462ca3:/app# ./manage.py opensearch --rebuild /usr/local/lib/python3.6/site-packages/OpenSSL/crypto.py:8: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography and will be removed in a future release. from cryptography import utils, x509 Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 37, in load_command_class return module.Command() File "/usr/local/lib/python3.6/site-packages/django_opensearch_dsl/management/commands/opensearch.py", line 32, in __init__ if settings.TESTING: # pragma: no cover File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 80, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'TESTING' Sentry is attempting to send 1 pending error messages Waiting up to 2 seconds Press Ctrl-C to quit I'm not sure where I'm going wrong. Any help would be … -
How to display ID for each form in Django Formset
Need to make the UI more ordered, can i have indexing for the forms in formset or access the form ID? <div class="card"> <div class="card-body"> <div id="form-container"> {% csrf_token %} {{ formset1.management_form }} {% for form in formset1 %} <div class="test-form"> {% crispy form %} </div> {% endfor %} <button id="add-form" type="button" class="btn btn-primary">Add Another Request </button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> -
Upload PDF File via Django Admin, Users Download from Link on Template
I'm trying to allow users to download a PDF file that I've previously uploaded to the MEDIA_ROOT folder via the admin console. I've emulated the answer in this post, however it's incomplete and I can't figure out how to fix this. Hoping someone can spot my issue in the code below. settings.py # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = str(BASE_DIR) + "/media/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = str(BASE_DIR) + "/static/" # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' models.py from django.db import models # Create your models here. class ResumeModel(models.Model): pdf = models.FileField(upload_to="resume_app/media/resume/") # So this file gets uploaded to root > media > resume_app > media > resume admin.py from django.contrib import admin from .models import ResumeModel # Register your models here. admin.site.register(ResumeModel) views.py from django.shortcuts import render from .models import ResumeModel # Create your views here. …