Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Html is not extending correctly only base.html
When trying to extend from base.html my home.html is not showing when at the url that shows home.html only the base.html is showing. I can't seem to figure out what the problem without extending my home.html shows up perfectly but when extending from base.html it seems like it doesn't want to work Base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href={% static 'css\base.css'%} </head> <body> <body> <nav class="navbar"> <ul class="navbar-nav"> <li class="nav-item">Home</li> <li class="nav-item">About</li> <!-- Dropdown will go here --> </nav> {% block body_block %} {% endblock %} </body> </body> </html> Home.html {% extends 'base.html' %} {% load static %} <div class="contianer"> <div class="heading">NEW RENTALS</div> {% for List in listings %} <div class="items"> <img src="{% static List.itempicture %}" alt="" /> <div class="Info"> <h1>{{List.title}}</h1> <p>{{List.about}}</p> <a class="button" href="{{ List.get_absolute_url }}">Contact</a> </div> </div> {% endfor %} </div> <link rel="stylesheet" href={% static 'css\home.css'%} -
Does durable Django atomic transaction imply we don't need savepoints
A Django atomic transaction has the durable and savepoint arguments. See docs. durable=True ensures the atomic block is the outermost atomic block. Per the docs: It is sometimes useful to ensure an atomic block is always the outermost atomic block, ensuring that any database changes are committed when the block is exited without errors. This is known as durability and can be achieved by setting durable=True A PostgreSQL SAVEPOINT establishes a new savepoint within the current transaction. Sounds like this is only needed if the atomic block is nested. I have the following questions: If durable=True then savepoint should ALWAYS be False, right? Because there's no point in using a savepoint if the atomic block is the outermost atomic block. If durable=True, should Django set savepoint=False for us? Reading through the source code, it doesn't appear to do it for us but I feel like it should. -
how to add like button to each blog post in the same page with django
i am building a blog platform, i tried to add like button to each post in the same page with Ajax so that whenever the like button is press it will automatically work without refreshing but it shows this error NoReverseMatch at / Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P<pk>[0-9]+)\\Z'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['like/(?P<pk>[0-9]+)\\Z'] Exception Location: C:\Users\HP\anaconda3\lib\site-packages\django\urls\resolvers.py, line 803, in _reverse_with_prefix Raised during: blog.views.HomeView Python Executable: C:\Users\HP\anaconda3\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\HP\\Dacurate-1', 'C:\\Users\\HP\\anaconda3\\python39.zip', 'C:\\Users\\HP\\anaconda3\\DLLs', 'C:\\Users\\HP\\anaconda3\\lib', 'C:\\Users\\HP\\anaconda3', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\locket-0.2.1-py3.9.egg', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\HP\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Sun, 11 Sep 2022 23:17:55 +0000 here is my view file views.py def CategoryView(request,cats): category_post=Post.objects.filter(category=cats.replace('-',' ')) return render(request,'category.html',{'cats':cats.title().replace('-',' '),'category_post':category_post}) def CategoryListView(request): cat_menu_list=Category.objects.all() return render(request,'category_list.html',{'cat_menu_list':cat_menu_list}) class UserRegisterView(CreateView): form_class=SignUpForm template_name='register.html' success_url=reverse_lazy('home') def LikeView(request, pk): post=get_object_or_404(Post, id=int(request.POST.get('post_id'))) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user.id) result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result,}) def FollowerView(request, pk): post=get_object_or_404(Post, id=request.POST.get('follow_id')) followed=False if post.followers.filter(id=request.user.id).exists(): post.followers.remove(request.user.id) followed=False else: post.followers.add(request.user.id) followed=True #return redirect (reverse('home', post.pk) + '#{{post.pk}}') #return HttpResponseRedirect(reverse('article-detail', args=[post.pk])+ '#{{post.pk}}') return redirect('home') class HomeView(ListView): model=Post template_name='home.html' ordering=['-id'] def get_context_data(self, *args, **kwargs): cat_menu=Category.objects.all() context=super(HomeView, … -
Docker + Django if_debug template tag is not working
I am running a docker-compose with nginx routing requests to my Django server, with this config: upstream django { server backend:8000; } server { listen 80; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } To use the {% if debug %} template tag I know I need both the correct internal IP and the DEBUG setting turned on. I get the correct internal IPs by running the following code snippet in my Django settings.py: import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip for ip in ips] + ['127.0.0.1'] When I docker exec -it backend sh, and import the DEBUG and INTERNAL_IPS settings, I get that the values are ['172.19.0.4', '127.0.0.1'] and True, respectively. Then, when I run docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq) to check the containers' IP address, I see that the backend container that runs Django has an IP of 172.19.0.4, same as the internal IP. Despite this all, in the Django template, I get a Django debug mode error (further proving that debug is turned on) that says that an error got triggered on line 61!!! 57 {% if debug %} 58 <!-- This … -
path() got an unexpected keyword argument 'name'
I am new to Django and trying to set up my first app (home page) and I am currently following a tutorial. When i added in a new path into my urlspatterns list, and link it to the correct function, I get TypeError: path() got an unexpected keyword argument 'name' Below is my code: App Directory urls.py from argparse import Namespace from importlib.resources import path from unicodedata import name from django.urls import re_path from . import views urlspatterns = [ path('', views.index, name='index') # this is the main site path (home page) ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. # This is form the home page def index(request): return HttpResponse('<h1>Hey, Welcome</h1>') project directory urls.py """cheatChecker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from … -
How can my users delete a file that they uploaded using latest Django version?
I'm not getting an error message---but when the Delete button is pressed in my template, nothing happens. Does anyone see what's missing in my code below? settings.py MEDIA_URL = '/home/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'home/') models.py class Roll(models.Model): csv = models.FileField(default="", upload_to='home/') def delete(self, *args, **kwargs): self.csv.delete() super().delete(*args, **kwargs) views.py class DeleteRollView(LoginRequiredMixin, DeleteView): model = Roll form_class = RollForm template_name = 'users/delete_roll.html' @staticmethod def delete_roll(self, request, pk): if request.method == 'POST': roll = Roll.objects.get(pk=pk) roll.delete() return redirect('users:list_roll') delete_roll.html <input type="submit" value="Delete"/> -
Can't seem to make a simple Hello World app
sorry in advance if my format is off this is my first time posting to here. I'm having a really hard time getting started with Django I've followed the tutorial on the https://djangoforbeginners.com/hello-world/ and when I finished I still get the standard landing page is there something that I'm not getting ? #from project.urls from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path("admin/", admin.site.urls), path("", include("pages.urls")) # new ] # from app.urls from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] #from apps.views from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1>Hello, World!</h1>") -
Html file template for Django
I understand if this quetion isn't phrased correctly, but i trying because i cant find the answer. Hello, i have a quetion(sorry if its a simple quetion, i`m beginner in django). I want to create a template html file so that it copy each time. I understand that a block exists and can be modified through it, but I want to create a template that can be inserted in the right place in the HTML code, and edit the template as needed. Exampl what it looks like now : <!doctype html> <html lang="en"> <head> <title>TITLE</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS v5.2.0-beta1 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> </head> <body> <!--NAWBAR--> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <b class="navbar-brand" href="#">Tezla</b> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog:all_blogs' %}">Blog</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> … -
Django Is the server running on host "localhost" (127.0.0.1) and accepting web-1 | TCP/IP connections on port 5432?
I am trying to dockerize my Django project. I have the following config files: Dockerfile: FROM python:3.9-bullseye WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY csgo . RUN apt-get update -y \ && apt-get upgrade -y pip \ && pip install --upgrade pip \ && pip install -r requirements.txt CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] My docker-compose.yml looks like: version: '3' services: web: build: context: . dockerfile: Dockerfile env_file: - csgo.env volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 restart: always ports: - 5432:5432 env_file: - csgo.env environment: - POSTGRES_PASSWORD=postgres - DB_NAME=postgres - DB_USER=postgres - DB_PASSWORD=postgres - DB_HOST=localhost volumes: - ./db/psql-init/db.sql:/docker-entrypoint-initdb.d/db.sql - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: When I try to docker-compose up I get this error: django.db.utils.OperationalError: could not connect to server: Connection refused csgo-web-1 | Is the server running on host "localhost" (127.0.0.1) and accepting csgo-web-1 | TCP/IP connections on port 5432? csgo-web-1 | could not connect to server: Cannot assign requested address csgo-web-1 | Is the server running on host "localhost" (::1) and accepting csgo-web-1 | TCP/IP connections on port 5432? What could be the problem? Can you explain what it means by Is the server running on host "localhost" and why it wouldn't accept connection on port 5432? … -
How to convert string into list?
Well, I am using python. And I have case here. from my api. The following key and value is coming. games : ["['football','cricket']"] Now i want to get that football and cricket from coming games value and store in python list. expected output: print(games) ==> ["football","circket"] print(type(games)) ==> <class list> -
'WSGIRequest' object has no attribute 'htmx'
Hi just looking for some help at solving this error in Django whilst trying to call a view that to accept a htmx request. The final result is to display a popup Modal of images from a Gallery when a thumbnail is clicked. HTMX installed via script in head. View if request.htmx: slug = request.GET.get('slug') context = {'pictures': Media.objects.filter(slug=slug)} return render(request, 'main/gallery-detail.html', context=context) context = {'objects_list': Albums.objects.all()} return render(request, 'main/gallery.html', context=context) Relevant html with the button to open gallery of images. <a class="btn btn-primary" hx-post="{{ request.path }}?slug={{ img.slug }}" hx-target="#modal"> {{ img.slug }}</a> {% endfor %} <div id="modal">{% include "main/gallery-detail.html" %}</div> -
How do I run function on database class rather than class in views.py in django
I have this in my views.py, it all works if I use the class in the views.py but if i switch the function to use the same class in the models.py (which is what I want to use) I get: '<' not supported between instances of 'int' and 'DeferredAttribute' If I declare it an int() then I get: a typerror. int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' This is my code. Can someone point me in the right direction please. from django.views.generic.base import TemplateView from django.shortcuts import render from django.http import HttpResponse import math, datetime from settings.models import Extruder class Extruders: def __init__(self, name, min_width = 0, max_width = 0, max_speed = 0, gussets = False, printer = False, location = "GY", lft = False, cfs = False, dws = False, jfs = False, sws = False, treatment = False): self.name = name self.min_width = min_width self.max_width = max_width self.max_speed = max_speed self.gussets = gussets self.printer = printer self.location = location self.lft = lft self.cfs = cfs self.dws = dws self.jfs = jfs self.sws = sws self.treatment = treatment def __str__(self): return self.name ext1 = Extruders(name = "Extruder 1", max_width = 300, min_width … -
How do I implement user authentication in Django using rest_framework?
I'm using Django/Python3 to make a simple API. I already made my models and views (also using serializers). Currently this is my login view: class LoginView(generics.CreateAPIView): queryset = User_Login.objects.all() serializer_class = LoginUserSerializer def post(self, request, *args, **kwargs): id = request.data['id'] name = request.data['name'] password = request.data['password'] email = request.data['email'] User_Login.objects.create(id=id, name=name, password=password, email=email) return HttpResponse({'message': 'User Created', 'id': id}, status=200) All my views are basic like this, just to implement a database that I previously modeled. I need to implement authentication (the one that generates simple tokens that the user need to add to their request's header) and I know It's easy, but I followed this tutorial and I got a lot of errors. Any advice? -
Django: "Cannot resolve keyword 'email' into field. Choices are: created_at, expires_at, id, otp, user, user_id"
I'm trying to validate an OTP that was sent to the user when registering i have a separate model for otp which has an OneToOne relation with the user Otp Model class Verify(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="userverify", blank=False, null=True) otp = IntegerRangeField( min_value=111111, max_value=999999, blank=True, null=True) created_at = models.DateTimeField( _("created at"), auto_now=False, auto_now_add=True, blank=False) expires_at = models.TimeField(null=True) the Verify_Email view takes an email and otp value to validate the email How I'm trying to verify the otp class Verify_Email(APIView): def post(self, request): try: data = request.data serializer = VerifySerializerBase(data=data) if serializer.is_valid(): email = serializer.data['email'] otp = serializer.data['otp'] verify = Verify.objects.filter(email=email, otp=otp) user = User.objects.filter(email=email) if not user[0].exists(): return Response({ 'message': "A user with this email was not found" }, status=status.HTTP_400_BAD_REQUEST) elif user[0].is_active: return Response({ 'message': "This email has already been verified" }, status=status.HTTP_400_BAD_REQUEST) elif verify[0].exists(): if verify[0].expires_at >= datetime.now(): return Response({ 'message': "This OTP has expired, please request another one" }, status=status.HTTP_400_BAD_REQUEST) elif verify[0].otp != otp: return Response({ 'message': "This OTP is invalid" }, status=status.HTTP_400_BAD_REQUEST) else: verify[0].delete() user[0].is_active = True user[0].save() return Response({ 'message': "Email has been verified" }, status=status.HTTP_200_OK) return Response({ 'message': "Something is wrong" }, status=status.HTTP_400_BAD_REQUEST) return Response({ 'message': "Something is wrong" }, status=status.HTTP_400_BAD_REQUEST) except Exception … -
Combine Scrapy with Django or isolate them
I have a Django application running at AWS ,I want to have a Scrapy crawler program to fetch data and insert into the Django application database. Now I have 2 options ,either combine Scrapy with Django or build a isolated Scrapy project and directly insert data into data without through Django's Model. I'm wondering which option is better ,I personal prefer isolating these 2 projects.There are 2 reasons: 1.I have no experience to combine Scrapy with Django. 2.Lower the risk, if one die another one can still alive. Any suggestion? -
How to change 2 separate parts in an HTML without Refreshing page using Ajax in a Django Project
I have a HTML template for a django project where there are 2 button on the top of a page and one at the end of the page. In the begining the top button is enabled and the lower one is disabled. My objectiveis that when a user clicks on the top button it gets disabled and the lower button gets enabled. Currently I am at the stage that when a user clicks the top buttons gets disabled with the whole page refreshing but I want to add the lower one to it as well. Here is the main template to have a better idea: <!-- button --> <div id="startworkout"> {% include 'my_gym/button.html' %} </div> <!-- button --> ................................................... <!-- button --> <div id="deactivate"> {% include 'my_gym/deactivate.html' %} </div> <!-- button --> Here is the button.html: <form action="{% url 'my_gym:bla' id=workout.id %}" method='post'> {% csrf_token %} {% if workout.active %} <button disabled id="customSwitches" type="button">Close Workout </button> {% else %} <button value="true" id="customSwitches" type="button" >Start the workout </button> {% endif %} </form> Here is the 2nd part deactivate.html of that I want to include: <div> {% if workout.active %} <button id="stop" onclick="stop();" type="button">Finish Workout</button> </a> {% else %} <button disabled id="stop" … -
How do I resize an image to be rendered in template without affecting original image?
I tried resizing the image in my views.py using PIL, but it doesn't take effect in the rendered page as the image is still the same size. Is there something obvious I'm missing? Views.py def home(request): if request.method == "POST": pass vendors = Vendor.objects.all() size = (360, 200) for vendor in vendors: try: image = Image.open(vendor.imageURL) except: continue image.thumbnail(size) image.save(vendor.imageURL) context = {'vendors': vendors} return render(request, 'home.html', context) Models.py class Vendor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, unique=True) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url -
Vue - Accessing Attributes in a Django Dictionary
In Vue, using {{ game.data }} results in: [ { "game": 1, "turn": 1, "player": 1, "word": "trend", "score": 18 }, { "game": 1, "turn": 2, "player": 2, "word": "test", "score": 12 } ] But I want to access {{ game.data.player }} My models.py class Game(models.Model): date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) class Word(models.Model): game = models.ForeignKey(Game, related_name='word', on_delete=models.CASCADE) turn = models.IntegerField() player = models.ForeignKey(User, on_delete=models.CASCADE) word = models.CharField(max_length=255) score = models.IntegerField() serializers.py class GameSerializer(serializers.ModelSerializer): data = serializers.SerializerMethodField(read_only=True) class Meta: model = Game fields = ['id', 'date' ,'data'] def get_data(self, obj): return WordSerializer(obj.word, many=True).data Game.vue <script> import axios from 'axios' export default { name: 'Game', data() { return { game: {}, } }, mounted() { this.getGame() }, methods: { async getGame() { this.$store.commit('setIsLoading', true) const GameID = this.$route.params.id axios .get(`/api/v1/games/${GameID}/`) .then(response => { this.game = response.data }) .catch(error => { console.log(error) }) this.$store.commit('setIsLoading', false) } } } </script> Thanks in advance, -
Can I Use Django's context processor in Django rest framework
I have a question I need to store some data globally so I can access them anywhere in my Djangorestframework application, kind of like how flask provides flask.g for this. Can I use Django context processor for this? I know I can use Django context processor if I am working with Django templates, I just want to know if it is possible for me to use it with Djangorestframework -
Show the values in dropdown in reverse order in Django Forms
class FineForm(forms.ModelForm): class Meta: model = Fine fields = ['student', 'fine'] widgets = { 'student': forms.Select(attrs={'class': 'form-control'}), 'fine': forms.TextInput(attrs={'class': 'form-control'}), } I have this Django form. The student field is a foreign key. I want to show the students in reverse order in this form in the template. Help please. -
Django, MySQL, and SSL certs: strings instead of filenames?
I'm attempting to configure a Django application to connect to a MySQLDB instance with TLS configured. Django's DATABASES settings documents how to configure the ssl settings, for eg.: DATABASES = { 'default': { 'ENGINE': os.environ.get('DATABASE_ENGINE', 'django.db.backends.mysql'), 'HOST': os.environ.get('DATABASE_HOST'), 'PASSWORD': get_vault_secret('DATABASE_PASSWORD'), ... 'OPTIONS': { 'ssl': { 'ca': '/ca/server.cert.pem', 'cert': '/ca/client.cert.pem', 'key': '/ca/client.key.pem' } } }, } Our problem is that the values required for ca, cert, and key are filenames. Our app is containerized, and we pull all of our secrets from hashicorp Vault during app initialization using a helper func (see the value for PASSWORD). We also store client certs, keys, etc in vault, and would like to supply these to Django directly - but MySQL demands a string, pointing to a file. Is there a way to wrap the cert / ca / key strings we get from vault into some kind of IOFile / BytesIO esque container to pass from Django, to python mysqlclient, to mysql_ssl_set()? Due to security considerations, actually writing these values to a file is not an option. -
after uploading file in the page update contents without refreshing the page using htmx (without ajax)
Hi iam new to HTMX and as well as Ajax and JQuery. here im not familiar with htmx and i have an issue with using htmx instead of ajax and Jquery. I have an drop down menu(options as the folder names) while selecting the option the files in the folder are displays as table there is an upload option will be enabled. using the upload option you can upload files after clicking the upload button the file is uploaded into that selected folder and displays in the same state. here, I need to show the uploaded file in that display files area without uploading the page(using htmx) and without using ajax & JQuery . how can proceed with this requirement. I have attached my html,python and JS codes here with the question.. Any help would be appreciated... script.js // Getting name of the uploaded file function fileInfo() { uploadFileName = document.getElementById('file').files[0].name; } function getDirectories() { let arrayOfThisRow = []; let inputFile = document.querySelector('input[type="file"]'); let uploadBtn = document.querySelector('input[type="submit"]'); inputFile.addEventListener("change", updateBtn); function updateBtn(e) { let tableTr = document.querySelectorAll("table#data tr"); for (let i = 0; i < tableTr.length; i++) { let tableData = tableTr[i]; let tableDataQuery = tableData.querySelector("td"); if (tableDataQuery) { arrayOfThisRow.push(tableDataQuery.textContent); } … -
half of the css styles don't work in django
I have configured everything to work with static in django(static_dirs, static_root,static_url, urls, etc..) but when im running server, styles from 'css/responsive.css' and 'css/jquery.mCustomScrollbar.min.css' are not working. The first two styles work by the way(from 'css/bootstrap.min.css' and 'css/style.css') {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- mobile metas --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <!-- site metas --> <title>evolve</title> <meta name="keywords" content=""> <meta name="description" content=""> <meta name="author" content=""> <!-- bootstrap css --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <!-- style css --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- Responsive--> <link rel="stylesheet" href="{% static 'css/responsive.css' %}"> <!-- fevicon --> <link rel="icon" href="images/fevicon.png" type="image/gif" /> <!-- Scrollbar Custom CSS --> <link rel="stylesheet" href="{% static 'css/jquery.mCustomScrollbar.min.css' %}"> <!-- Tweaks for older IEs--> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" media="screen"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]--> </head> <!-- body --> <body class="main-layout"> <!-- loader --> <div class="loader_bg"> <div class="loader"><img src="images/loading.gif" alt="#" /></div> </div> <!-- end loader --> <!-- header --> <header> <!-- header inner --> <div class="header"> <div class="container-fluid"> <div class="row"> <div class="col-xl-3 col-lg-3 col-md-3 col-sm-3 col logo_section"> <div class="full"> <div class="center-desk"> <div class="logo"> <a href="index.html"><img src="images/logo.png" alt="#" /></a> … -
useState doesn't work, it renders the previews photo of the product
WEBSITE GIF Hello, I am making ecommerce website using react.js and django DRF.. here is the issues.. 1. as you can see the gif, I tried to implement the function that changes the representative picture when I click on the small images using useState.. However, when I refresh the page, the representative picture disappears. when I click the other product, it shows the previews product that I clicked.. Here's my definition of the driving principle. In two actions, call the data from api and store it in each variable. use useState() to render the representative Picture, and when I click other images, useState is going to change the src url of the image.. and having trouble.. I know it is messy and long codes.. please help me.. thank you! django codes are here models.py class Product(models.Model): name = models.CharField(max_length=255, blank=False) category = models.ManyToManyField(ProductCategory) thumbnail_image = models.ImageField(null=True, blank=True) discription = models.TextField(null=False, blank=False) price = models.DecimalField(max_digits=20, decimal_places=2, null=False, blank=False) stock = models.IntegerField(default=0) tag = models.CharField(max_length=255, null=True, blank=True) date = models.DateTimeField(auto_now=True) enable = models.BooleanField(default=True) def image_tag(self): if self.thumbnail_image: return mark_safe('<img src="%s" style="width: 45px; height:45px;" />' % self.thumbnail_image.url) else: return 'No Image Found' image_tag.short_description = 'Image' def __str__(self): return self.name class ProductImages(models.Model): product = … -
from blog.views import (blog_post_detail_page), SyntaxError: invalid syntax
hi I was trying to use run server for my Django app that i have created in my directory that looks like this I was getting this error during runserver from blog.views import (blog_post_detail_page), SyntaxError: invalid syntax ` 1-try_django *src *blog init.py admin.py app.py models.py test.py views.py *tamplest about.html base.html blog_post_detail.html home.html title .txt *try_django.py init.py setting.py urls.py views.py wsgi.py init.py` #my views looks like: from django.shortcuts import render from .models import BlogPost def blog_post_detail_page(request): obj = BlogPost.objects.get(id=1) template_name = 'blog_post_detail.html' context = {"object": obj} return render(request, template_name, context) #blog models: from django.db import models # Create your models here. class BlogPost(models.Model): title = models.TextField() content = models.TextField(null=True, blank=True) #urls : from django.contrib import admin from django.urls import path,re_path from blog.views import (blog_post_detail_page), from .views import ( home_page,about_page,contact_page,example_page) urlpatterns = [ path('', home_page), path('blog',blog_post_detail_page,name='home'), path('page/',about_page), path('pages/',about_page), re_path(r'^pages?/$',about_page), re_path(r'^about/$', about_page), path('example/', example_page), path('contact/', contact_page), path('admin/', admin.site.urls),]