Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django prefetch_related is taking to much runtime
I need to list all my devices. To do this I use a prefetch related to reduce the amount of queries. But one of them is consuming to much time.. I wonder if it can't go better. I will start with the model construction: I want a list of devices. This is the device model: class Device(models.Model): name = models.CharField(max_length=250, null=True, blank=True) def get_active_gateway(self): from backend.gateways.models import Gateway all_gatewaydevices = self.gatewaydevices.all() for gd in all_gatewaydevices: if not gd.end_date: return gd.gateway return None In the real code the model is larger, but that code is irrelevant. As you can see, a device has some gatewaydevices (which is a model between gateway and device) The gatewaydevice model looks like: class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) So in my list of devices, I want for every device, the linked gateway. This is my view: class AdminDeviceView(GenericAPIView): def get_permissions(self): return IsAuthenticated() # noinspection PyMethodMayBeStatic def get_serializer_class(self): return AdminDeviceInfoSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully fetched all data from devices."), AdminDeviceInfoSerializer, ) } ) def get(self, request): devices = ( Device.objects.prefetch_related( "gatewaydevices__gateway", ) .all() ) serializer_class = self.get_serializer_class() serializer = serializer_class(devices, many=True) devices_data = serializer.data return … -
How to change query parameters in djnago filter?
I've created a multi field filter API using django filter My custom class based filter code is as below from django_filters import rest_framework as filters class EnquiryLogFilter(filters.FilterSet): start_date = filters.DateFilter(field_name='actual_mail_date',lookup_expr='gte') end_date = filters.DateFilter(field_name='actual_mail_date',lookup_expr='lte') broker_name = filters.CharFilter(field_name='broker_name') insured_name = filters.CharFilter(field_name='insured_name') class Meta: model = EnquiryLog fields =['start_date','end_date','broker_name','insured_name'] and my filter view is class ENQUIRYFILTERVIEWSET(viewsets.ModelViewSet): # comment this when using inbuilt get_queryset queryset = EnquiryLog.objects.all() serializer_class = EnquirySerializer filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter,) filterset_class= EnquiryLogFilter ordering = ('-unique_id_for_mail') search_fields = ('country_name') now when i call my api in browser with various query parameters i am getting the result also /di_enquirylog_filter_query/?start_date=2020-08-10&end_date=2020-08-30&broker_name=Broker-BPL+5&insured_name= and my response HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "unique_id_for_mail": "DISOMPO031", "actual_mail_date": "2020-08-30", "subject_name": "RE: Macquarie - Vedanta Prepay", "broker_name": "Broker-BPL 5", "is_today_mail": -2, "insured_name": "Mac Steel", "obligor_name": "ING Prosafe Nautipa", "country_name": "UK", "limit": "USD 45M", "is_enabled": "True" } ] Until now everything is working fine,the above API works well for single query parameter or multi query parameter by keeping query parameter to blank i mean like below .../di_enquirylog_filter_query/?start_date=2020-08-10&end_date=2020-08-30&broker_name=&insured_name= Here you can see broker_name and insured_name are blank (i am using django rest framework) But when my developer hit the same api he syas that for … -
Django on Mac showing Page not found (404) with every new project
I just switch my project from windows to Mac at first I create everything correctly and tried to create a test project to make sure my environment working fine and the home page of new Django Project lunch correctly. after that I tried to zip my project from windows and move it to the Mac and issue start showing. I tried to install all the missing packages and still not working. now even if I try to create a new project I'm receiving the below error Page not found (404) Using the URLconf defined in newproject.urls, Django tried these URL patterns, in this order: admin/ The current path, Login/, didn't match any of these. even with the new project. any idea what could be the issue ? -
How to send waysiprint pdf by mail
I'm trying to generate a pdf file from an HTML template using Weasyprint python package and I need to send it via email using. Here's what i have tried: views.py : user_info = { "name": 'nadjib', } html_string = render_to_string('Proformas/command.html') html = HTML(string=html_string,base_url=request.build_absolute_uri()) # html.write_pdf(target='/tmp/mypdf.pdf'); fs = FileSystemStorage('/tmp') with fs.open('mypdf.pdf') as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'filename="Commande.pdf"' pdf = weasyprint.HTML(string=html_string, base_url=request.build_absolute_uri()).write_pdf( stylesheets=[weasyprint.CSS(string='body { font-family: serif}')]) to_emails = ['nadjzdz@gmail.com'] subject = "SH INFOR FACTURE" email = EmailMessage(subject, body=pdf, from_email='attaazd@gmail.com', to=to_emails) email.attach("Commande".format(user_info['name']) + '.pdf', pdf, "application/pdf") email.content_subtype = "pdf" # Main content is now text/html email.encoding = 'us-ascii' email.send() return response the pdf is rendered successfully but not sent by mail ? -
Celery workers in two projects with local tasks and mutual queue
I have two projects, A and B (A and B projects have a celery worker each). Project A handles user registration, login, password reset etc. Project B uses project A for user related things. Project B needs to keep some local data about users. So when a user in Project A gets updated, Project B needs to be notified (event on a message-queue). Both projects use celery and I have a message broker that both projects connect to and they can read and write events to it. This has been working fine. Now I need to create a task in Project B that should be handled by the worker in Project B (AKA NOT the worker in project A). The problem is that when I start a task in Project B it gets sent to worker A which says that the Task is unregistered (it's registered in project B!). I want to be able to start tasks in Project B that get handled by it's worker, and does not get sent to the worker in Project A. -
Foreign Key Query
I have the following models: class status(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #data class next(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') target = models.ForeignKey(User, on_delete=models.CASCADE, related_name='target') #data class settings(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #data and want to Query next and status with the following output: next,nextdata,status(target) => Attach the status of the target to the (next) queryset Is this possible via Django Query? Or should I just write raw SQL cheers, keslol -
Why is the error' ValueError at /add_to_cart/printed-shirt/ Field 'id' expected a number but got 'Red'.' being thrown?
I got this error and have no idea why this is coming ValueError at /add_to_cart/printed-shirt/ Field 'id' expected a number but got 'Green'. I'm trying to add variations to my product. So when I'm submitting, I'm printing the values the users are selecting by writing print(request.POST.getlist('variations', [])) and those are coming back as ['Red', 'Medium']. Now I was trying to see if the product matching these variations already exists in the cart. If it exists, then I would increase the quantity, and if it does not exist, then I would add a new item. But my code doesn't seem to work. Can anyone please help me with this? Thanks in advance! My views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) variations = request.POST.getlist('variations', []) print(variations) minimum_variation_count = Variation.objects.filter(item=item).count() if len(variations) < minimum_variation_count: messages.info(request, "Please specify the required variations.") order_item_qs = OrderItem.objects.filter( item=item, user= request.user, ordered=False, ) for v in variations: order_item_qs = order_item_qs.filter( item_variations__exact=v ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 order_item.save() else: order_item = OrderItem.objects.create( item=item, user= request.user, ordered=False, ) order_item.item_variations.add(*variations) order_item.save() order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if not order.items.filter(item__id=order_item.id).exists(): order.items.add(order_item) messages.success(request, "Product added to cart.") return redirect("order-summary") else: ordered_date = timezone.now() … -
Django cannot find url pattern request from Angular
Angular 8, Django 3. I have done the same routing and urls, views, services a hundred times but this one route will not work for some reason and i dont know why.. Angular: html (with link) <h2>My Restaurants</h2> <ul *ngFor = "let restaurant of restaurants"> <a [routerLink]="['/ordersummary', restaurant.id]">Orders</a> </ul> app.routing.module const routes: Routes = [ {path: 'ordersummary/:id', component:OrderSummaryComponent} ]; OrderSummaryComponent export class OrderSummaryComponent implements OnInit { constructor( private orderservice:OrderService, private router: ActivatedRoute) { } id; orders; ngOnInit() { this.id = this.router.snapshot.paramMap.get('id') this.getrestaurantorders(this.id)} getrestaurantorders(id){ this.orderservice.restaurantorders(id).subscribe( x => this.orders = x )}} OrderService export class OrderService { private baseUrl2 : string ='http://127.0.0.1:8000/users/' private restaurantordersUrl : string = this.baseUrl2+'restaurantorders/' constructor( private http: HttpClient) { } restaurantorders(id):Observable<any>{ return this.http.get<any>(this.restaurantordersUrl+id) } Django urls.py #base urls urlpatterns = [ path('users/', include('users.urls')), #users urls urlpatterns = [ path(r'restaurantorders/<int:pk>', RestaurantOrders.as_view(), name='restaurantorders'), ] views.py class RestaurantOrders(generics.RetrieveAPIView): serializer_class = RestaurantOrderSerializer queryset = Orders.objects.all() serializers.py class RestaurantOrderSerializer(serializers.ModelSerializer): recipe = RecipeSerializerName customer = CustomerSerializerShort class Meta: model = Orders fields = '__all__' I know that Angular is asking for the correct url because the error i get is "Http failure response for http://127.0.0.1:8000/users/restaurantorders/2: 404 Not Found". But the http://127.0.0.1:8000/users/restaurantorders/2 url is right there... i dont understand, all of my other requests work. … -
How to handle celery tasks on multiple nodes pointing to the same database on Django?
I have a question with a problem that I'm having, my system run on multiple servers (let's call them nodes) pointing to the same database (postgres), each node has celery tasks that monitor around 1000 sensors each, all that data is collected on a central database (postgress) on a 30 secconds interval. My problem is that I don't know why celery keeps all my connections to the database "open" and one node alone takes almost 40 connections to postgress. Postgress has a limit around 100 connections by default, so adding more than couple nodes hits the connection limit. I tried using pgbouncer but had. a really bad peformance impact on the system, I'm thining that i will try pgpool II with database replication on multiple servers and test that. Instead of trying to remedy the problem, I wanted to know if there is anything that I can do on celery to mitigate the amount of connections open to the database. As a quick test after each task I added a line db.connections['default'].close() to try forcing close the database, but I can still see multiple connections from celery to the database. Any ideas on what is causing this? I'm using django … -
How to insert the blog pagination on Django Blog
I trying to implement pagination on my blog using the Bootstrap. I did comment because in this way is working but shows only one number. I did try some different way but not working yet, I feel that is close. or not. :-) Following my "blog.html" file. Thank you. <nav aria-label="Page navigation example"> <ul class="pagination pagination-lg justify-content-center"> {% if queryset.has_previous %} <li class="page-item"> <a class="page-link" href="?{{ page_request_var }}={{ queryset.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% endif%} {% comment %} <li class="page-item"><a class="page-link" href="?{{ page_request_var }}">{{ queryset.previous_page_number}}</a></li> {% endcomment %} <li class="page-item"><a class="page-link" href="?{{ page_request_var }}">{{ queryset.number }}</a></li> {% comment %} <li class="page-item"><a class="page-link" href="?{{ page_request_var }}">{{ queryset.next_page_number}}</a></li> {% endcomment %} {% if queryset.has_next %} <li class="page-item"> <a class="page-link" href="?{{ page_request_var }}={{ queryset.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> {% endif%} </ul> </nav> -
Adding Social Authentication to Django
I am using Django 3.0.5 and python 3.6. I want to add social authentication for my blog. Related files Settings.py, urls.py and login.html are: Settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR=os.path.join(BASE_DIR,'templates') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'social_django', ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.github.GithubOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url,include from blog import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index, name='index'), path('datetime/',views.current_datetime,name='datetime'), path('',views.post_list,name='post_list'), url(r'^blog/(?P<id>\d+)/(?P<slug>[\w-]+)/$',views.post_detail,name="post_detail"), … -
why we use namspace and tow accounts urls please guide me
hello everyone i have a doubt i am just doing an online Django course in that the tutor sets two accounts in urls.py file can someone please explain me why he had done that and why we use this namespace path('accounts/', include('accounts.urls', namespace='accounts')), path('accounts/', include('django.contrib.auth.urls')) -
How to fix R1710 Either all return statements in a function should return an expression, or none of them should.?
I'm using pylint on my code and getting the error R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements) There are only two possible return statements and they both return expression if I am not mistaken @api_view(["GET", "POST"]) def user_info(request): if request.method == 'GET': username = request.GET.get("username") password = request.GET.get("password") return JsonResponse(error_handle(serialize(username, password))) if request.method == 'POST': username = request.data["username"] password = request.data["password"] return JsonResponse(error_handle(serialize(username, password))) def error_handle(serializer): error = serializer["error"].value if error > 0: return {"success": "false", "internal_code": error} return {"success": "true", "account_token": serializer.data["account_token"], "user_id": serializer.data["id"], "account_name": serializer.data["account_name"], "account_permission": serializer.data["account_permission"], "pin": serializer.data["pin"] } def serialize(user, password): data = Account.objects.get(username=user, password=password) return AccountSerializer(data) -
How to save my crawling data on Django rom?
Im using bs4 for crawling news data. At the first time, I made crawler function on views.py but it make error 504 error due to long loading time. So, I decided to crawling and save data with Django ORM with new python file named 'crawling.py' in the same directory with models. My crawler importing below functions # from django.portal import settings from .models import * import requests from bs4 import BeautifulSoup import urllib.request as req import ssl from bs4.builder import builder_registry import time but it occurs error like below (project) macs-MacBook-Pro:portalpage mac$ python crawling.py Traceback (most recent call last): File "crawling.py", line 2, in <module> from .models import * ImportError: attempted relative import with no known parent package I found way to run my crawler in root directory but I will use crontab for batch jobs so I would like to locate my crawling.py inside app directory. How could I run my crawler on back-end smoothly? -
Django comma-separated field does not work well with admin site
I wrote a custom field as shown below, following the documentation (Django 3.0). This field allows to store a list of comma-separated strings. My problem is that from_db_value is called also when populating the form field in the admin site. For example, suppose that the value in the database is alpha,beta, representing the Python list ['alpha', 'beta']. If I want to change the model instance, the form is populated with the string ['alpha', 'beta']. This would not be terrible, but when I save the model instance (without touching this field), the new value becomes ["['alpha'", " 'beta']"]! In other words, the input to the form field is then interpreted as a comma-separated list. What's the correct way to handle this, in order to have a usable admin site? class CommaSepField(models.CharField): description = "A comma-separated list of strings" def __init__(self, separator=",", *args, **kwargs): self.separator = separator super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Only include kwarg if it's not the default if self.separator != ",": kwargs['separator'] = self.separator return name, path, args, kwargs def from_db_value(self, value, expression, connection): print('here', value) if value is None: return value return value.split(self.separator) def to_python(self, value): if value is None: return None … -
is there any solution available app not compatible with buildpack
(pdjangoenv) C:\Users\bhvbh\Desktop\practice django\dental_john>git push heroku master Enumerating objects: 208, done. Counting objects: 100% (208/208), done. Delta compression using up to 4 threads Compressing objects: 100% (201/201), done. Writing objects: 100% (208/208), 2.88 MiB | 47.00 KiB/s, done. Total 208 (delta 26), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack- registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to dentist-yash. remote: To https://git.heroku.com/dentist-yash.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/dentist-yash.git' I am trying to deploy my app in heroku, but is failing with "App not compatible with buildpack" error. I have added requirement.txt and procfile in my project, yet it is failing. -
How should I solve this weird Primary Key error in Django?
I have a Django to-do list app. In this app there is a page that gives all the details about a task like subtasks and notes, etc. The url of this page is like this "/todo/name of task". I wish to pass the pk of the task as well for security reasons. Also, if I check for a task in the database with its pk along with the title then this would allow a user to have multiple tasks with the same name. But as soon as I pass the pk with the URL, I face weird issues with subtasks and notes. This is my view function that handles the page of the task: def todo_detail(request, title): try: todo = ToDo.objects.get(title=title, creator=request.user) except: return render(request, "ToDo/restrict_access.html") subtasks = SubTask.objects.filter(parent_task=todo) try: note = Notes.objects.get(parent_task=todo) except: note = Notes() if request.method == "POST": note_form = ToDoNotesForm(request.POST) subtask_form = SubTaskForm(request.POST) due_form = DueDateForm(request.POST) if note_form.is_valid(): task_notes = note_form.cleaned_data.get("task_notes") new_note = Notes(content=task_notes) new_note.parent_task = todo new_note.save() todo.has_notes = True todo.save() messages.success(request, "Your notes are saved") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) elif subtask_form.is_valid(): subtask_title = subtask_form.cleaned_data.get("sub_task") subtask = SubTask(title=subtask_title) subtask.parent_task = todo subtask.parent_task.num_of_subtasks += 1 subtask.parent_task.save() subtask.save() messages.success(request, "Subtask added") return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) elif due_form.is_valid(): days = … -
How to create a website that acts as GUI for a python script
We (my team and I) are developing a prototype sensor that uses a raspberry to preprocess sensor readings. we have a working python script and made a simple GUI using GUIzero to test everything, but this needs a screen to be connected, and that is not possible once the setup is finished and deployed in a field for example. We now have the raspberry acting as a wifi-hotspot, and after connecting to the local network, we can access the RBPi using VNC-viewer, and interact with the simple (guizero-)GUI. This is fine for continuing testing and developing. But once we will distribute the sensor to some test-users, the VNC-solution is not optimal, as it allows too much snooping around on the RBPi. To solve this, we were thinking that a nice solution would be to somehow link our python script with a web page, hosted on the RBPi. A user could then walk upto the sensor, connect to the local wireless network, type in an IP in a browser and the page that loads would then allow starting/stopping the sensor, downloading measured data, managing archiving data, ... Googling points in many directions (Django, flask, ...) and I'm too much of a … -
Nginx, Gunicorn, Django Ubuntu server 502 Bad Gateway
I am getting a 502 bad request error when I try to load a page. I have setup a django app on gunicorn, nginx and supervisor. I have looked at other posts here and they have not fixed the issue. the nginx error logs include messages like this 2020/05/06 15:09:00 [crit] 7361#7361: *4 connect() to unix:/home/USER/APP/APP.sock failed (2: No such file or directory) while connecting to upstream, client: IP, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/USER/APP/APP.sock:/", host: "HOST" supervisor config file [program:APP] command=/home/USER/APP/site/bin/python3.7 /home/USER/APP/site/bin/gunicorn --workers 3 --preload --timeout 120 --bind unix:/home/USER/APP/APP.sock APP.wsgi:application directory=/home/USER/APP autostart=true autorestart=true stderr_logfile=/var/log/APP.err.log stdout_logfile=/var/log/APP.out.log nginx config file server { listen 80; server_name _; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/USER/APP; } location / { include proxy_params; proxy_pass http://unix:/home/USER/APP/APP.sock; } } -
Django dumpdata CommandError: Unable to serialize database: invalid literal for int() with base 10
When I run the following command to export my database in a JSON file : python manage.py dumpdata > datadump.json I have the following error message : CommandError: Unable to serialize database: invalid literal for int() with base 10: b'19 22:00:00' I think that at a moment the command tries to convert a part of a datetime to an integer and fails, but I don't understand why such a thing appears. Any help will be appreciate, thanks -
Unable to run Django application on xampp server (Windows 7)
I am trying to deploy my Django project on xampp server. I have followed the steps from here I am using windows 7, Python 3.6(64 bit), xampp(64 bit) I have also installed mod_wsgi using pip install mod_wsgi command And copied and the mod_wsgi.cp36-win_amd64.pyd file to the apache's modules folder as mod_wsgi.so as mentioned in the steps in the link and added the LoadModule line as well. I have added the following lines to httpd.conf file: <IfModule wsgi_module> WSGIScriptAlias / C:\xampp\htdocs\Hostel\Hostel\wsgi.py WSGIPythonPath C:\xampp\htdocs\Hostel <Directory C:\xampp\htdocs\Hostel> allow from all </Directory> Alias /static/ C:\xampp\htdocs\Hostel\live_static\static_root <Directory C:\xampp\htdocs\Hostel\live_static\static_root> Require all granted </Directory> </IfModule> The apache server is running on port 8012 but when I open localhost:8012 it is unable to load anything. This is my error log: [Wed May 06 19:51:33.663007 2020] [core:warn] [pid 2680:tid 148] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run? [Wed May 06 19:51:33.697009 2020] [mpm_winnt:notice] [pid 2680:tid 148] AH00455: Apache/2.4.43 (Win64) OpenSSL/1.1.1g mod_wsgi/4.7.1 Python/3.6 PHP/7.2.30 configured -- resuming normal operations [Wed May 06 19:51:33.697009 2020] [mpm_winnt:notice] [pid 2680:tid 148] AH00456: Apache Lounge VC15 Server built: Apr 22 2020 11:11:00 [Wed May 06 19:51:33.697009 2020] [core:notice] [pid 2680:tid 148] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache' [Wed May … -
What SAML library is better for Django and Python?
I use python 3.6, Django 2.1.5 and SAML 2 I tried many SAML libararies so far. Most of them are either out of date or does not work at all. The last one was: python3-saml-django It produces an error: onelogin.saml2.errors.OneLogin_Saml2_Error: Invalid dict settings: sp_cert_not_found_and_required Any suggestions? -
Uncaught (in promise) TypeError: Request failed with django-pwa
I'm trying to setup django-pwa. I got like this error in console. django-pwa: ServiceWorker registration successful with scope: https://my_domain.com/ Uncaught (in promise) TypeError: Request failed. serviceworker.js:1 Application tab shows this error. No matching service worker detected. You may need to reload the page. What it did Add console.log("console.log('hello sw.js');") in serviceworker.js then console log show the comment, however I got same error at first line of the serviceworker.js I checked to access https://my_domain.com/manifest.json. It was fine. Do you have any idea to solve this problem? Please help me. -
Enable and disable dynamically a field on condition of another one in Django
I created a model TransactionModel and its related ModelForm TransactionForm. As you see below I have a field called 'Type' where I can choose between two values: 'EXPENSE' and 'INCOME'. When I choose either of them I want to be able to disable either the 'expenses' or the 'incomes' field dynamically in the form so that the user does not select both. Below is the Model class TransactionModel(models.Model): type = models.CharField(max_length=100, choices=TransactionType.choices, null=True, default=TransactionType.expense, verbose_name=_('type')) title = models.CharField(max_length=200, verbose_name=_('title')) slug = models.SlugField(max_length=200, unique_for_date='publish') amount = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('amount')) created = models.DateTimeField(auto_now_add=True, verbose_name=_('created')) publish = models.DateTimeField(default=timezone.now, verbose_name=_('publish')) updated = models.DateTimeField(auto_now=True, verbose_name=_('updated')) expenses = models.CharField(max_length=200, choices=ExpenseType.choices, blank=True, verbose_name=_('expenses')) incomes = models.CharField(max_length=200, choices=IncomeType.choices, blank=True, verbose_name=_('incomes')) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='katika_transaction') Here is the Form class TransactionForm(BSModalForm): class Meta: model = TransactionModel exclude = [ 'slug', 'user', ] def __init__(self, *args, **kwargs): super(TransactionForm, self).__init__(*args, **kwargs) if self.fields['type'] == 'EXPENSE': self.fields['incomes'].disabled = True self.fields['expenses'].disabled = False else: self.fields['expenses'].disabled = True self.fields['incomes'].disabled = False As you can see I tried to put some if condition in init of the form to do it but it doesn't work at all. in the views I don't know if I have to change something but I will also share … -
Passing anonymous users from one view to another in Django 3.0.5
I'm trying to create a fully anonymous survey, where the survey participant enters a landing site (index.html), clicks a link and is directed to a survey view. On this survey (pre_test.html) page, I want to assign a new Participant object with a primary key and link that to the Survey model via a foreign key. Because this Survey isn't the main part of my study, I want to send that Participant object to a new view, where the Participant primary key is again used as a foreign key to link to another model (call it Task). What I've tried so far in the views.py is: def pre_test(request): if request.method == "POST": participant = Participants() participant.save() participant_pk = participant.pk form = PreTestQuestionnaireForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() post_primary = PreTestQuestionnaire(pk=post.pk) post_primary.Analyst_id = Participants(pk=participant_pk) post_primary.save() request.session['user'] = participant_pk return HttpResponseRedirect(reverse('main:picture_test')) else: form = PreTestQuestionnaireForm() return render(request, 'study/pre_test.html', {'form': form}) def picture_test(request): obj = Participants(Unique_ID=request.session.get('user')) # Unique_ID is the pk I've set for Participants but when calling print(obj) all I get is Participants object (None). What am I missing in using the session? Should I not be using sessions in this way at all, or should I create actual users in another …