Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django change last_login from DateTimeField to IntegerField
i have a litte probleme i have a legacy database that have a users table and in the table of users the last_login field is an integerfield when I have extend an absractbaseuser and put the last_login in IntegerField it give a me an error when trying to connect to django dashboard it say that the last_login field expected a number but got date time value any help please ? -
How to add empty_label with smart-selects ChainedForeignKey in Django
I have the following models: class CompanyRole(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Office(models.Model): company_role = models.ForeignKey(CompanyRole, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) def __str__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) company_role = models.ForeignKey(CompanyRole, on_delete=models.SET_NULL, null=True) office = ChainedForeignKey( Office, on_delete=models.SET_NULL, null=True, blank=True, chained_field="company_role", chained_model_field="company_role", show_all=False, auto_choose=True, sort=True, ) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username And the following form: class RegisterForm(UserCreationForm): office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office') def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.pop("autofocus", None) class Meta: model = User fields = ["username", "email", "company_role", "office"] This was all working fine with the chained selects from smart-selects app, however I needed to show the empty_label to show 'Select Office' which I managed to do by adding the following line to my form as shown above: office = forms.ModelChoiceField(queryset=Office.objects, empty_label='Select Office') But since adding that line to my form the empty_label now shows but the chained selection is broken as in previously the user would select company role and depending on selection would populate the list of offices. For example: company role selection was translator then no offices would be populated but if they selected … -
JQuery UI Autocomplete for Django
The project I'm currently working on requires that a form field have autocomplete functionality. The data to be populated in the autocomplete list is pulled each time the page is loaded using an API call to a 3rd-party platform. Is it possible to call a Django views function (that will implement the above mentioned API call) to provide the JQuery-UI source with the list for auto-completion? According to the documentation (https://api.jqueryui.com/autocomplete/#option-source), the source function type might be the best option for my scenario, but I might be mistaken. So I'm open to a better way of doing it in JQuery-UI if possible. thanks. -
How "--keepdb" affects setUpTestData?
From the Django documentation I see that a Django TestCase wraps the tests within two nested atomic() blocks: one for the whole class and one for each test. Then I see that setUpTestData method "allows the creation of initial data at the class level, once for the whole TestCase": so we're talking about the whole class atomic block. This means that the --keepdb flag should not affect this behaviour, because what this flag do is just skip the database create/destroy. But I noticed that if I run the test with the --keepdb flag the data I create in the setUpTestData method are preserved. I'm fine with this but I want to understand what --keepdb exactly does, because I can't understand why this happens. I tried to look directly at the Django TestCase class source code but I don't see any check about the --keepdb option. Why - if I run my test with the --keepdb option - the data I create in setUpTestData method are preserved? -
Heroku Python Local Environment Variables
Working on a heroku django project. Goal: I want to run the server locally with same code on cloud too (makes sense). Problem: Environments differ from a linux server (heroku) to a local PC windows system. Local environment variables differ from cloud Heroku config vars. Heroku config vars can be setup easily using the CLI heroku config:set TIMES=2. While setting up local env vars is a total mess. I tried the following in cmd: py -c "import os;os.environ['Times']=2" # To set an env var then py -c "import os;os.environ.get('Times','Not Found')" stdout: "Not Found". After a bit of research it appeared to be that such env vars are stored temporarily per process/session usage. So I came up with the idea of using .env file. I would like os.environ to be redirected to .env file of the root heroku project instead of the PC env vars. So I found this perfect tool direnv perfect solution for Unix-like OSs but not for Windows. views.py code (runs perfect on cloud, sick on the local machine): import os import requests from django.shortcuts import render from django.http import HttpResponse from .models import Greeting def index(request): # get method takes 2 parameters (env_var_string,return value if var is … -
Getting sum of averages in a django queryset
def get_queryset(self): current_academic_year = get_current_academic_year() domains = Domain.objects.all() start_date = self.request.query_params.get("start_date", current_academic_year.start_date) end_date = self.request.query_params.get("end_date", current_academic_year.end_date) queryset = Account.objects.annotate(**{ f"domain_overall_{domain.uuid}": Avg( "assessed_from__accountevaluationresult__calculated_rating", filter=Q( assessed_from__updated__range=(start_date, end_date) ) & Q(assessed_from__domain=domain) ) for domain in domains }).annotate(**{f"domains_total": ~query~ }) There are five domains. Here I got 5 key-value pairs with certain calculated values for each domain. I need to get the sum of those values from the first annotation, but have no idea how to retrieve it in continuous annotations. Response I need in a json must be like this: "domain_overall_8939396e-d0a9-4c87-afe1-ae3a4660d84b": 2, "domain_overall_786a99b4-38fd-4b60-ac91-5a09f007db32": 1, "domain_overall_a1f503a7-5e77-47ee-a812-7ae1fb4e8a84": 1, "domain_overall_4c55b38b-8471-48d1-bc43-323570b290a4": 1, "domain_overall_6ec0c80b-5afe-4ac2-8c07-0fff5c4f023c": 3, "domains_total": 8, What is the best approach/solution here? -
Getting error "product has no attribute " ON SerializerMethodField
Im using django raw query for some reason. where as product dont have fieldsexpiry_date so im externally adding this and some fields by using SerializerMethodField(). The thing is it is working in local fine but getting error in production 'Product' object has no attribute 'expiry_date'. CODE: # VIEWS query = Product.objects.raw( 'SELECT * FROM product p LEFT JOIN category c ON p.category=c.id WHERE p.id=' + str(product_id) ).using('product') serializer = RawSingleStockData(query[0], context={"stock": query2}).data # SERIALIZER class RawSingleStockData(serializers.Serializer): ... expiry_date = serializers.SerializerMethodField() ... def get_expiry_date(self, obj): return False ERROR: File "/home/aaa/aaa/pharmacy_product_list/views.py" in post 222. serializer = RawSingleStockData(query[0], context={"stock": query2}).data File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data 559. ret = super().data File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data 261. self._data = self.to_representation(self.instance) File "/home/aaa/aaa/pharmacy_product_list/serializer.py" in to_representation 1118. representation = super().to_representation(instance) File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation 513. attribute = field.get_attribute(instance) File "/home/virtual_env/env/lib/python3.6/site-packages/rest_framework/fields.py" in get_attribute 476. raise type(exc)(msg) Exception Type: AttributeError at /pharmacy_product_list/product/name/ Exception Value: Got AttributeError when attempting to get a value for field `expiry_date` on serializer `RawSingleStockData`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'expiry_date'. -
The SECRET_KEY setting must not be empty. Django docker
i tried to find solution on stack and other websites but without result. Im fighting with django for some days. I got my django app dockerized and it works fine. I'm using .env file to serve secret variables. And here start the problem. I can't use travis CI or debug mode in Visual Studio Code becouse my env variables are not visible. When im trying to run travis or debuger, im getting error "The SECRET_KEY setting must not be empty". The question is, how to properly configure my django app or docker instance to use env variables in every situation? Some days ago i tried to write secret_key without hidding it, but my debuger is failing on connection with database, so it seems that my variables are not visible at all. But as i said, when i run my app in normal mode or as a docker instance it works fine, my .env file is visible for django. Here you can find my settings.py SECRET_KEY = os.getenv('SEC_KEY') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': 5432 } } And here is my docker-compose file: version: '3.4' services: electronicshop: image: electronicshop build: context: … -
How to make edit function to have the previous prepopulated content
I am trying to make the existing content to be the initial value of the textarea (i.e what the user typed before while adding that page should show when the user wants to edit the page.) when the user clicks on the Edit button. When I click on edit, the content previously written tends to go to the title page in the url. Can you please help show me why? VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) class EditPageForm(forms.Form): content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", }) ) def edit_page(request, title): entry = util.get_entry(title) if request.method == "GET": form = EditPageForm(request.POST, initial={ "content": entry }) else: form = EditPageForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] util.save_entry(title, content) return redirect('encyclopedia:entrypage', title) return render(request, 'encyclopedia/editpage.html', {'form': form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Edit</a> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name="entrypage"), path("search", views.search, name="search"), path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") … -
Knockout js form is not saving in django
productscreate.html <form> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: $data.save" >Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script type="text/javascript"> var ViewModel = function () { var self = this; self.title = ko.observable(""); self.description = ko.observable(""); var PerData = { name: self.name, description: self.description, }; self.save = function () { //Ajax call to Insert the Employee $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: PerData, contentType: "application/json", headers: {'X-CSRFToken': csrftoken}, //cache: false, mimeType: "multipart/form-data", //processData: false, success: function () { window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new … -
Same Django Models Shared in two different Projects hosted at different urls
I have hosted a django project with one app on heroku. I have few models with too many data inside it . Now I wanted an another django project that will be hosted at example.herokuapp.com with same settings,views and everything as it is in keshavbits.herokuapp.com. Now the question is how can I access the Database hosted at keshavbits.herokuapp.com in the example.herokuapp.com . Or How can I share databases b/w these two apps at different locations. Kindly Help:) -
Django model with exactly 2 users references
I want to define a 'Game' model in which exactly (and not more) 2 users will compete. Each of this user can compete in another game in parallel or later. I thought about a Manytomanyfield, but I don't know how to restrict the number of users. How to do it? -
How to prefill django form Dynamically
I am trying to display a form in django and pre-filling it dynamically. I want the user of my sample news gathering site to modify an entry. I have my Manual Input form class #forms.py class ManualInputForm(forms.Form): source = forms.CharField(label="Source:", widget = forms.TextInput(attrs={'size': 97})) topic = forms.CharField(label="Topic:", widget = forms.TextInput(attrs={'size': 97})) news = forms.CharField(widget = forms.Textarea(attrs={"rows":5, "cols":100})) link = forms.CharField(label="Link (optional):", required = False, widget = forms.TextInput(attrs={'size': 97})) In the HTML I am going manually because I would like to pre-fill all fields with data coming in from the related function in views.py. #html file <form method="post" class="form-group"> {% csrf_token %} <div class="input-group mb-3"> <div class="container"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} <br> {{ field }} </div> {% endfor %} </div> <div class="input-group"> <p> </p> <button type="submit" class="btn btn-success" name="Submit">Save</button> </div> </div> </form> How do I do it? It's driving me crazy o.O I would like to keep using django's forms because of its integrated error manager (not all fields are required but some are and I'd like for django to keep managing it). Thank your for your suggestions! -
Declaring class name in variable
I am building a project and I am trying to declare class's name in variable before declaring variable. But when I declare variable like :- klassName = MyClass class klassName(models.Model): title = models.CharField(max_length=30) then it is assigning with KlassName Not the variable I referenced to it. Then I tried :- className = 'MyClass' klass = type(className, (object,), {'msg': 'foobarbaz'}) x = className() class x(): title = models.CharField(max_length=30) it is showing NameError: name 'className' is not defined I didn't find any documentation of declaring. I did follow according to This. But none is seemed to work for me. Any help would be much appreciated. Thank You in Advance. -
psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist
I hosted a django website on heroku I am unable to run migrations on it now , I tried resting database , running fake migrations , syncdb and some other possible solutions.Everything is working fine on my machine but migrations are not working on heroku I am unable to even open /admin this is the code . ~ $ python manage.py makemigrations Migrations for 'AIWeb': AIWeb/migrations/0007_alter_digitalnote_subjectname.py - Alter field subjectName on digitalnote Migrations for 'captcha': .heroku/python/lib/python3.9/site-packages/captcha/migrations/0002_alter_captchastore_id.py - Alter field id on captchastore ~ $ python manage.py migrate Operations to perform: Apply all migrations: AIWeb, admin, auth, captcha, contenttypes, sessions Running migrations: No migrations to apply. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 90, in wrapped … -
Django: SQL queries are slow due to complex sub-queries, how to split or speed them up?
I need to execute a query set with complex sub-queries like the one below. It takes a considerable amount of time to execute the query. (8000ms) I think the slowdown is caused by complex subqueries, but is it possible to split or speed up a single SQL query without generating N+1? The db lookup we are using and the slow query set this time # lookups.py class Groonga(Lookup): lookup_name = "groonga" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return "%s &@~ %s" % (lhs, rhs), params # queryset Video.objects.annotate( is_viewed=Exists(History.objects.filter(user=user, video=OuterRef("pk"))), is_favorited=Exists( Favorite.objects.filter(user=user, video=OuterRef("pk")) ), is_wl=Exists( Track.objects.filter( playlist__user=user, playlist__is_wl=True, video=OuterRef("pk") ) ), ).filter( Q(title__groonga=value) | Q(tags__pk__in=Tag.objects.filter(name__groonga=value).values_list("pk")), is_public=True, published_at__lte=timezone.now(), ).order_by("-published_at").distinct()[:20] SQL query and EXPLAIN ANALYZE results SELECT DISTINCT "videos_video"."id", "videos_video"."published_at", EXISTS (SELECT (1) AS "a" FROM "videos_history" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_viewed", EXISTS (SELECT (1) AS "a" FROM "videos_favorite" U0 WHERE (U0."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS "is_favorited", EXISTS (SELECT (1) AS "a" FROM "videos_track" U0 INNER JOIN "videos_playlist" U1 ON (U0."playlist_id" = U1."id") WHERE (U1."is_wl" AND U1."user_id" IS NULL AND U0."video_id" = "videos_video"."id") LIMIT 1) AS … -
End a for loop if a certain condition is met in Django using templates
A similar question was asked before but the provided solutions did not work for me. Let's say I receive a list from the django views, for instance: context['requests'] = requests In the template: {% for r in requests %} {% if r.status == "Active" %} //do A {% else %} //do B {% endif %} {% endfor %} The requests list has 10 elements, one of them satisfies the condition of r.status == "Active". (invented example) What I want is: Check the requests list to determine if any of the elements in the list satisfies the condition of r.status == "Active" (or whatever condition, this is just an example) If some element in the list has the status Active the for loop will execute only one iteration, run the //do A code and then the loop will finish/break. If no element in the list has the status Active, the for loop will execute the //do B once and then break. I'm a bit confused and I don't know if there is another default tag to do this type of operation in Django -
pytest for django rest frame work api returns 301
I made simple Django application which returns {'result': 'OK'} for endpoint '/api/v1/test/ping/'. Now I am trying to test it with pytest. My test directory /test conftest.py /test_app test_api.py My conftest.py import pytest from rest_framework.test import APIClient @pytest.fixture def api_client(): return APIClient My test_api.py import pytest def test_api1(api_client): response = api_client().get("/api/v1/test/ping") assert response.status_code == 200 Test script execution fails: test_api.py::test_api1 FAILED [100%] test\test_gml_api\test_api.py:3 (test_api1) 301 != 200 But code works correct if I run server and check it manually! Give me please an advise how to solve this? -
How to youtube-dl video download directly to a user side not download file in local system using python Django?
I am trying to youtube videos to merge with audio(formate_id:140) and video(formate_id:313) using the youtube-dl library. But it downloads files in the local system. I want it directly download to the client side. I don't want to store files in the local system. Client-side means downloading files directly to a user system through a browser. Local system means it's my server. Example ydl_opts = { 'format': '313+140', 'keepvideo':'false', } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=Wt8VRxUYDso']) If any way like merging process and response streaming process work at a time. r = requests.get(videoUrl, stream=True) response = StreamingHttpResponse(streaming_content=r) response['Content-Disposition'] = f'attachement; filename="{fileName}"' return response Please guide me in solving this coding problem. -
default language url not working in Django Debug false mode
When Debug = True everything is working as expected, but when Debug is False, URL opens 404 page for default URL. For example my URL is like that -> www.example.com this is opens www.example.com/**en** automatically when debug true, but when debug is false it doesn't work and opens like that www.example.com/ and shows my custom 404 page. . Site is multilingual and I wrote urls.py like that urlpatterns = i18n.i18n_patterns( path('', include("core.urls")), Any ideas? -
CORS error after adding secondary database(Amazon Redshift) to Django
After adding secondary database(Redshift) to Django, I am getting CORS error 'no access control allow origin' in production environment. Frontend is React. Everything works fine when I run Django server on localhost, but as soon as I push changes, I get cors error on login. By the way login api call uses differnet database(Amazon RDS/MySQL). I have checked django cors headers. Configured VPC and security groups. But I still get the same error? Maybe someone have had similar issue before and could share some widsom or nudge in direction of the problem? Thanks in advance for your help. -
Django | Type error - missing 1 required positional argument: 'file_id'
Hello I'm trying to create a platform that will solve problems and then let the user download a file with the result. I'm having trouble with the downloading part this is the error I'm getting TypeError at /download/ download() missing 1 required positional argument: 'file_id' models.py class Snippet(models.Model): email = models.CharField(max_length=100) file = models.FileField(upload_to='documents/') def __str__(self): return self.email urls.py from . import views from .views import (snippet_detail) app_name = 'app' path('download/<int:file_id>/', views.snippet_detail, name='snippet_detail'), views.py def download(request, file_id): media_path = "/home/me/project/media/documents/" result_path = '/home/me/Desktop/' max_timeout = 1*24*60*60 #days*hours*mins*secs if request.method == 'POST': form = SnippetForm(request.POST, request.FILES) if form.is_valid(): form = Snippet(file=request.FILES['file']) form.save() file_name_final = form.file.name[10:] file_path = media_path + file_name_final ### analysis code ### data_id = test['outputs'][0].get('id') datamap = dict() datamap['0'] = {'src': 'hda', 'id': data_id} results_run = .. results_id = results_run['outputs'] file_id= ''.join(results_id) if file_id !='': filepath= 'result_path' + file_id path = open(filepath, 'rb') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; file_id=%s" % file_id return redirect('/download/{file_id}') else: raise Http404("No result file") download.html <p>Your problem is solved please click here to download <a class="btn btn-default btn-sm" title="Download the file" data-toggle="tooltip" data-placement="right" href="{% url 'app:snippet_detail' file.id %}"> <i class="bi bi-download"></i> </a> </p> -
Table relations with django models
I am having models for subjects like English , Biology and so on. and in the other side I have a model called teachers that store records of teachers .I am working on with Django and the problem is that I don't know how could I create the many to many relationship between teachers and the subjects what am trying to achieve is to assign the responsibility of teachers. I tried to make the models English ,Biology and others into one model called Subjects and later to use Manytomanyfield, but the frequencies are totally different and I stacked. some of my models are listed below. `class English(models.Model): studentID = models.IntegerField() l_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) s_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) r_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) w_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) hw_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) t_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) p_1 = models.DecimalField(max_digits=5, decimal_places=2, default=0) l_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) s_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) r_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) w_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) hw_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) t_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) p_2 = models.DecimalField(max_digits=5, decimal_places=2, default=0) def get_mark_30_first(self): sum = self.l_1+self.s_1+ self.r_1 + self.w_1 + self.hw_1 + self.t_1 +self.p_1 return sum def get_mark_30_second(self): sum = self.l_2+self.s_2+ … -
Getting : Not Found: /{% url "postQuestion" %} in Django app
So I am running this django app which is a FAQ knowledge base search engine. the app runs on localhost port 8000 whereas the BERT model runs on localhost 5000. Unfortunately, while clicking on "post a question" option on the front end html page, the request doesn't go to the view which is created. My App's view.py code snippet: def postQuestion(request): print ("---------------reposting-----------------") dataOwners=db.dataOwners if request.method=="POST": json_dict={} json_dict['User_ID']=request.user.id json_dict['Question_asked']=request.POST['question'] json_dict['Category']=request.POST['cat'] json_dict['Sub-Category']=request.POST['subCat'] moderator_document = dataOwners.find({'Category' : json_dict['Category']}) mods_list=[] for i in moderator_document: mods_list.append(i['Moderator']) json_dict['Moderators_available']=mods_list json_dict['Moderator_assigned']='null' json_dict['Status']="Pending Assignment" json_dict['Answer_given']= 'null' if 'revision' in request.POST and 'qid' in request.POST: json_dict['Comments']="Query details corrected" questionColl.find_one_and_update({"_id" : ObjectId(request.POST['qid'])}, {"$set": {"Question_asked":json_dict['Question_asked'],"Category":json_dict['Category'] ,"Sub-Category":json_dict['Sub-Category'],"Moderators_available":mods_list,"Comments":json_dict['Comments'],"Status":json_dict['Status'] } },upsert=True) else: json_dict['Comments']=request.POST['comments'] questionColl.insert_one(json_dict) data=json.loads(json_util.dumps(json_dict)) return HttpResponse(data) I idea is that when someone post a question from the html front-end, the control goes to the above function which then puts the question details in a database collection (local mongodb). The data is being collected through a ajax call which should push the question details to "postQuestion" view. However I am getting an error like below: [28/Dec/2021 15:20:27] "POST /%7B%%20url%20%22postQuestion%22%20%%7D HTTP/1.1" 404 5624 Not Found: /{% url "postQuestion" %} My ajax call snippet: // Post a question ajax call // $(document).ready(function(event){ $(document).on("click","#postQuestion",function(event){ event.preventDefault(); //data to … -
This field is required DRF on server side only
I created a django restframe work api which is working fine locally. But when I moved it to the server, it stop working. On server i am getting this { "file_name": [ "This field is required." ] } Here is the code view.py class VideoUploadViews(APIView): def post(self, request): serializer=VideoUploadSerializer(data=request.data)#acess the data if serializer.is_valid():#check validation start=time() vid_path=serializer.data["file_name"] vid_path=os.path.join(settings.S3PATH,vid_path) pred_hr=inference.predicthr(vid_path) end=time() return Response({"status": "success", "predicted hr": pred_hr,'time taken':end-start},\ status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class VideoUploadModel(models.Model): file_name = models.CharField(max_length=100,blank=False, null=False) serializer.py class VideoUploadSerializer(serializers.ModelSerializer): class Meta: model=VideoUploadModel fields='__all__'