Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Converting jsonb_each postgresql query to Django ORM
I have a query that joins on a jsonb type column in postgres that I want to convert to Django SELECT anon_1.key AS tag, count(anon_1.value ->> 'polarity') AS count_1, anon_1.value ->> 'polarity' AS anon_2 FROM feedback f JOIN tagging t ON t.feedback_id = f.id JOIN jsonb_each(t.json_content -> 'entityMap') AS anon_3 ON true JOIN jsonb_each(((anon_3.value -> 'data') - 'selectionState') - 'segment') AS anon_1 ON true where f.id = 2 GROUP BY anon_1.value ->> 'polarity', anon_1.key; Following are my models: class Tagging(BaseModel): class Meta: db_table = "tagging" json_content = models.JSONField(default=dict) feedback = models.ForeignKey("Feedback", models.CASCADE) class Feedback(BaseModel): class Meta: db_table = "feedback" feedback_text = models.TextField(blank=True, null=True) The json_content field stores data in the following format: { "entityMap": { "0": { "data": { "people": { "labelId": 5, "polarity": "positive" }, "segment": "a small segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 75, "anchorOffset": 3 } }, "type": "TAG", "mutability": "IMMUTABLE" }, "1": { "data": { "product": { "labelId": 6, "polarity": "positive" }, "segment": "another segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 138, "anchorOffset": 79 } }, "type": "TAG", "mutability": "IMMUTABLE" } } } What I want is to get count of the polarities per tag. … -
Pytest-django admin interface
I have been looking for sources where I would get some examples of testing Django admin interface using pytest. From this question, I got one of the examples that I am following now. However, it is not in pytest, it is also more advanced testing than I am looking for. PS: I am also new guy in testing and kind struggle some parts from there. Anyways, Here is my class in admin.py: class Sample(admin.ModelAdmin): readonly_fields = ("id",) list_display = ("id", "name", "report") list_filter = ("name", "report") search_fields = ("name", "report__name") save_as = settings.SAVE_AS_NEW I want to do something like this: assert readonly_fields == "id" for every field I have following setup in test_admin.py: class MockRequest: pass request = MockRequest @pytest.mark.django_db() class TestSampleAdmin: @pytest.fixture(autouse=True) def _setup_model(self) -> None: self.site = AdminSite() self.model = ModelAdmin(Sample, self.site) def test_recommendation_list_display(self) -> None: view = self.model print(view.readonly_fields) But my printout is empty, while I expect it to be "id" What am I doing wrong and how can I make it work? -
Django : Paginator page exceed max page
I'm currently working on CBV Paginator in Django redirecting last page when given page exceed maximum pages. So, let's say there's Post models that has 200 instances and ListView with paginated_by=10. Then maximum page is 20. So, when I enter URL with "?page=21", it return 404 Error Page. I want to redirect to maximum page. How can I do? -
django - iterate through model in create view & return inline formset
I'm trying to create a formset that will allow the user to set scores for each Priority when creating a new project with the CreateView. The Priority model already has data associated (3 values) foreach Priority that has been created I'm trying to return a char-field in the Project CreateView where the user can enter the score for the Priority. Currently I have the three char-fields showing up in the Project CreateView but I'm getting this error when trying save NOT NULL constraint failed: home_projectpriority.priority_id. I have done some testing & it looks like the ProjectPriority is never having the Project or Priority values set only the score value. I have been struggling for days trying to get this to work. I appreciate all the help. Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm success_url = 'home/project/project_details.html' def get_context_data(self, **kwargs): ChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('score',), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = ChildFormset(self.request.POST, instance=self.object) else: data['priorities'] = ChildFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() priorities = context["priorities"] self.object = form.save() if priorities.is_valid(): priorities.instance = self.object priorities.save() return super().form_valid(form) Models.py class Priority(models.Model): title = models.CharField(verbose_name="Title", max_length=250) def __str__(self): return self.title class Project(models.Model): name … -
Django ListView how loop in one field in the template?
I have django ListView I know I can loop in it like this {% for i in object_list %} {% i.id %} {% endfor %} I want to loop in one field only {% for i in object_list.id %} {% i %} {% endfor %} -
Dockerize Django app failed with error "/bin/sh: [python3,: not found"
my docker-compose file as below: Django_2.2: build: context: . dockerfile: Dockerfile_Build_Django # Give an image name/tag image: django_2.2:iot container_name: Django_2.2 depends_on: - Django_Mongo_4.2.12 networks: sw_Django: ipv4_address: 192.168.110.12 ports: - 8000:80 restart: always volumes: - type: volume source: vol_django_codes target: /usr/src/app My docker file "Dockerfile_Build_Django" as below: FROM python:3.9.3-alpine3.13 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . . RUN pip install -r requirements.txt # CMD ["python","./IoTSite/manage.py","runserver","0.0.0.0:80"] CMD python ./IoTSite/manage.py runserver 0.0.0.0:80 but when I run "docker-compose up", it failed with below errors, [root@Django]# docker logs Django_2.2 /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found /bin/sh: [python3,: not found I have been searching for solution for a long time and tried many fixes found via google, no luck so far. any help is appreciated. I feel like getting involved in IT is a waste of life because coding according to guide/user manual for 5 mins then troubleshooting for hours or even days... -
Django template how to compare current item with the previous item in for loop?
My context is an integer array, I'm trying to make a table where every number is compared to the previous one and I will display an arrow indicating if this number has increased or decreased. This is what I'm trying to make {% for number in object_list %} {% if forloop.first %} {% set prev_number = number %} {%endif%}{%endfor%} {% for number in object_list %} {% if number > prev_number %} ... {% else %} ... {% endif %} {% set prev_number = number %} {% endfor %} I know there is not {%set%} tag in django is there any tag equivalent to it? something like {%with%} but doesn't require {% endwith %} or a template tag that does it or I should do it in the views. -
Send email from Django in docker container
I have deployed an existing application inside a docker container. The email service is now working any more. I have exposed the email server port (587), but still not working. This is my django email configuration: # EMAIL handler EMAIL_HOST = "smtp.office365.com" EMAIL_PORT = 587 EMAIL_HOST_USER = "email@email.com" EMAIL_HOST_PASSWORD = "pssword" these are my container exposed ports: docker run -d -p 8001:8020 -p 587:587 --name ... 587/tcp -> 0.0.0.0:587 8020/tcp -> 0.0.0.0:8001 -
whenever i write django-admin,i get this error:ModuleNotFoundError: No module named 'django.utils'
$ django-admin Traceback (most recent call last): File "c:\python\python38\lib\runpy.py", line 194, in _run_module_as_main return run_code(code, main_globals, None, File "c:\python\python38\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Python\Python38\Scripts\django-admin.exe_main.py", line 4, in File "C:\Users\Asus\AppData\Roaming\Python\Python38\site-packages\django_init.py", line 1, in from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' -
Django Encrypt the URL (PK and ID)
I am trying to find best solution for encrypting my URL, I have found some old versions, for python 2.2. I need to set my URLs, not to display like this: petkovic.com/AddPost/1/ and petkovic.com/PostDetail/40. But something like this:petkovic.com/AddPost/DMQRzZWMDdGQtbndzBHNsawN0aXRsZQR0ZXN0AzcwMQR3b2UDMjQwMjEwNQ That you can not guess what PK is and access that page: URLs: urlpatterns = [ path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'), ] view.py: class PostDetail(DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, *args,**kwargs): post = Post.objects.all() context = super(PostDetail,self).get_context_data(*args,**kwargs) stuff = get_object_or_404(Post,id=self.kwargs['pk']) total_likes=stuff.total_likes() context['total_likes'] = total_likes return context -
CSS Referencing many stylesheet and scalability
I'm having some problem with my multiples stylesheet references. Basically the classes defined on style.css are not acting on my index.html. Might be that as there are multiple stylesheet someone of these are overwriting the file style.css? Last time I was having a similar problem and I asked a question here but after a couple of hours the file was working fine... Now I have restarted and all but still style.css still do nothing... myapp/static/style.css h1 { color: blue; text-align: center; } .box { width:30%; height:30%; background-color: blue; } On my layout.html have been defined multiples stylesheet references on the following way <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user- scalable=no"> <!-- Estilos de la master --> <link rel="stylesheet" href="{% static 'myapp/style.css' %}" type="text/css" > <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" type="text/css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'js/sss/sss.css' %}" type="text/css" media="all"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <!-- Estilos de los recursos adicionales --> <link rel="stylesheet" href="{% static 'fontawesome/web-fonts-with-css/css/fontawesome- all.min.css' %}"> <!-- Librerías adicionales --> <script src="{% static 'js/jquery.min.js'%}"></script> <script src="{% static 'js/sss/sss.min.js' %}"></script> <!-- Librerías de plugins --> <!-- Archivo personalizado de Javascript --> <script src=" {% static 'js/codejs.js' %}"></script> <title>{% block title %}{% endblock %}</title> </head> and … -
Using DRF Serializer/Model to find different combinations of relationships
Using Django Rest Framework, I have a feature that shows the users that the logged-in-user is following. It works as expected. I now want to be able to show the users who FOLLOW the logged-in-user. Would this be possible using the same model and serializer somehow, is this where I would use a reverse look up? I want to avoid writing a new model if possible. Here is my model class UserConnections(models.Model): user = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE) Here is the serializer class UserConnectionListSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = ['user','following_user'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' depth = 2 And here is the view: class FollowingViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): if self.request.method == 'GET': return serializers.UserConnectionSerializer return self.serializer_class def get_followers(request): if request.method == "GET": name = self.request.GET.get('username', None) return UserConnections.objects.filter(user__username=name) -
Django: 'Q' object is not iterable
I have following APIView: class SubmitFormAPIView(APIView): def put(self, request, pk): # some other codes form = Form.objects.get(id=pk) tu_filter, target_user = self._validate_target_user(request, form) user_status, created = UserFormStatus.objects.get_or_create( tu_filter, form_id=pk, user_id=request.user.pk ) # Some other codes. def _validate_target_user(request, form): if some_conditions: return Q(), None else: try: target_user_id = int(request.GET.get('target_user_id)) except ValueError: raise ValidationError() target_user = get_user_model().objects.get(id=target_user_id) return Q(target_user_id=target_user_id), target_user but when django wants to execude get_or_create method, raises following error: 'Q' object is not iterable Note: If _validate_target_user() returns Q(), None, no errors raised and view works fine. I know, question information is not completed, just I want to know, what may cause this error? -
Django not loading global static files in only one app
I have a Django project with multiple apps. Every app has a 'static/' dir to store some CSS and JS in their respectives folders. In addition, the project has a global '/static' dir to store the global assets that aren't attached to an app in particular. The structure of the project is the following one: monitor (project root) clients static assets css js scheduler static assets css js monitor static (global static dir) assets css js I'm not sure about this structure, but this is how it generates when use startproject and startapp commands from Django. If I put the global assets in the path /monitor/assets instead of /monitor/monitor/assets, then none of the apps can load them. The problem comes when loading assets from the global static dir. The app scheduler loads them perfectly. However, the app clients can't find them. But I'm loading them exactly the same way!!! Seriously, I'm going mad with this. I have put staticfiles in the installed apps, and have set up STATIC_URL and STATICFILES_DIR parameters: INSTALLED_APPS = [ 'scheduler.apps.SchedulerConfig', 'clients.apps.ClientsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "monitor/static", ] This is the way I'm loading the … -
I changed the session cookie name in my django project and I am unable to login
I want to change the SESSION_COOKIE_DOMAIN because it's set incorrectly on a production server. Due to this, I also need to change the SESSION_COOKIE_NAME to something else. Otherwise there'll be two cookies with the same name and different domains on the users side, because it's already in production. With these two cookies, the user will have trouble logging in. This would normally be fine, but now the problem. Just after I changed the SESSION_COOKIE_NAME (so I haven't even changed the SESSION_COOKIE_DOMAIN yet), I am unable to login into the admin console. I can see the cookie with the new name being set. The application itself has no problems and users can login without problems, which is strange because it's the same authentication. What I've tried: Deleting all session on the server site Private mode Other Browser Flushing all possible caches on the server but might have mist one. Checking for hardcoded session names, but there are not. What else could I possibly check? If I set the SESSION_COOKIE_NAME back to what it was, I can log in again. This issue only happens on the production server; not locally, and on not on the test server, which makes it hard to … -
How to get payment response from paypal as boolean in django?
I am using Paypal api for my Django website.I am able to make payment but don't know how to get payment response from paypal server as either True or False. -
TESTING a Django View
I am very new to testing, this is my first set of tests. I have followed few tutorials on how to go about testing and while the testing that I have made for models and URLs work perfectly, my views testing are not working properly. I have looked at some answers for similar questions on Stack but can't find a reason why this would not work. This is my View function: @csrf_exempt @login_required def profile(request, username): user = request.user profilepic = ProfilePic.objects.filter(user=user).first() username = User.objects.filter(username=username).first() usr = username following = FollowedCrypto.objects.filter(user=user.id) cryptos = [] for i in following: cryptos.append(i.cryptocurrency) return render(request, "PlanetCrypton/profile.html", { "following":following, "user": user, "usr" : username, "profilepic":profilepic, "crypto": cryptos, }) and this is my test for it: def test_profile(self): c = Client() user_b = User.objects.create(username="Fred", password="fred") user_b.save() profilepic = ProfilePic() profilepic.user = user_b profilepic.profile_pic = SimpleUploadedFile(name='test_image.jpg', content=open("/Users/michelangelo/Desktop/FP1/static/images/Jaguar.jpg", 'rb').read(), content_type='image/jpeg') profilepic.save() followedcryptos = FollowedCrypto() followedcryptos.user = user_b followedcryptos.cryptocurrency = "bitcoin" followedcryptos.save() l1 = [] l2 = [] l1.append(followedcryptos) l2.append(followedcryptos.cryptocurrency) data = { "following": l1, "user": user_b, "usr" : user_b.username, "profilepic": profilepic, "crypto": l2 } response = c.get(f"/profile/{user_b.username}", data, follow=True) self.assertEquals(response.status_code, 200) instead of using l1 and l2 to pass the data, I have also directly tried by writing … -
How to add padding downwards in a bootstrap card?
I want to add padding on all four sides of a bootstrap card, and so used the attribute style='padding:25px', but padding is only being applied on the other three sides except downwards, i.e there are no padding between rows. How do I fix this? I am using django and htm <div class="row" style='padding:25px'> {% for player in players %} <div class="col-auto col-md-3"> <div class="column"> <div class="card" style="width: 18rem;"> <img class="card-img-top" width="20" height="300" src="{{ player.image_url }}"> <div class="card-body"> <h5 class="card-title">{{ player.name }}</h5> <p class="card-text">{{ player.position }}</p> <a href="#" class="btn btn-primary">Know More!</a> </div> </div> </div> </div> {% endfor %} </div> -
How to display annotions values in Django templates?
I want to display a list in my dashboard with a context processor view. But it did not works. It displays nothing in the table. But when I use it on another page with a normal view it works. How can I solve it? Is there a problem with context processor? views.py def risk_context_processor(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) countries = Customer.objects.values_list('country__country_name', flat=True).distinct() country_links = Country.objects.filter() iso_country_links = Customer.objects.values_list('country__country_name', flat=True).distinct() codes = pycountry.countries.get(name='American Samoa').alpha_2 counting_list = Customer.objects.values("country", "country__country_name").annotate( **{ f"{stored.lower().replace(' ', '_')}_count": Count( "risk_rating", filter=Q(risk_rating=stored) ) for (stored, displayed) in Customer.RISK_RATING }, total_credit_limit=Sum("credit_limit"), total_customers=Count("id"), ) test = 0 context = { 'customer_list': customer_list, 'countries': countries, 'country_links': country_links, 'iso_country_links': iso_country_links, 'codes': codes, 'test': test, 'counting_list': counting_list } return context **template.html** <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Country</th> <th>Total</th> <th>Low Risk</th> </tr> </thead> <tbody> {% for country in counting_list %} <tr> <td> {{ country }} </td> <td> {{ country.total_credit_limit }} </td> </tr> <tr> <td>{{ country.low_risk_count }} customers</td> </tr> {% endfor %} </tbody> </table> -
Django API, manage linked tabes using multiple GETs
In my django app i expose two tables using DjangoRestAPI for manage data one related to other. There is a result data with this structure: "results": [ { "id": 175194, "device": "f906e9db70b0cc822cb44ccd1b2b89a7", "res_key": "b865c3125cb4ef173e55377026d94b2b", "read_date": "2021-03-31T07:06:04.143569Z", "unit": 2 }, { "id": 21278, "device": "f906e9db70b0cc822cb44ccd1b2b89a7", "res_key": "c8a961f3ef9f8fa0ebdac3c910070055", "read_date": "2021-03-26T15:54:04.171926Z", "unit": 1 }, { "id": 25173, "device": "f906e9db70b0cc822cb44ccd1b2b89a7", "res_key": "75126c6b2b4e78fc553ec75c7eb927ea", "read_date": "2021-03-26T16:48:03.259185Z", "unit": 1 }, ... and a result_details API endpoint related to results: "results_details": [ { "id": 1, "id_res": 236, "var_id": 1, "var_val": "[41]", "var_hash": "6f241d5445cf3031f6420de63c0a409bad527ea3" }, { "id": 2, "id_res": 326, "var_id": 1, "var_val": "[45]", "var_hash": "e5f03cfbed7ee88445b44ddf8e64365da310f8ec" }, ... there is an id_res field that link to main results data. So, in this configuration, every time a user have to get results related to a specific device have to execute a GET to the first table filtering for device and then, inside a for loop, manage n GETs on second table passing the id for link to id_res. If i find 100 rows from Results API call i have to execute 100 different calls to the Results_data. Someone have an idea for better manage this king of situation from external API calls? I try to avoid internal data aggregation, i … -
How to print the contents of the uploaded file in django?
Hi I am beginner in django I was trying to print the content of the uploaded file so far I did is def upload(request): if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) return HttpResponse("Successful") return HttpResponse("Failed") def handle_uploaded_file(file, filename): f = open(filename, "r") print(f.read()) I am getting error as FileNotFoundError at /file/upload/ [Errno 2] No such file or directory: 'file.odt' Note: file.odt is the file which is uploaded Please help anyone thanks in advance -
Selenium timing out inconstantly with Django
I have written essentially the same code in two different projects however I'm getting different timed out in the Django project often. My Django project has an endpoint that when hit will start up Selenium webdriver and loop through the products in the database where it finds the urls to scrape. I've been having on and off luck with Article and minimal luck with Wayfair in the Django code but 100% success with the same urls in the minimal code below. Here's my Django code: @api_view(['GET']) def update_prices(request): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36', 'upgrade-insecure-requests': '1', 'dnt': '1' } DRIVER_PATH = '/usr/bin/chromedriver' options = webdriver.ChromeOptions() options.add_argument("--incognito") options.add_argument("--headless") options.add_argument(f"user-agent={headers['User-Agent']}") driver = webdriver.Chrome(executable_path=DRIVER_PATH, options=options) driver.set_window_position(0, 0) driver.set_window_size(1024, 768) XPATHS = { 'wayfair': '//*[@id="bd"]/div[1]/div[2]/div/div[2]/div/div[1]/div[2]/div/div/div/span', 'eq3': "//span[contains(@class,'MuiTypography-root') and contains(@class,'MuiTypography-h3')][1]", 'elte': '//*[@id="mainContent"]/div[1]/div/div[3]/div/div[1]/div/span', 'crate_&_barrel': '//*[@id="react_0HM7EN3OE6904"]/div/div/div[2]/div[4]/div[1]/div/div[2]/span/span/span', 'bouclair': '//*[@id="ordering-panel"]/div[1]/div[3]/div[3]/div/span/span[2]/span', 'article': '//*[@id="app"]/div[2]/div/div/div[4]/div[4]/div[2]/div[2]/div[2]/div[2]/span' } for product in Product.objects.all(): # Skip products without URL if not product.url: pass url = product.url print('Getting:', url) driver.get(url) print('Got URL') def wait_for_element(retailer): try: return WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, XPATHS[retailer]))).text except TimeoutException: return 'Timeout' if ('wayfair.ca' in url or 'wayfair.com' in url): print("Retailer: Wayfair") retailer = 'wayfair' price = wait_for_element(retailer) elif ('eq3.com' in url): print("Retailer: EQ3") retailer = … -
Using Django alllauth to sign in with ACCOUNT_EMAIL_VERIFICATION gives incorrect redirect
I am using Django allauth to manage users on my website. I want to use ACCOUNT_EMAIL_VERIFICATION and so in settings.py ACCOUNT_EMAIL_VERIFICATION = 'mandatory' # problematic - changes login redirect! LOGIN_REDIRECT_URL = '/home' home.html {% if user.is_authenticated %} ... {% else %} <p>You are not signed in</p> <p><a href="{% url 'account_login' %}">Sign In</a></p> ... {% endif %} If I comment out ACCOUNT_EMAIL_VERIFICATION = 'mandatory', sign in works as expected and redirects to '/home' If I leave it in, it redirects to accounts/confirm-email/ I have tried to find where the redirect occurs in the allauth code, but I cannot find it. Can anyone help? -
TypeError: 'InMemoryUploadedFile' object does not support indexing
I have a list of Document display in my browser, all documents that the user submit will save in my database, this is my views.py h = 0 documentname=[] for docname in request.POST.getlist('docname'): documentname.append(docname) //name of the document for i in documentname: for docfile in request.FILES.getlist('doc'): //the file of document clientsubmitdocument = clientSubmittedDocument( User=V_insert_data, Document=docfile[h], Remarks=documentname[h] ) clientsubmitdocument .save() h+=1 print("clientsubmitdocument ",clientsubmitdocument) my html {% for doc in docpergradelevel %} <tr> <td style="border-radius: 5px; border: 1px solid #ddd; "> <input type="file" name="doc">{{doc.Document_Requirements}} <input type="hidden" name="docname" value="{{doc.Document_Requirements}}"> {% endfor %} this is the error i encountered Traceback (most recent call last): File "C:\Users\Kaito\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Kaito\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Kaito\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\UCC\unidaproject\accounts\views.py", line 630, in elementaryEnrollment Document=docfile[h], TypeError: 'InMemoryUploadedFile' object does not support indexing -
Django - django.db.utils.OperationalError: no such table: django_session
I am trying to use AbstractUser in django. I made migrations and migrated and everything goes fine but then i tried to login using admin and i got the Following Error- no such table: django_session Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1.7 Exception Type: OperationalError Exception Value: no such table: django_session Can anyone help how should i fix this? I have also added AUTH_USER_MODEL in settings.py