Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Exception Handler doesn't get invoked
I've been using custom exception handler to alter the default behavior while raising ValidationError, since i need to get user-friendly message in json instead 500 status code and html page. However, im faced with an issue, that handler does not even get invoked. The path to handler is specified correctly in settings.py: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'api.utils.exception_handler.handler', } Part of the handler function in exception_handler.py: def handler(exc, context): response = exception_handler(exc, context) ... Part of the post method in APIView class: def post(self, request, *args, **kwargs): serializer = UserMiniSerializer(data=request.data) if serializer.is_valid(raise_exception=True): ... Part of the Validate method of UserMiniSerializer: def validate(self, attrs): ... if not user.check_password(password): raise ValidationError({'password': 'Invalid password. Please, try again.'}) ... I've tried to handle ValidationError with try-except block in post method, however i think there is a better solution. Thanks. -
manytomany: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import)
I'm facing this problem with a ManyToManyField in Django . Import Error: cannot import Room from partially initialized module. file contact.py: from django.db import models from accounting.models.account import Account class Contact(models.Model): id = models.BigAutoField(primary_key=True) last_name = models.CharField(max_length=255, blank=True, null=True) account = models.ManyToManyField(Account, through='contactaccount') file account.py from django.db import models from .accountgroup import AccountGroup from .accountclass import AccountClass class Account(models.Model): id = models.BigIntegerField(primary_key=True) code = models.IntegerField() class_account = models.ForeignKey(AccountClass, models.DO_NOTHING,default=0) group_account = models.ForeignKey(AccountGroup, models.DO_NOTHING,default=0) file contactaccount.py from django.db import models from accounting.models.account import Account from .contact import Contact class ContactAccount(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) I can' find the solution -
Give access to add items only to admin created superuser
guys. Im new using django . I did this CRUD app ,and I want to give access to add items in to the app only to 'the admin superuser' created before.Can anyone explain me how to do that, sorry for my english another thing that I need to improve to. thanks . -
djngo account register match with Users app
One of the two apps I created in my Django project is accounts and the other is Users. Accounts allows users to register, log in and log out. The Users app creates a user page using their information. How can I import the information of the user registered in the Accounts app to the app in Users? how can I do some one if registered automatically create I new user in Users app how can I access this data -
Django TIME_ZONE and USE_TZ
In my project settings I have TIME_ZONE="Europe/Kiev" and USE_TZ=True. Problem description: if it is 12.00 in Kyiv, I will receive 9.00. How can I fix this? -
django and react integration without RestApi
please let me know can we use django with react without using RestApi. i want to get the answer that can we use django with react without using django-RestApi. gimme the solution please to how can i integrate without RestApi -
postgres database is not connecting while using with docker container on django application
enter image description here this is my .env file POSTGRES_READY=0 POSTGRES_DB=dockerdc POSTGRES_PASSWORD=mysecretpassword POSTGRES_USER=myuser POSTGRES_HOST=localhost POSTGRES_PORT=5434 this is my docker-compose.yaml file version: "3.9" services: postgres_db: image: postgres restart: always command: -p 5434 env_file: - web/.env expose: - 5434 ports: - "5434:5434" volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: i think this part is having issue on this part postgres_db: image: postgres restart: always command: -p 5434 env_file: - web/.env expose: - 5434 ports: - "5434:5434" volumes: - postgres_data:/var/lib/postgresql/data/ The docker-compose.yaml file you provided seems mostly correct, but there is a minor issue with the command field for the postgres_db service. The value for command should be specified as an array of strings, but you have used a single string with a leading hyphen ( Here's the corrected docker-compose.yaml file: -
New session is creating every time I visit the cart. Django REST Framework
I want 1 session for 1 anonymous user. The thing is, every time I enter cart endpoint, session does not save. Cookie sessionid is creating only when I log in to admin panel. # views.py in cart app def get_or_create_cart(request): if request.user.is_authenticated: token, created = Token.objects.get_or_create(user=request.user) cart, _ = Cart.objects.get_or_create(user_token=token) else: if not request.session.session_key: request.session.create() session_key = request.session.session_key print(session_key) cart, _ = Cart.objects.get_or_create(session_key=session_key) cart.session_key = session_key cart.save() return cart @api_view(['GET', 'POST', 'PUT', 'DELETE']) def cart_view(request): cart = get_or_create_cart(request) if request.method == 'GET': cart_items = CartItem.objects.filter(cart=cart) serializer = CartItemSerializer(cart_items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ... # settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], } SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_NAME = "sessionid" SESSION_COOKIE_SECURE = False SESSION_SAVE_EVERY_REQUEST = True``` -
How to config django to support bulk_create with mysql upsert?
I checked MySQL with follow SQL: INSERT INTO extras (`date`, `code`, `is_st`) VALUES ('2013-01-04', '000001.XSHE', 0) ON DUPLICATE KEY UPDATE is_st = 1; But when call MyModel.objects.bulk_create, it reports error: django.db.utils.NotSupportedError: This database backend does not support updating conflicts with specifying unique fields that can trigger the upsert. -
missing files at django-admin startproject
I am learning Django & when following through I can create the startup project however it only brings one file.. so I cannot continue to start the Django development server. These are the instructions I followed so far: How do I recreate those missing files as depicted in the instructions' tree . Please assist -
Data missing (files) in my django serializer
I have an issue, some data are missing in my serializer (in validate and create functions). My Model: class PostsImage(models.Model): image = models.ImageField(upload_to="posts/images") post = models.ForeignKey( "socialmedia.Post", on_delete=models.CASCADE, related_name="posts_images" ) class Meta: verbose_name = "PostsImage" verbose_name_plural = "PostsImages" def __str__(self): return self.image class PostsAttachedFile(models.Model): attached = models.FileField(upload_to="posts/attached") post = models.ForeignKey( "socialmedia.Post", on_delete=models.CASCADE, related_name="posts_attached_files", ) class Meta: verbose_name = "PostsAttachedFile" verbose_name_plural = "PostsAttachedFiles" def __str__(self): return self.attached class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() business_sector = models.CharField(max_length=50, choices=BUSINESS_SECTOR_CHOICES) author = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="posts" ) created_at = models.DateTimeField(auto_now_add=True) valid_until = models.DateTimeField() location_type = models.CharField(max_length=20, choices=LOCATION_CHOICES) location = models.CharField(max_length=255) location_radius = models.PositiveIntegerField(null=True, blank=True) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" def __str__(self): return self.title My serializer: class PostSerializer(serializers.ModelSerializer): images = PostsImageSerializer(many=True, source="posts_images", required=False) attached_files = PostsAttachedFileSerializer( many=True, source="posts_attached_files", required=False ) class Meta: model = Post fields = "__all__" def validate(self, attrs): print(attrs) author = attrs.get("author") location_type = attrs.get("location_type") location_radius = attrs.get("location_radius") valid_until = attrs.get("valid_until") user = self.context["request"].user if author and author != user: raise serializers.ValidationError( {"author": "You can't create post for another user"} ) if location_type == "local" and not location_radius: raise serializers.ValidationError( { "location_radius": "You must provide location radius if location type is local", } ) if valid_until and … -
how should i make a button a link without losing the appearances?
I have been given a series of button elements which i have to change them into links But they lose their appearances when i put them inside a element. how should i turn these buttons into links? an example is the below button <a href="{% url 'blog:post-detail' post.slug %}" class="text-decoration-none"> <button> read more </button> </a> the main purpose of these buttons is to navigate in pages and i can not replace them entirly with links -
Are there any alternatives to PyInstaller for making standalone Python Executables or Linux Libraries
Everyone recommends pyinstaller, but I'd like to: Create the C version of the python code (including all dependent modules). In a simple script. Compile this C version into an executable or library. Call it wherever I want. For example, on linux. With this I want to gain more speed in the execution of the code because it will be compiled machine code and not interpreted. A pseudo-code to example: import numpy as np # Create two matrices matrix_A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) matrix_B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]]) # Compute the dot product dot_product = np.dot(matrix_A, matrix_B) print("Dot Product of Matrix A and Matrix B:") print(dot_product) # Compute the transpose of the resulting matrix transpose_result = np.transpose(dot_product) print("\nTranspose of the Dot Product:") print(transpose_result) I did a few searches but all of them landed on the PyInstaller option. -
Plaid Python link_token_create TypeError: expected string or bytes-like object, got 'NoneType'
I am trying to use plaid-python==15.5.0 in django and I am following plaid's own Python Quickstart (albeit for flask). But, since I'm learning, I am trying to do the integration one step at a time, Isolating each step in the flow and seeing how it works. Unfortunately, I'm stuck at step 1. and seeing as the plaid-python library recently changed significantly, there isn't much out there that pops up for my specific error. I am Running: Python 3.11.1 MacOS 11.7.8 requirements.txt asgiref==3.7.2 certifi==2023.7.22 charset-normalizer==3.2.0 Django==4.2.5 idna==3.4 nulltype==2.3.1 plaid-python==15.5.0 psycopg2-binary==2.9.7 python-dateutil==2.8.2 requests==2.31.0 six==1.16.0 sqlparse==0.4.4 urllib3==2.0.4 here's my testing.py file import os import time import plaid from plaid.model.country_code import CountryCode from plaid.model.products import Products from plaid.api import plaid_api from plaid.model.link_token_create_request import LinkTokenCreateRequest from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser # Plaid API credentials PLAID_CLIENT_ID = os.getenv("PLAID_CLIENT_ID", None) PLAID_SECRET = os.getenv("PLAID_SBX_ID", None) PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox') PLAID_COUNTRY_CODES = os.getenv('PLAID_COUNTRY_CODES', 'US').split(',') host = plaid.Environment.Sandbox if PLAID_ENV == 'sandbox': host = plaid.Environment.Sandbox if PLAID_ENV == 'development': host = plaid.Environment.Development if PLAID_ENV == 'production': host = plaid.Environment.Production PLAID_PRODUCTS = os.getenv('PLAID_PRODUCTS', 'liabilities').split(',') products = [] for product in PLAID_PRODUCTS: products.append(Products(product)) configuration = plaid.Configuration( host=host, api_key={ 'clientId': PLAID_CLIENT_ID, 'secret': PLAID_SECRET, } ) api_client = plaid.ApiClient(configuration) client = plaid_api.PlaidApi(api_client) request = LinkTokenCreateRequest( … -
How can we send notification from specific app while working with FCM notification in django?
I'm developing a website where I have 3 fcm apps. so that i have 3 credentials file of different projects. Now i have initialize three of them. But the problem is. I am unable to configure how to send notification from desire app. as you see below. this is the list of app that i initialize. {'[DEFAULT]': <firebase_admin.App object at 0x7fa5e2ce2350>, 'meidan_userpanel': <firebase_admin.App object at 0x7fa5e2ce05b0>,'meidan_merchant': <firebase_admin.App object at 0x7fa5e3uc05b1>} here is my code. def mobile_push_notes(notification=None,registration_tokens=None,file_name=None): print("file_name == ",file_name) if not file_name: return if not registration_tokens: return if isinstance(registration_tokens, str): registration_tokens=[registration_tokens] try: if not firebase_admin._apps: cred = credentials.Certificate(f'{file_name}.json') if not initializers[file_name] : initializers[file_name] = firebase_admin.initialize_app(cred) except Exception as e: print("Mobile push file not found! or ",str(e)) return None print("initializers ============================",firebase_admin._apps) message_body = remove_html(notification["message"]) if not registration_tokens: return None try: data = notification["data"] except: data="{}" message = messaging.MulticastMessage( data={ 'id':str(notification["id"]), "sender":str(notification["sender"]), "message":str(notification["message"]), "title":str(notification["title"]), "is_merchant_side":str(notification["is_merchant_side"]), "is_userpanel_side":str(notification["is_userpanel_side"]), "category":str(notification["category"]), "resolution_reply":str(notification["resolution_reply"]), "create_time":str(notification["create_time"]), "is_remove":str(notification["is_remove"]), "data":data }, notification=messaging.Notification( title=notification["title"], body=str(message_body) ), android=messaging.AndroidConfig( ttl=datetime.timedelta(days=7), # autoCancel=False, priority='normal', notification=messaging.AndroidNotification( icon='icon.jpg', color='#f45342', ), ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(), ), ), tokens=registration_tokens, ) response = messaging.send_multicast(message) here i want to specify my app where i want to send notification. response = messaging.send_multicast(message) -
can i add a static folder wtih files in the static folder and load files
I want to store a admin folder with different static files in static folder in a django project. Basically, i want to load my user part fronted with some of static files and want to load my admin panel with other diffrent static files. how can i do that? i add a folder named admin which contains admins static files. here the snippet how can i load user static files and admins static files from admin folder? -
How to correctly implement password reset in django
am getting the following error when i try to to make migrations for my app Traceback (most recent call last): File "/home/edward/Desktop/Lynia-remittance-platform-/remittance_platform/manage.py", line 22, in <module> main() File "/home/edward/Desktop/Lynia-remittance-platform-/remittance_platform/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/base.py", line 453, in execute self.check() File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/home/edward/Desktop/Lynia-remittance-platform-/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
DJANGO MODEL FORM INITIAL VALUE
Please I need help with setting initial value for my model form. from django import forms from multipage_form.forms import MultipageForm, ChildForm import calculation from .models import VinanPetLtd class ReportForm(MultipageForm): model = VinanPetLtd starting_form = "Stage1Form" class Stage1Form(ChildForm): display_name = "Transaction History" required_fields = ["entry_Date", "branch", "product"] next_form_class = "Stage2Form" class Meta: fields = ["entry_Date", "branch", "product"] widgets = { 'entry_Date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Stage2Form(ChildForm): display_name = "Tank History" required_fields = "__all__" next_form_class = "Stage3Form" class Meta: fields = [ "tank_1_Opening", "tank_1_Closing", .... ] widgets = { 'tank_1_Difference': calculation.FormulaInput('tank_1_Opening-tank_1_Closing'), 'tank_1a_Difference': calculation.FormulaInput('tank_1a_Opening-tank_1a_Closing'), 'tank_1b_Difference': calculation.FormulaInput('tank_1b_Opening-tank_1b_Closing'), ...] viwes.py from django.urls import reverse_lazy from django.views.generic import TemplateView from multipage_form.views import MultipageFormView from .forms import JobApplicationForm class JobApplicationView(MultipageFormView): template_name = 'mpf/form_page.html' form_class = JobApplicationForm success_url = reverse_lazy("mpf:thank_you") class JobApplicationThankYouView(TemplateView): template_name = 'mpf/thank_you.html' The fields are 12 and all 12 fields are not applicable to users. I want users to only fill fields applicable to them and submit with other fields as 0 initial value. I was wondering if overwriting the init function of would solve the problem. -
Fail to serialize body, when trying to send a post request with kotlin ktor to django rest API
I'm getting the following error, when I try to make a post request to my django rest API with ktor Error: Fail to serialize body. Content has type: class com.example.watchwithmemobile.domain.dto.user.UserPostRequest (Kotlin reflection is not available), but OutgoingContent expected. If you expect serialized body, please check that you have installed the corresponding feature(like Json) and set Content-Type header. I'm trying to get the username, email, password, password_check from a composable textField in kotlin, then within ktor to send an HTTP post request to my django REST API. However, I get the errors listed above. I'm catching the exception in the PostServiceImplementation as custom exception, I also have the 4xx exceptions catcher. I'm currently using Ktor 1.6.3, I do not want to migrate to version 2.x.x. The create user view in django accepts: username = request.data.get('username') email = request.data.get('email') password = request.data.get('password') password_check = request.data.get('password_check') and it is accessed by http://127....../user/register its response is a {'Actuvation': 'Account created'} in kotlin, the Response/Request look as follows: data class UserPostResponse ( val activation: String ) data class UserPostRequest( val username: String, val email: String, val password: String, val password_check: String ) and the post service implementation: override suspend fun createUser(postRequest: UserPostRequest): UserPostResponse? { return … -
How do I check the count of different requests?
I'm working on a small project, and I want to write a function that will count the number of requests. If this is the first request to this url, then the cookie value is false, and if this request is greater than 1, then the value is true, but I ran into a problem. My function is not reset after changing the url; how can I fix it? My code: def request_counter(request, request_number=[0]): request_number[0]+=1 return request_number[0] def set_cookie(url: str) -> str: try: session = requests.Session() cookie = requests.cookies.create_cookie(name='unique', value=url, expires=None, domain=url) session.cookies.set_cookie(cookie) except Exception as e: return HttpResponse(e.args) return session.cookies.get_dict() def get_full_url(url: str, unique: bool) -> str: try: link = Links.objects.get(short_url__exact=url) if not link.is_active: raise KeyError('Ссылка больше недоступна!') except Links.DoesNotExist: raise KeyError('Попробуйте другую ссылку. Этой нет в базе данных!') if not unique: link.unique_requests_count +=1 link.requests_count +=1 link.save() else: link.requests_count +=1 link.save() return link.full_url def redirection(request, short_url): try: if request_counter(request) == 1: full_link = get_full_url(short_url, False) else: full_link = get_full_url(short_url, set_cookie(short_url)) return redirect(full_link) except Exception as e: return HttpResponse(e.args) -
User Authentication using Angular and Django Mat-error from response is not being Displayed
I’m working on Signup page and I want to handle 'if username already Exists' I have tried to console.log the Error I want to display and it’s been logged on the Console but not appearing on the Mat-error Label. This is my HTML code: <mat-form-field class="example-full-width" appearance="outline"> <mat-label>Username</mat-label> <input matInput formControlName="username" required /> <mat-error *ngIf="registrationForm.get('username')!.hasError('required')" > Username is <strong>required.</strong> </mat-error> <mat-error *ngIf=" registrationForm.get('username')!.hasError('pattern') && !registrationForm.get('username')!.hasError('required') " > Username should start with <strong>a letter or underscore.</strong> </mat-error> <mat-error *ngIf=" (registrationForm.get('username')!.hasError('minlength') || registrationForm.get('username')!.hasError('maxlength')) && !registrationForm.get('username')!.hasError('required') " > Username should be <strong>between 2 and 12 characters.</strong> </mat-error> <mat-error *ngIf="usernameTakenError"> {{ usernameTakenError }} </mat-error> </mat-form-field> and That’s my Form Submit Method. submitForm(): void { if (this.registrationForm.valid) { this.http.post('http://localhost:8000/api/register', this.registrationForm.getRawValue()) .subscribe( () => { this.router.navigate(['login']); }, (errorResponse) => { if (errorResponse.status === 400) { const errors = errorResponse.error; console.log(errors); if (errors.email && errors.email.length > 0) { this.emailTakenError = errors.email[0]; console.log(this.emailTakenError); } else { this.emailTakenError = null; } if (errors.username && errors.username.length > 0) { this.usernameTakenError = errors.username[0]; console.log(this.usernameTakenError); } else { this.usernameTakenError = null; } } else { // Handle other types of errors (e.g., server errors) here. } } ); } } How can I handle it and make it display the Error? By … -
Django access local storage
I am using jwt tokens for authentication, react for frontend and django for backend. I have two models User and Post. When a new post is made I want to associate it with the user who made it. I use axios to make a post where I send a request in a django serializer. class PostSerializer(serializers.ModelSerializer): class Meta: model = Post depth = 1 fields = '__all__' def create(self, validated_data): print(self.context['request'].auth) return Post.objects.create(user=self.context['request'].user) The problem is that the current user is AnonymousUser even if the token exists. So I thought to access the authToken from localStorage and add it by the token. Should I store authTokens in cookies and access them by there or is there another way? Is it even good to store them in cookies. Edit: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } -
Chrome GUI not showing in IIS windows server
I have a Django web scrapping project that is using Selenium and Chromedriver. Everything works fine and I tested multiple times on the local host . The problem is when I run that through my IIS server in a Windows operating system , its working in the task manager but not showing GUI. I also tested that code on that windows server using : python manage.py runserver And that was showing chrome GUI in that server local host also . So the only problem is when I run it through the IIS . How to solve this problem? Is that about security permissions? -
server error (500) after deploying to heroku - but only one page
I have recently deployed a project onto heroku using AWS for media and elephantsql. Things seem to be working okay however there is only one page that returns a server 500 error. Does anyone have any idea of where I can start to investigate? I've tried moving the checkout page. here is the page code i am trying to access {% extends "base.html" %} {% load static %} {% load bag_tools %} {% block extra_css %} <link rel="stylesheet" href="{% static 'checkout/css/checkout.css' %}"> {% endblock %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="overlay"></div> <div class="container"> <div class="row"> <div class="col"> <hr> <h2 class="logo-font mb-4">Checkout</h2> <hr> </div> </div> <div class="row"> <div class="col-12 col-lg-6 order-lg-last mb-5"> <p class="text-muted">Order Summary ({{ product_count }})</p> <div class="row"> <div class="col-7 offset-2"> <p class="mb-1 mt-0 small text-muted">Item</p> </div> <div class="col-3 text-right"> <p class="mb-1 mt-0 small text-muted">Subtotal</p> </div> </div> {% for item in bag_items %} <div class="row"> <div class="col-2 mb-1"> <a href="{% url 'product_detail' item.product.id %}"> {% if item.product.image %} <img class="w-100" src="{{ item.product.image.url }}" alt="{{ product.name }}"> {% else %} <img class="w-100" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}"> {% endif %} </a> </div> <div … -
when i whant to use views.py i give 'QuerySet' object has no attribute error
i want to open course detail with next and previouse course but my try doesnt workes and i give 404 error and when i delete try and except i give 'QuerySet' object has no attribute error and says error is from counted_viewsenter image description here views.py: ``` def course_detail(request,id): try: course = Courses.objects.get(id=id) id_list = [] course = Courses.objects.filter(status = True) for cr in course : id_list.append(cr.id) if id_list[0] == id: next_course = Courses.objects.get(id=id_list[1]) previous_course =None elif id_list[-1] == id: next_course = None previous_course = Courses.objects.get(id=id_list[-2]) else: next_course = Courses.objects.get(id=id_list[id_list.index(id)+1]) previous_course = Courses.objects.get(id=id_list[id_list.index(id)-1]) course.counted_views += 1 course.save() context = { 'course': course, 'next_course': next_course, 'previous_course': previous_course, } return render(request,"courses/course-details.html",context=context) except: return render(request,'courses/404.html') ``` urls.py: ``` from django.urls import path from .views import * app_name = 'course' urlpatterns = [ path('',Maincourse,name='courses'), path('category/<str:cat>',Maincourse,name='course_cat'), path('teacher/<str:teacher>',Maincourse,name='course_teacher'), path('search/',Maincourse,name='course_search'), path('course_detail/<int:id>',course_detail,name='course_detail'), ]``` models.py: ```class Courses(models.Model): title = models.CharField(max_length=40) content = models.TextField(max_length=1000) teacher = models.ForeignKey(Trainer,on_delete=models.CASCADE) price = models.IntegerField(default=0) image = models.ImageField(upload_to='courses',default='default.jpg') category = models.ManyToManyField(Category) counted_views = models.IntegerField(default=0) counted_likes = models.IntegerField(default=0) status = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add = True) updated_date = models.DateTimeField(auto_now = True) available_seats = models.IntegerField(default = 0) schedule = models.DateTimeField(default=datetime.datetime.now()) ``` enter image description here