Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save MultyPlygon in Django model field
I'm trying to save MultyPlygon to Dajngo MultiPolygonField but get this error: TypeError: Cannot set Plot SpatialProxy (MULTIPOLYGON) with value of type: <class 'shapely.geometry.multipolygon.MultiPolygon'> My actual code is model.py: ... poligon = gis_models.MultiPolygonField(verbose_name=_('Polygon'), blank=True, null=True) ... gml_parser.py: self.plot.poligon = geometry_plot self.plot.save() The geometry_plot object type is <class 'shapely.geometry.multipolygon.MultiPolygon'> Any idea ? Thanks in advance. -
Logging in Django does not work when using uWSGI
I have a problem logging into a file using python built-in module. Here is an example of how logs are generated: logging.info('a log message') Logging works fine when running the app directly through Python. However when running the app through uWSGI, logging does not work. Here is my uWSGI configuration: [uwsgi] module = myapp.app:application master = true processes = 5 uid = nginx socket = /run/uwsgi/myapp.sock chown-socket = nginx:nginx chmod-socket = 660 vacuum = true die-on-term = true logto = /var/log/myapp/myapp.log logfile-chown = nginx:nginx logfile-chmod = 640 Thanks in advance -
Is there any other option for on_delete other than models.CASCADE for a ForeignKey in Django models>
Why is the on_delete property of a ForeignKey in a Django model not default? That should be the case if there is no other option other than models.CASCADE. Is there any other option for the on_delete property? -
URL with multiple parameters throws a NoReverseMatch error
I aim to redirect the view after the form has been saved. However django keeps throwing a NoReverseMatch error. Is there a step that I've missed or a misconfiguration? views.py def add_carpet(request): context_dict = {} carpet_form = forms.CarpetForm() if request.method == "POST": carpet_form = forms.CarpetForm(request.POST) if carpet_form.is_valid(): carpet = carpet_form.save() return redirect(reverse( "dashboard_add_images", kwargs={ "model_type": "carpet", "id": carpet.id } )) context_dict["carpet_form"] = carpet_form return render( request, 'dashboard/add_carpet.html', context_dict ) def add_images(request, model_type, id): ... urls.py urlpatterns = [ path('add_carpet', views.add_carpet, name="dashboard_add_carpet"), path('add_images/<str:model_type>/<uuid:id>', views.add_images, name="dashboard_add_images"),] An example redirect url after a form has been submitted is this: http://127.0.0.1:8000/dashboard/add_images/carpet/97afd259-6ec4-48fc-869f-2a00bbe29c70 Error: Reverse for 'dashboard_add_images' with no arguments not found. 1 pattern(s) tried: ['dashboard/add_images/(?P<model_type>[^/]+)/(?P<id>[^/]+)$'] -
Go to another page without refresh [Django]
How to achieve going to another page without refreshing after for example clicking a link to another URL. More examples, I have a list of books display and when I clicked on one of the book, it will redirect me to the selected book page. This is the example of the code link. <a class="link" href="{% url 'books:view_book_detail' obj.book.name obj.pk %}">View book</a> I know about the history.pushState() but how to actually use it ? Can it be use with URL from Django. Are there any method else then stated ? -
ValueError: Field 'id' expected a number but got 'create'
When I try to request this class: class CourseCreate(CreateView): model = Courses form_class = CoursesForm template_name = 'main_app/courses/course_form.html' success_url = reverse_lazy('courses') def form_valid(self,form): messages.success(self.request, f"Course created successfully") return super().form_valid(form) I got this error: ValueError at /academiaweb/courses/create Field 'id' expected a number but got 'create'. models.py: class Courses(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() year = models.ForeignKey(SchoolYears,on_delete=models.CASCADE) class Meta(): verbose_name = 'Course' verbose_name_plural = 'Courses' def __str__(self): return self.name Urls.py: path('courses/create',views.CourseCreate.as_view(),name='course_create'), -
How do I prepopulate Foreign key fields on django admin inline?
I have Service Groups and Services. Together, they create a unique relation GroupService which includes some other foreign keys.So, in django admin, upon creation of a group, I want to prepopulate service inlines with two default services' ids. I've tried overriding the BaseInlineFormSet for my inline but no success. Here's what I've tried, now it gives me KeyError: "Key 'id' not found in 'GroupServiceForm'. Choices are: counter, deduction, numerator, service.". When I tried to implement it using self.empty_form, I actually succeeded at displaying default services' foreing keys but could not save the form even if I had all my fields filled in. class CustomInlineFormSet(BaseInlineFormSet): def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None, **kwargs): super().__init__(data=data, files=files, instance=instance, save_as_new=save_as_new, prefix=prefix, queryset=queryset, **kwargs) default_services = Service.objects.filter( is_default=True).values_list('id', flat=True) services = [form['service'].initial for form in self.forms] for default_service in default_services: if default_service not in services: empty_form = self.form(initial={'id': 12, 'group': instance.id, 'service': default_service}) # empty_form.is_valid() self.forms.append(empty_form) class GroupServiceInline(CompactInline): model = GroupService fieldsets = ( (None, {'fields': ('service',)}), ('KPI', {'fields': ('counter', 'deduction', 'numerator')}), ) formset = CustomInlineFormSet extra = 2 -
Selenium: get file URL from WebElement (django, pytest)
I'm trying to test a django web app via Selenium and pytest. My test page has the following link displayed within a table (along with other links of the same format): <a href="/download_file/?file_path=serve/myid/results_XYZ.csv"><input type="button" value="Results (.csv)" /></a> I can get that webelement by using the following code: input_fields = self.driver.find_elements(By.CSS_SELECTOR, '\\input') for elem in input_fields: value = elem.get_attribute("value") if value == "Results (.csv)": csv_link = elem # more elif clauses to get the various links calling .click() on that webelement leads to a successful download of the file, so that works. Now, I also need to extract the actual download link from that element, to get the filename. What I have tried: print(mylink.get_attribute("href")) # prints None print(mylink.get_attribute('outerHTML')) # prints <input type="button" value="Results (.csv)"> print(mylink.get_attribute('innerHTML')) # prints nothing print(mylink.get_attribute("ownerElement")) # prints None The latter is surprising to me, because the following: mydic = mylink.get_property('attributes')[0] for key in mydic: print(f"\t{key}:\t{mydic[key]}") prints, among other things, ownerElement: <selenium.webdriver.remote.webelement.WebElement (session="c470b6e33d0b2fbec3f1a0e7e26dec55", element="81bdc092-0b8b-4069-a1ec-8a685fda18a5")> So I'm confused why I can't get that ownerElement. And also, why .get_attribute('innerHTML'), which I have seen advertized everywhere, does not give me anything. But mostly, I need to know: How do I get the file-url from such a download link? -
Google OAuth2 for Android using python-social-auth
I have a Django project, that implements Google OAuth2 with python-social-auth package. It works fine for Web applications. My config in settings.py: SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('GOOGLE_OAUTH2_SECRET') AUTHENTICATION_BACKENDS = ( 'entity.oauth.backends.CustomGoogleOAuth2', 'entity.oauth.backends.CustomFacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_STRATEGY = 'entity.oauth.strategies.CustomStrategy' After completing the request I generate JWT tokens for the user: def jwt_do_complete(backend, login, user=None, redirect_name='next', *args, **kwargs): ... if user: if user_is_active(user): # Get the JWT payload for the user. refresh = TokenObtainPairSerializer.get_token(user) payload = { 'refresh': str(refresh), 'access': str(refresh.access_token) } else: raise RuntimeError('Unauthorized', 'The user account is disabled.', status.HTTP_401_UNAUTHORIZED) else: raise RuntimeError('Unauthorized', 'The user account does not exist.', status.HTTP_401_UNAUTHORIZED) return user, payload So the workflow of the authorization is the following: Frontend authenticates by Google form and receives code and other information. It sends it to the complete route of the Django server. Django verify the code with help of python-social-auth. Django sends back JWT tokens. Here is the complete view: @never_cache @csrf_exempt @psa(f'{NAMESPACE}:complete') def complete_with_jwt(request, backend, *args, **kwargs): """Authentication complete view""" try: user, token_info = jwt_do_complete( request.backend, _do_login, user=request.user, redirect_name=REDIRECT_FIELD_NAME, request=request, *args, **kwargs ) except RuntimeError as e: if len(e.args) != 3: raise return HttpResponse(json.dumps({ 'status': e.args[0], 'message': e.args[1], }), status=e.args[2]) return HttpResponse(json.dumps(token_info)) It works fine as I said … -
Django is taking the templates from virtualenv not from /templates for application
I am using Django 3.2.10 and I also use a template for frontend and for admin panel. My problem is that the website is loading the templates from virtualenv and not from the template folders in the applications. My current configuration is: INSTALLED_APPS = [ 'django.contrib.admindocs', 'apps.admin_volt.apps.AdminVoltConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.app', 'apps.crypto', 'apps.taskmgr', 'django_celery_results', 'apps.home', 'apps.authentication', 'debug_toolbar',] CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for crypto TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { ... STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = 'static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'core/static'), os.path.join(CORE_DIR, 'apps/admin_volt/static'), os.path.join(CORE_DIR, 'apps/static'), ) How can I change my configuration to ensure that the templates are taken from app/admin_volt/templates/admin and not from venv\Lib\site-packages\admin_volt\templates\admin Thank you -
Empty fields are added to the extended Users table when registering new users in Django
Empty fields are added to the extended Users table when registering new users. How to fix it? Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main models.py: from django.contrib.auth.base_user import AbstractBaseUser from django.db import models class User(AbstractBaseUser): name = models.CharField(null=False, max_length=60) email = models.CharField(null=False, max_length=60) password = models.CharField(null=False, max_length=40) level = models.IntegerField(null=True) USERNAME_FIELD = 'name' def __str__(self): return self.name views.py: from django.contrib.auth import logout from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import RegisterUserForm, LoginUserForm class RegisterUser(CreateView): form_class = RegisterUserForm success_url = reverse_lazy('login') template_name = … -
Getting com_error when I interact with Django app
I'm getting an error when I try to use a Django app. com_error at /polls/ (-2147024891, 'Access is denied.', None, None) Request Method: GET Request URL: http://192.1.1.100:4455/polls/ Django Version: 2.2.6 Exception Type: com_error Exception Value: (-2147024891, 'Access is denied.', None, None) Exception Location: C:\Python64\Python37\lib\site-packages\appdirs.py in _get_win_folder_with_pywin32, line 481 Python Executable: C:\Python64\Python37\python.exe Python Version: 3.7.4 Python Path: ['.', 'C:\\inetpub\\wwwroot\\Pounce', 'C:\\Python37\\python37.zip', 'C:\\Python37\\DLLs', 'C:\\Python37\\lib', 'C:\\Python37', 'C:\\Python37\\lib\\site-packages', 'C:\\Python37\\lib\\site-packages\\win32', 'C:\\Python37\\lib\\site-packages\\win32\\lib', 'C:\\Python37\\lib\\site-packages\\Pythonwin'] The app had been working fine over the past year. This is the first time I'm getting this error. I recently installed pypiwin32. Otherwise everything is the same. -
Django Login in context processor doesn't work properly
I tried to display login and registration form on all my Django app. For that I use context_processor that ad login form in context this is my context_processors.py in app 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: auth.login(request, user) return redirect("visuapp:user_page") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return {"login_form": form} I then call processors in settings.py TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'myapp.context_processors.login_request', ], }, }, ] And finally I ue declared form in a modal in my base.html template <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#loginModal"> SignIn </button> <!-- Modal --> <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h1>Login</h1> <form method="POST"> {% csrf_token %} {{ login_form }} <button class="btn btn-primary" type="submit">Login</button> </form> <p class="text-center">Forget Password? <a href="{% url 'password_reset' %}">Change password</a>. </p> <p class="text-center">Don't have an account? <a href="#registerModal">Create an account</a>.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close </button> <button type="button" class="btn … -
NoReverseMatch for Django and DjangoCMS App
I am trying to set up some URLs for tags and categories on a forum. The links look like this <a href="{% url 'article-list-by-tag' %}{{ tag }}" class="badge badge-info" >{{ tag }}</a> The URL pattern article-list-by-tag comes from a DjangoCMS app called AldrynNewsblog. It can be found HERE and looks like this url(r'^tag/(?P<tag>\w[-\w]*)/', TagArticleList.as_view(), name='article-list-by-tag'), Note that the NewsBlog does not have app_name declared in its urls.py. The app itself is part of a larger Django app called DjangoCMS. The url entry-point for the latter is declared in project's main urls.py as follows: path('', include('cms.urls')), The error that I am getting is Reverse for 'article-list-by-tag' not found. 'article-list-by-tag' is not a valid view function or pattern name. What should I do to resolve this? I have tried adding namespace to various URL entries as well as app_name to NewsBlog to no avail. The Django version being used is 2.1 -
ochange event only works after the second selection
I have to show some data base on selection drop down list, the form is dynamic, here is my teplates function imeiInfo () { $('select').change(function(e) { e.stopImmediatePropagation(); let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'/ajax/return_back_imei_plusinfo/', data:data, success:function(data){ console.log(data.price) if (data.price){ elm.closest("div.child_imeiforms_row").find("input.nrx").val(data.price); } if (data.mobile){ elm.closest("div.child_imeiforms_row").find("input.mobile-type").val(data.mobile); } } }) }) } imeiInfo(); <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-file-signature"></i> <label>customer</label> {{ main_form.customer | add_class:'form-control' }} </div> <p class="text-danger text-center" hidden id="collection_date_error"></p> </div> <div class="col-md-2"> <div class="form-group"> <i class="fas fa-box-usd"></i> <label>balance</label> <input type="number" disabled class="form-control" id="balance_cus"> </div> <!-- /.form-group --> </div> <!-- /.col --> <div class="col-md-4 pull-right"> <div class="form-group"> <i class="far fa-clock"></i> <label>date</label> {{main_form.created | add_class:'form-control text-center'}} </div> <p class="text-danger text-center" hidden id="company_error"></p> <!-- /.form-group --> </div> </div> <div class="row no-gutters title_info text-center table-bordered text-white"> </div> {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control choose'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-3"> <div class="form-group"> <input type="text" disabled class="form-control mobile-type" placeholder='mobile type '> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | add_class:'nrx'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-1"> <div class="form-group"> {{imei.discount | add_class:'dis'}} … -
Run Django in docker container with GDAL
I am currently trying to run a Django project inside a docker container, to provide the project with a local DB. The Project is depending on GDAL, but when trying to install the requirements it always runs into the same problem. The following is my dockerfile: FROM python:3.9-slim-buster WORKDIR /app RUN apt-get update \ && apt-get -y install netcat gcc postgresql \ && apt-get clean RUN apt-get update \ && apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal RUN pip install --upgrade pip COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . The Error message I get is always: Could not find a version that satisfies the requirement pygdal==3.2.0 (from versions: 1.8.1.0, ..., 3.3.2.10) ERROR: No matching distribution found for pygdal==3.2.0 I am running out of solutions. Thx in advance. -
Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state
I am trying to stream video. The script work fine locally but gives following error when i moved to server Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. at sendMessage (https://website.com/video:67:24) at drawCanvas (https://website.com/video:59:17) at HTMLButtonElement.<anonymous> (https://website.com/video:63:17) Here is script i am using <script type="text/javascript"> var socket = new WebSocket('ws://localhost:8888/websocket'); $(document).ready(function () { let video = document.getElementById('video'); let canvas = document.getElementById('canvas'); let context = canvas.getContext('2d'); let draw_canvas = document.getElementById('detect-data'); let draw_context = draw_canvas.getContext('2d'); let image = new Image(); if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) { video.srcObject = stream; video.play(); }); } function drawCanvas() { context.drawImage(video, 0, 0, 600, 450); sendMessage(canvas.toDataURL('image/png')); } document.getElementById("start-stream").addEventListener("click", function () { drawCanvas(); }); function sendMessage(message) { socket.send(message); } socket.onmessage = function (e) { image.onload = function () { console.log(e)}; }; }) </script> In server I changed to var socket = new WebSocket('wss://10.0.1.232:8888/websocket'); Here is code for websocket class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print ('new connection') def on_message(self, message): from sub_app.py_files.detect import get_face_detect_data image_data = get_face_detect_data(message) if not image_data: image_data = message self.write_message(image_data) def on_close(self): print ('connection closed') def check_origin(self, origin): return True application = tornado.web.Application([ (r'/websocket', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) myIP = socket.gethostbyname(socket.gethostname()) print ('*** … -
How to create private pip package on pypi that require password at installation
I want to create a private pip package so that can be accessible to specific users whom i authenticate. What I have tried I have create pip package and uploaded to pypi but that is accessible to all users, then i created using git repository which works fine but it ask my git username and password. so what i want that it ask for password only and that can be used only once. Please provide any solution Thanks in advance. -
Get the right data at the right place
I have a Json file and was able to extract some values from it and sum them up. I want to be able to put the result to the right key but can't figure it out. Below is my code: from builtins import print import json import jmespath from collections import Counter const = ['constituency A','constituency B','constituency C'] region = ['region A','region B','reigon C'] poll = ['POLLING STATION A','POLLING STATION B','POLLING STATION C','POLLING STATION Z','POLLING STATION F'] fake = {'transaction':[{'region A':{'constituency A':{ 'POLLING STATION A':{'PARTY A':10,'PARTY B':20,'PARTY C':30,'PARTY D':40}, 'POLLING STATION Z':{'PARTY A':50,'PARTY B':60,'PARTY C':70,'PARTY D':80}, 'POLLING STATION B':{'PARTY A':90,'PARTY B':100,'PARTY C':110,'PARTY D':120}, 'POLLING STATION F':{'PARTY A':190,'PARTY B':1100,'PARTY C':1110,'PARTY D':1120},}, }}]} a = json.dumps((fake)) p = json.loads(a) j = jmespath.search('transaction[*]',p) ham = [] man = set() for new_d in j: for k,v in new_d.items(): for i_k,i_v in v.items(): for w,c in i_v.items(): if w in poll and i_k in const and k in region: ham.append(c) up = len(ham) i= 0 a1=Counter() while i < up: a1 += Counter(ham[i]) i+=1 print(a1) So this is what I wanted to do, the result which is a1 will be placed a dictionary this way =>[ {'region A':{'constituency A':{'PARTY D': 1360, 'PARTY C': 1320, 'PARTY … -
Multiple buttons for differents actions in the same Django form
I have a Django form where I need to include buttons to make certains actions, like fill various fields, I'm doing this with javascript scripts. The problem comes when I click that button, the form validates, like if I'm submiting the form. Are there any ways to prevent this? -
Selenium gives Server Error 500 after click (Django, pytest)
I have a Django app that I want to test via pytest and Selenium. The routine I'm trying to go through is to let Selenium log in, then go to the menu, choose one of the options. This redirects to a new page, which is found fine. There, I let selenium enter data and click a button to start a submission. This, too, works, and redirects to a third page. On this third "your submission was created successfully" page, there is a link displayed that the user can click to collect the results of their submission (this page . This link is displayed correctly, the href URL is fine. But when I let Selenium click on it, I suddenly get a Server Error 500: <html lang="en"><head> <title>Server Error (500)</title> </head> <body> <h1>Server Error (500)</h1><p></p> </body></html> When I do the exact same thing manually, it works fine. Here's my test code (slightly simplified): @pytest.fixture(scope="class") def chrome_driver_init(request): options = webdriver.ChromeOptions() options.headless = True options.binary_location = CHROME_BIN_PATH driver = webdriver.Chrome(service=CHROME_SERVICE, options=options) request.cls.driver = driver yield driver.quit() @pytest.mark.django_db @pytest.mark.usefixtures("chrome_driver_init") class SubmissionTest(LiveServerTestCase): def test_adding_submission(self): self.driver.get(self.live_server_url) username = TEST_USER pwd = TEST_USER_PWD User = get_user_model() user = User.objects.create_user(username=username, password=pwd) user.save() # click 'Login': self.driver.find_element(By.LINK_TEXT, "Login").click() # … -
URL disapears in createview when going from get to POST
I have a question regarding an issue where I'm out of options and best describes with what is seen in the log. Some background : /order/createnumber/ is just a CBV createView that will show a create form. the url looks like url(r"^createnumber/$", views.OrderCreate.as_view(), name="order-create"), The Class looks like class OrderCreate(CreateView): """ CBV for creating order""" model = Order form_class = OrderFormCreate The above is working for a GET request put fails for a POST request, where both URLs are the same. web_1 |- - [17/Dec/2021:13:08:04 +0100] "GET /order/createnumber/ HTTP/1.0" 200 10209 "http://mytestsite.local/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0" web_1 | Not Found: /order/createnumber/ It happens in my QA environment only, I'm using gunicorn. In development it is working as expected, there I use the django runserver Any ideas on this ? -
Authentication and authorization django app(backend) using keycloak
I had a problem. I had a react app that authenticate, using KeyCloak. From KeyCloak-server i recieve some credentials, like tokens, uuid of user and etc. Then, i am trying to access api on Django Backend, but request.user is Anonymous User. So, how can I can authenticate Django DRF? Should I send credentials from frontend to backend and create User model on backend or I don't need this? -
how to use onChange with dynamic form - jquery
I'm trying to use onChange in order to return some data related to the foreign key in the drop down - select field, but it only works for the first form, after that i've to select the item twice, then returns back the data! i'm using modelformset_factory, views.py @login_required def return_back_imei_oddinfo(request): query = request.GET for item in query: if item.startswith("imei-") and item.endswith("-item"): item_id = query.get(item) break selling_price= Imei.objects.get(id=item_id).mobile.selling_price, mobile=Imei.objects.get(id=item_id).mobile.mobile.model, data = { 'price' : selling_price, 'mobile':mobile, } return JsonResponse(data) and here is my forms.py class ImeiModelChoiceField(ModelChoiceField): def label_from_instance(self,obj): return str(obj.imei) class ImeiInvoiceForm(forms.ModelForm): item = ImeiModelChoiceField(queryset=Imei.objects.filter(status=True),widget=forms.Select(attrs={'onchange':'imeiInfo();'})) class Meta: model = ImeiInvoice fields = ['item','price','cash','discount'] error_messages = { 'item':{ 'required':'تکایە ناتوانی بە بەتاڵی بەجێی بهێڵیت' }, 'price':{ 'required':'تکایە ناتوانی بە بەتاڵی بەجێی بهێڵیت' }, 'cash':{ 'required':'تکایە ناتوانی بە بەتاڵی بەجێی بهێڵیت' }, } widgets = { 'price':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}), 'cash':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}), 'discount':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}), } ItemCustomerInvoice = modelformset_factory(can_delete=True,model=ImeiInvoice,form=ImeiInvoiceForm) and also here is my templates function imeiInfo () { $('select').change(function() { let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'/ajax/return_back_imei_oddinfo/', data:data, success:function(data){ console.log(data.price) if (data.price){ elm.closest("div.child_imeiforms_row").find("input.nrx").val(data.price); } else{ alert('not found') } if (data.mobile){ elm.closest("div.child_imeiforms_row").find("input.mobile-type").val(data.mobile); } } }) }) } imeiInfo(); <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="form-group"> <i class="fas fa-file-signature"></i> … -
Communication between two Django projects
I have two python-django projects which have different databases. What is the best way two communicate between these two projects? By communication I mean reading data from each other, send data to be written into the other project's database, etc.