Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make User instance
i have two applications in my django project accounts and bp in account application i have a custom user model accounts/models.py: class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) is_admin = models.BooleanField(default=False) #other fields accounts/views.py: def signup(request): form = RegistrationForm() if request.method == 'POST': registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save(commit=False) user.is_active = True user.save() user_id=user.id return redirect(reverse('bp:profile',kwargs={'user_id':user_id})) return render(request,'signup.html',{'form':form}) bp/models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #other fields bp/views.py def profile(request,user_id): if request.method =='POST': form = NewProfileForm(request.POST) if form.is_valid(): profile=form.save(commit=False) profile.user=User.objects.get(id=user_id) profile.save() else: form=NewProfileForm() return render(request,'profile.html',{'form':form}) bp/urls.py : urlpatterns = [ path('profile/<int:user_id>/',views.profile, name='profile'), ] after creating the user it redirect me to profile html after writing the data when i submit it show me this error can you help me please -
Connecting Postgresql to Django
I am trying to connect 2 databases to django project so I can use one for develop and another on production My setting file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES["default"].update(db_from_env) export DATABASE_URL=path_to_database When i try to run server I got this error: "django.db.utils.NotSupportedError: PostgreSQL 12 or later is required (found 11.18)." But when i write psql in terminal I got: psql (14.7 (Homebrew), server 15.2) And PostgrSQL@11 is not installed on my mac -
how can i call the instance of a model like we do with request.user for the user model
I'm working on a project where users can create a specific store that will only have their own product, but beyond that, there is a main store whose products from different users are displayed, so I don't know how to do it. filter allowing me to display specific products for each user. I know that with the user we make request.user so how to do with other models? my models file class Shop(models.Model): name= models.CharField(max_length=60, verbose_name='nom') adress= models.CharField(max_length=250, verbose_name='adresse') description=models.TextField(max_length=1000) logo=models.ImageField( blank= True ,null=True ) horaire=models.CharField(max_length=100) user= models.ForeignKey(User, blank= True , null=True ,verbose_name="utilisateur", on_delete=models.CASCADE) date= models.DateTimeField(auto_now_add=True, verbose_name='date de création') data=models.JSONField(null=True,blank=True) def __str__(self) -> str: return str(self.name) my views file def products_list(request): shop=Product.objects.all() products= Product.objects.filter(shop=shop) return render(request , 'shop/product_list', locals()) def home(request): products = [{**vars(p), 'image_url': (p.image and p.image.url) or p.image_url} for p in Product.objects.all().order_by('-name')] special_product= Product.objects.filter(vip =True) productOfday=Product.objects.filter(product_of_day= True ) return render(request, 'shop/home.html', locals()) def create_shop(request): form =CreateShopFrom() error='' if request.method == 'POST': form =CreateShopFrom(request.POST) if form.is_valid: form.save() else: error='identifiants Invalides' return redirect('shop') return render(request, "shop/create_shop.html",locals()) I tried that but without success: def products_list(request): shop=Product.objects.all() products= Product.objects.filter(shop=shop) return render(request , 'shop/product_list', locals()) -
Display an expression in an HTML table?Django
I have an expression as follows (text='FX506LH | 8GB RAM | 512GB SSD | i5 | 4GB VGA ا Laptop Asus FX506LH') I want to enter it in a table in a section, what solution do you suggest? Best regard This is what I am looking for I think the image is telling. -
Can't migrate properly a column in a Django database. Anyone know why?
So I'm working on a Django project and I did some changes to my user.py model. I simply added a boolean value to it. When I run the manage.py makemigrations <my app> everything runs smoothly, but when I run manage.py migrate it crashes and displays de following error: django.db.utils.OperationalError: no such column: ""is_admin"" Which I find odd because it is on my model file and I even got to make the manage.py makemigrations <my app> command properly. Does anyone know what's going on? If it makes it more clear I can put the whole error in the comments but I didn't want to add it here since it's very long. I even tried changing the name of my attribute but it doesn't seem to matter. The error still says "is_admin" is not a column. I've tried commenting/deleting the line of code in the model and run the migrations again but it seems kinda stuck on that error. -
keep getting this error message when launching django server
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs)` File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\nyaknoiton\Desktop\Django 2\venv\lib\site- packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'psychology_app' ` That is the command line after using the cd pyschology_project to get into the directory when i try to launch my django server using python manage.py runserver i get the above error -
I am trying to deploy Django project on render.com and have some troubles with Gunicorn
I have project which is working in dev environment. I am trying to deploy it on render.com. According to logs build is successful. But then Gunicorn starts and booting workers for a long-long time. Deploy failed without any error message. Apr 19 10:56:52 PM 125 static files copied to '/opt/render/project/src/myproject/staticfiles', 349 post-processed. Apr 19 10:56:53 PM Operations to perform: Apr 19 10:56:53 PM Apply all migrations: admin, auth, avito, contenttypes, sessions Apr 19 10:56:53 PM Running migrations: Apr 19 10:56:53 PM No migrations to apply. Apr 19 10:56:54 PM ==> Uploading build... Apr 19 10:57:04 PM ==> Build uploaded in 8s Apr 19 10:57:05 PM ==> Build successful 🎉 Apr 19 10:57:05 PM ==> Deploying... Apr 19 10:57:53 PM ==> Starting service with 'cd ./myproject && gunicorn -b :8000 --preload --log-level debug myproject.wsgi' Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [INFO] Starting gunicorn 20.1.0 Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [DEBUG] Arbiter booted Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [INFO] Listening at: http://0.0.0.0:8000 (51) Apr 19 10:58:00 PM [2023-04-19 22:58:00 +0300] [51] [INFO] Using worker: sync Apr 19 10:58:01 PM [2023-04-19 22:58:01 +0300] [52] [INFO] Booting worker with pid: 52 Apr 19 10:58:01 PM [2023-04-19 … -
File "<frozen importlib._bootstrap>", No module name 'material' | AWS ec2 instance, django project
~/blog/blog$ python3 manage.py makemigrations Traceback (most recent call last): File "/home/ubuntu/blog/blog/manage.py", line 22, in <module> main() File "/home/ubuntu/blog/blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'material' when i tried to run this coomand makemigrations on aws ec2 for my django project, it appeared No module named 'material' how can I fix this problems? -
DJANGO - python manage.py inspectdb - ERROR - TypeError: translation() got an unexpected keyword argument 'codeset'
I have a database with tables and relationships between those tables in MySQL Workbench and I am trying to connect/integrate with Django. I have specified it settings.py in my Django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'data_storage', 'USER': 'root', 'PASSWORD': 'my_password', 'HOST': 'localhost', 'PORT': '3306', } } When I run python manage.py inspectdb or python manage.py inspectdb > DjangoWebPage/models.py in (VS Code) terminal, it shows an ERROR: TypeError: translation() got an unexpected keyword argument 'codeset' Full prompt: (.venv) PS C:\Users\Prakse\Desktop\DjangoApp> python manage.py inspectdb Traceback (most recent call last): File "C:\Users\Prakse\Desktop\DjangoApp\manage.py", line 22, in <module> main() File "C:\Users\Prakse\Desktop\DjangoApp\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Prakse\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Prakse\Desktop\DjangoApp\.venv\Lib\site-packages\django\contrib\auth\models.py", line 94, … -
Filtering objects by date
My app has an optional date selection. All objects created on that day will be filtered by the selected date. I have a model: class MyModel(models.Model): name = = models.CharField() ... pub_date = models.DateTimeField(auto_now_add=True) Objects will be added every day and there will be a lot of them in the future. I planned to implement filtering with something like this: object = MyModel.objects.filter(pub_date__year=year pub_date__month=month, pub_date__day=day) But it occurred to me that if I make a separate model for the date, link it to the main model and filter by related_name, then the query will be more optimal and faster. class PubDateModel(models.Model): pub_date = models.DateTimeField(auto_now_add=True) class MyModel(models.Model): name = = models.CharField() ... pub_date = models.ForeignKey(PubDateModel, related_name='my_models') If I understand correctly, then my request will look like this: pub_date = get_object_or_404(PubDateModel, pub_date=date) objects = pub_date.my_models.all() Which option will be faster with a very large number of objects in the database? -
Page not found (404) at /user_signup in Django
Getting 404 error on signup and some more URLs. /login, /logout, /admin is working perfectly. I'm making a web app that lets a user login, logout, search a flight, book a flight and view the bookings made. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('search_flights/', views.search_flights, name='search_flights'), path('book_flight/<int:flight_id>/', views.book_flight, name='book_flight'), path('my_bookings/', views.my_bookings, name='my_bookings'), path('login/', views.user_signup, name='login'), path('signup/', views.user_signup, name='signup'),] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .models import Flight, Booking from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm, SignInForm, EditProfileForm def home(request): flights = Flight.objects.all() return render(request, 'home.html', {'flights': flights}) @login_required def search_flights(request): if request.method == 'POST': date = request.POST.get('date') time = request.POST.get('time') flights = Flight.objects.filter(date=date, time=time) return render(request, 'search_flights.html', {'flights': flights}) return render(request, 'search_flights.html') @login_required def book_flight(request, flight_id): flight = Flight.objects.get(id=flight_id) if request.method == 'POST': # Check if seats are available if flight.seats_available() > 0: # Book the ticket booking = Booking.objects.create(flight=flight, user=request.user) return redirect('my_bookings') else: # Show error message return render(request, 'book_flight.html', {'flight': flight, 'error': 'No seats available.'}) return render(request, 'book_flight.html', {'flight': flight}) @login_required def my_bookings(request): bookings = Booking.objects.filter(user=request.user) return render(request, 'my_bookings.html', {'bookings': bookings}) def user_login(request): … -
Why am I getting 403 for POST with DRF and rest_framework_api_key?
I am getting a 403 response from the server in my new Django app. It is very simple. I don't even have models, I just want to return an audio file, but I want to do it through an API. Because of that, since I am not going to have users, I need an API key, and I found that I can use the Django REST framework and the REST framework API key modules. I have followed the quickstarts and can't seem to get a response. It was working before, but it was authenticating through CSRF, and like I said, it is going to be an API, so I won't have CSRF cookies. Here is the view I am using: @api_view(["POST"]) def tts_view(request): data = request.POST voice_name = data.get("voice_name") text = data.get("text") if not voice_name or not text: return JsonResponse({"error": "Missing voice_name or text"}, status=400) return JsonResponse({"wav": text_to_wav(voice_name, text)}, status=200, safe=False) The settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'TTS', ] 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', ] REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] } And the fetch (the API key is just a test, so it doesn't matter): fetch('/create-speech', … -
An issue with OTP verification while using python-social-auth
I am attempting to implement a third-party login flow that redirects to an OTP verification screen before redirecting to a dashboard screen. It seems that after completing the OTP verification, when you use the command return redirect(reverse('social:complete', args=(backend_name,))), an 'AuthMissingParameter' error occurs with the message 'Missing needed parameter state'. I am not sure what's wrong with my code, any tips/suggestions are greatly appreciated. setting.py django_settings.SOCIAL_AUTH_PIPELINE = [ 'common.djangoapps.third_party_auth.pipeline.parse_query_params', 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'common.djangoapps.third_party_auth.pipeline.show_otp_form', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ] pipeline.py @partial.partial def show_otp_form(strategy, details, backend, request, *args, **kwargs): is_pass_otp = strategy.session_get("is_pass_otp", None) if not is_pass_otp: request.session['backend_name'] = request.backend.name return redirect('otp') views.py def otp_form(request): if request.method == 'POST': ....logic verify code OTP........ request.session['is_pass_otp'] = True backend_name =request.session['backend_name'] return redirect(reverse('social:complete', args=(backend_name,))) return TemplateResponse(request, 'otp/otp.html', {}) -
Django HTTPS on EC2 without a domain name?
I have a Django app working on HTTP with an EC2 instance running Amazon Linux 2. I was hoping to get HTTPS working without a domain name. How would I get a self signed certificate to work with the public IPv4 address assigned to my EC2 instance and then launch the django app on EC2 with HTTPS? Is it even possible? I have tried making a certificate using openssl and running the django app using django-extensions and Werkzeug using python manage.py runserver_plus but the app crashes on ec2 (works fine locally). I have tried a few other python packages with the same results. Any help is appreciated. -
Why coming this error: UnicodeDecodeError at /api/image/
My goal is to show the image's URL in response but it's not working. I getting errors. Here actually is it possible to return request.data.get('img')? Can you please give me a solution? serializer.py: class ImageSerializer(serializers.Serializer): img = serializers.ImageField(required=False) views.py: class ImageView(APIView): def post(self, request): serializer = ImageSerializer(data=request.data) return Response( { "processed_image_data": request.data.get('img') }, status=status.HTTP_200_OK ) errors: UnicodeDecodeError at /api/image/ 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Request Method: POST Request URL: http://127.0.0.1:8000/api/image/ Django Version: 4.2 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Exception Location: D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\rest_framework\utils\encoders.py, line 50, in default Raised during: app.views.ImageView Python Executable: D:\23_Spondon-Bhai\2_Image-Process\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\23_Spondon-Bhai\\2_Image-Process', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\23_Spondon-Bhai\\2_Image-Process\\venv', 'D:\\23_Spondon-Bhai\\2_Image-Process\\venv\\lib\\site-packages'] Server time: Wed, 19 Apr 2023 17:23:42 +0000 Unicode error hint The string that could not be encoded/decoded was: ���� Traceback Switch to copy-and-paste view D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\django\core\handlers\exception.py, line 55, in inner return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner Local vars D:\23_Spondon-Bhai\2_Image-Process\venv\lib\site-packages\django\core\handlers\base.py, line 220, in _get_response self.check_response( response, middleware_method, name="%s.process_template_response" % (middleware_method.__self__.__class__.__name__,), ) try: response = response.render() … except Exception as e: response = … -
Cannot Configure (Error While) Django setting in nginx
My server cannot find the files, it says no files found . I have following configuration user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush off; tcp_nodelay off; keepalive_timeout 265; types_hash_max_size 2000; and Server is server { listen 8000; server_name joshna.co www.joshna.co joshna.net www.joshna.net; location = /favicon.ico { access_log off; log_not_found off; } location /static/{ autoindex on; alias /home/bsyal/mysite/mypro/static; } location /media/{ autoindex on; alias /home/bsyal/mysite/mypro-project/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Server cannot find file, I have gone thhrough others solution but could not figured out -
Rest API create class based view using a mixin
I have a view inheriting from APIView and another custom mixin. None of the APIView methods is defined in the view but it is used only for declaring it as view. I need the url from only the mixin. But the mixin's url is never found django.urls.exceptions.NoReverseMatch. I am not sure how exactly to explain the problem therefore, I will provide the code: class TypeAPI(TwoFieldListMixin, APIView): queryset = Type.objects.all() permission_classes = [IsAuthenticated] class TwoFieldListMixin: query_field: str = "id" name_field: str = "name" @action(detail=False, methods=["GET"], url_name="id_code_list") def id_code_list(self, request: Request, *args: None, **kwargs: Any) -> Response: self.query_field = ( request.query_params.get("query_field", None) or self.query_field ) self.name_field = ( request.query_params.get("name_field", None) or self.name_field ) queryset: QuerySet[Any] = self.filter_queryset(self.get_queryset()).values( self.query_field, self.name_field ) serializer: ICListSerializer = ICListSerializer(queryset, many=True) return Response(serializer.data) url.py urlpatterns = [ path("types/", TypeAPI.as_view(), name="types"), ] + router.urls Test that I am writing: def test_pt_detail_api(self)->None: res = self.client.get(f"/api/v1/na/types/id_code_list/") res = self.client.get(url) assert res.status_code == 200 Here is the error: /usr/local/lib/python3.10/site-packages/django/urls/resolvers.py:802: NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'types-id_code_lis... Or applying some variations give an error: 'request_path': '/api/v1/na/types/id_code_list/', 'exception': 'Resolver404'} Question is how can I achieve creating a simple view which inherits from a mixin and does nothing else. -
Can anyone help me figure out what's happening with this html
So i am making this ecommerce for fun and got this weird bug That is html for new-skincare.html page. But then i have this perfumes page which is exactly the same as skincare page i just changed filter options in html so instead {% for skincare_item in skincare %} i used {% for perfume in perfumes %} . This is skincare.html {% extends 'base.html' %} {% block new_products%} {% load static %} {% load item_sizes %} <section class="page-header"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="content"> <h1 class="page-name">New Arrivals</h1> <ol class="breadcrumb"> <li><a href="{% url 'product-list'%}">Home</a></li> <li class="active">new skincare</li> </ol> </div> </div> </div> </div> </section> <section class="products section"> <div class="container"> <div class="row"> <div class="col-md-3"> {% block widget %}{% include 'widget.html'%}{% endblock widget%} </div> <div class="col-md-9"> <div class="row"> {% for item in skincare %} {% if item.is_new %} <div class="col-md-4"> <div class="product-item"> <div class="product-thumb"> <!-- TODO: CHANGE PRICE IF SALE --> {% if item.sale %} <span class="bage">Sale</span> {% endif %} {% if item.is_new %} <span class="new">New</span> {% endif %} {% load display_image %} {% static 'base/static/catalog/sku/'|add_str:item.front_image|add_str:'.webp' as front_image %} <img class="img-responsive" src="{{front_image}}" alt="product-img" /> {% comment %} {% endfor %} {% endcomment %} <div class="preview-meta"> <ul> <li> <span data-toggle="modal" data-target="#itemModal{{forloop.counter}}"> <i class="tf-ion-ios-search-strong"></i> … -
Dict in Django TemplateView throws Server Error 500, ListView helps for DetailView
I'm attempting to utilise the dictionary prices to retrieve the stock prices from yahoo finance. And the Django database is where I get my stock tickers. In HTML, I am unable to utilise dict. Please review the code samples I've included below. If the datatype for the variable "prices" is likewise a dict, Django produces a 500 server error. I need to pull stock prices from yahoo finance and show stock tickers from the Django database in HTML. How can I fix it? Please give me some advice on how to show my coins using ListView. In order to assist me with DetailView, which is crucial to my online application. I want to say thank you. Model: class Coin(models.Model): ticker = models.CharField(max_length=10) def __str__(self): return self.ticker View: class BucketView(LoginRequiredMixin, TemplateView): template_name = 'coinbucket/bucket.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) symbols = [symbol.ticker for symbol in Coin.objects.all()] prices = {} for symbol in symbols: ticker = yf.Ticker(symbol) price = ticker.history(period='1d')['Close'][0] prices[symbol] = f'$ {price:.6f}' context["prices"] = prices return context Template: {% for coin in coins %} <div class="col-12 col-md-8 my-2"> <div class="card"> <div class="card-body"> <div class="row"> <div class="col">{{ coin }}</div> <div class="col">{{ prices[coin] }}</div> </div> </div> </div> </div> {% endfor %} … -
Reference Serializer fields from Model in Django Rest Framework
The usual way of creating ModelSerializer in Django Rest Framework is specifying the fields attribute: class MyModelSerializer(serializer.ModelSerializer): class Meta: model = ModelConfig fields = ( 'id', 'uid', 'hashid', 'created_at', 'updated_at', 'added_by', 'updated_by', 'qr_code',) However in bigger projects, refactoring can be easier if the fields can be referenced through their Model, instead of specifying them as a string literal. However I don't know how this could be done in the most OOP way. I have tried using Model._meta.get_field(field) but this also only accepts the field_name, not a reference to the attribute. Something like Model.field.name would be great. Is this somehow possible? -
JavaScript returns value on the first review only, l don't know why
Am having a problem but l nor know what brings it. When I try to loop the Django to for JavaScript to display the Stars, it returns only on the first review and the rest it returns nothing. Now what can't do so that each user who adds a rating it displays it's stars not displaying only the first one? Below it's my HTML and JavaScript below Even l added also an image for results if try to reflesh the page. Html {% for review in reviews %} <p>display of numbers </p> <option value="{{ review.rating }}" id="hours"></option> <div class="staz"> <p id="demo"></p> {% endfor %} JavaScript <script> let hour = document.getElementById('hours').value; let greetings; if (hour == 1){ greetings = "★"; } else if (hour == 2){ greetings = "★★" } else if(hour == 3){ greetings = "★★★" } else if(hour == 4){ greetings = "★★★★" } else if(hour == 5){ greetings = "★★★★★"; } document.getElementById('demo').innerHTML = greetings </script> Results I expected that each review, it returns it's stars. -
Django deploy never completes on render.com
I have created app on Django. It works locally. Now I am trying to deploy it on render.com. Although, build is successful deploy never completes: Apr 19 05:33:01 PM 128 static files copied to '/opt/render/project/src/myproject/staticfiles'. Apr 19 05:33:03 PM Operations to perform: Apr 19 05:33:03 PM Apply all migrations: admin, auth, avito, contenttypes, sessions Apr 19 05:33:03 PM Running migrations: Apr 19 05:33:03 PM No migrations to apply. Apr 19 05:33:04 PM ==> Uploading build... Apr 19 05:33:13 PM ==> Build uploaded in 8s Apr 19 05:33:13 PM ==> Build successful 🎉 Apr 19 05:33:13 PM ==> Deploying... Apr 19 05:33:44 PM ==> Starting service with 'cd ./myproject && gunicorn --bind 0.0.0.0:8000 --workers=2 --preload --log-level debug myproject.wsgi' Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Starting gunicorn 20.1.0 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [DEBUG] Arbiter booted Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Listening at: http://0.0.0.0:8000 (51) Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [51] [INFO] Using worker: sync Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [61] [INFO] Booting worker with pid: 61 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] [62] [INFO] Booting worker with pid: 62 Apr 19 05:33:55 PM [2023-04-19 17:33:55 +0300] … -
I cant runserver from manage.py in Django
i want to runserver from my manage.py file for my Django project but i gives me error i should say that my graphic is old(Nvidia Geforce 9500gt) and the OpenGL version its : 1.1 , i think the error is for the open gl and i need a better graphic card but see my error. My python version is : 3.8 and my django is : 4.2 and my vs code is : 1.70 July 2020 I used this code for runserver: .\manage.py runserver i should say that i cant use the python before the manage.py .manage.py runserver because my vs code is old and it gives me error! but when i use the first code this error happend in my terminal: [2612:0419/191928.798:ERROR:gl_surface_egl.cc(808)] EGL Driver message (Error) eglCreateContext: Requested GLES version (3.0) is greater than max supported (2, 0). [2612:0419/191928.798:ERROR:gl_context_egl.cc(352)] eglCreateContext failed with error EGL_SUCCESS as i say my graphic card is old. -
Getting error while install django-autofixture
[getting error while installing django-fixture, tried pip install django-fixture, tried pip3, tried specific version of autofixture still getting error "AttributeError: 'UltraMagicString' object has no attribute 'endswith' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output." ](https://i.stack.imgur.com/RHxRR.png) -
Error while deploying Django with mod_wsgi
I'm trying to deploy my django project with mod_wsgi. My site config: <VirtualHost *:80> ServerName djangoproject.com ServerAlias www.djangoproject.com DocumentRoot /home/djangoproject ErrorLog /home/djangoproject/logs/back-error.log CustomLog /home/djangoproject/logs/back-access.log combined <Directory /home/djangoproject/djangoproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangoproject.com python-path=/home/djangoproject/ python-home=/home/djangoproject/venv WSGIProcessGroup djangoproject.com WSGIScriptAlias / /home/djangoproject/djangoproject/wsgi.py </VirtualHost> But im getting error ModuleNotFoundError: No module named 'django' My project structure: /home/djangoproject /djangoproject ... wsgi.py /venv /logs manage.py What am i doing wrong?