Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering multiple data in Django
I want to retrieve multiple value based on their data value below. Currently what I did is I've been using for loop below but it only retrieve one value and I want to update based on the looping result.It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance @login_required(login_url='log_permission') def archive_folder(request): if request.method == 'POST': data_id = request.POST.get('id') #single value only example we have: 6 data = gallery_photos.objects.filter(gallery_info_id = idd) # multiple value example we have 3 rows for sample in data : viewing= sample.photos # I want to retrieve those three rows based on their photos column value in database Person.objects.filter(path = viewing).update(path=None) return JsonResponse({'data': 'success'}) -
NameError at /HomeFeed/ name 'slug' is not defined
NameError at /HomeFeed/ name 'slug' is not defined Is there a way for me to define slug without changing my url? def home_feed_view(request, *args, **kwargs): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['blog_post'] = blog_post return render(request, "HomeFeed/snippets/home.html", context) path('', home_feed_view , name= "main"), class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) -
How can i add choice if some choice is entered in django?
problem_choice = ( ("ford", 'Ford'), ('lambroghini', 'Lambroghini'), ) model_lamb = ('AVENTADOR.', 'AVENTADOR S.', 'AVENTADOR S ROADSTER.', 'AVENTADOR SVJ') model_ford = ('t', 'b', 'd') problem_name = models.CharField(max_length=10, choices=problem_choice, default='Ford') # if some choice is taken use that and make another choice in database I want to have Lambroghini model come out in another choice fields, If lambroghini is choosen and so for ford. Is there any way to do this inside django models? Thank you -
Function in Django model not updating and saving corresponding field
Trying to set-up a function inside the model below to count the length of an ArrayField whenever the instance is updated. The function def total_stocks_calc() doesn't update the model, it's useless. class Bucket(models.Model): stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True, blank=True) objects = models.Manager() def total_stocks_calc(self): self.stock_count = len(Bucket.objects.get(self.id).stock_count) self.save() I'm not getting any errors as well, however this works in django shell: len(Bucket.objects.get(id=1).stock_count), I get the corresponding amount of items within the object. Would that be the best way to accomplish a Count or Length of total strings within the ArrayField known as stock_count? -
Trying to compare current time to expiration date and return true if within 7 days:
I am writing a Pantry Inventory app for a school project with a Django backend, a DjangoRest API and a Vue2 frontend. I am trying to discern if an item is within one week of the expiration date tied to each of the items, and change expiring_soon to true if it is. My model in Django takes the expiration date through a DateTimeField that is serialized as such: class PantrySerializer(serializers.ModelSerializer): owner_detail = NestedUserSerializer(read_only=True, source='owner') expiration_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = models.PantryItem fields = ( 'id', 'item_name', 'create_date', 'expiration_date', 'owner', 'owner_detail', 'getting_low', 'tag', 'category', 'quantity', 'to_grocery', 'slug', 'amount_type', 'expiring_soon', 'brand', ) After browsing some related questions I've tried this as a Vue method in my root app. I call it in the created section.: getExpiry: function() { var one_day=1000*60*60*24; var currentTime = new Date() for (let i = 0; i < this.pantryItems.length; i++) var exdate = this.pantryItems[i].expiration_date; var diff = Math.ceil((exdate.getTime() - currentTime.getTime())/one_day); if (diff <= 7) { this.pantryItems[i].expiring_soon = true updateItem() } }, gettingLow: function(item) { item.getting_low = true } It gives me this error: VM22198 vue.js:634 [Vue warn]: Error in created hook: "TypeError: Cannot read property 'getTime' of undefined" (found in <Root>) warn @ VM22198 vue.js:634 logError @ … -
Django Question - Should i start a new project in the same virtual environment?
Django newbie here. I have an existing Django virtual environment that was setup as part of a tutorial, using Django 2.2. and Vagrant + Virtual Box on my laptop. There was 1 project created for the tutorial above. I will now be starting another Django tutorial, wherein I will be creating a few more projects. WHat is the best way to go about this? Should I create a new virtual environment for tutorial #2? Or use the existing environment, that was setup for tutorial #1? FYI - tutorial #2 uses Django 1.11 Thanks a lot! -
Can't get the data from HTML page by using request.GET.get
I need a simple search form in my Django app. The code is: in HTML file: <html> <body> <h2><a href="/tube">Hypertube</a></h2> <a target="_blank" href="/login/"> Log In</a> <p><form action="tube/" method="GET"> <input name="q" placeholder="Search..."> <input type="submit" value="search"> </form></p> <p><a href="/tube/tag= {{ da_tag }}/">{{ da_tag }}</a></p> <p> {{ len }} videos</p> {% for video in videos %} <div><a href="/tube/watch/{{ video.id }}/">{{ video.video.title }}</a></div> {% endfor %} <p><a target="_blank" href="/tube/upload/">Upload video</a></p> </body> </html> in views.py: class MainPageView(ListView): def get(self, request): query = request.GET.get('q') if query is not None: videos = Video.objects.filter(Q(title__icontains=query)) else: videos = VideoTag.objects.all() return render(request, 'index.html', context={'videos': videos, 'len': len(videos)}) The problem is that 'query' is None. How can I fix this? -
Django request.user.id 'matching query does not exist' error in webhook
I'm building a Stripe webhook in my Django app that, after the payment is confirmed, retrieves the current user's ID in the database and uses it to assign a subscription to the team that that user is assigned to. There are a few database tables that are important to note here: User (a custom user model for my app) Team (an organization-style model table that contains team names and a ManyToManyField with the User table "through" to the Membership table) Membership (the "through" table that contains foreign keys to the user, team, and Stripe customer tables) StripeCustomer (the Stripe customer information table that has a OneToOneField with the Team table, and stores the Stripe customer ID and subscription ID) After the payment is confirmed in the Stripe webhook, I want to pull the current user's ID from the User table using request.user.id and use it with the Membership table to get an object containing the current user's team (so that the Stripe subscription can be assigned to that team). The problem is that, when I use request.user.id within Membership.objects.get(user_id=request.user.id), I receive an error in the console stating that the "Membership matching query does not exist." However, if I just print … -
Django error only when deployed on PythonAnywhere: "No category matches the give query"
I have deployed My Django website via PythonAnywhere.com and everything seems to be working other than my search bar which gives me the the following error even if the item does exist. You can reproduce the error by going to https://www.ultimatecards5.com/ and searching for anything in the search bar. Although, when I run my project locally and do the same exact search I get the desired result of "0 results found" or a found result if it exists. Below are the error on the live page and then the same function when ran locally: The error says raised by shops.views.allProductCat My shops views.py def allProdCat(request, c_slug=None): #used to show all products in that category c_page = None #for categories products_list = None if c_slug!=None: c_page = get_object_or_404(Category,slug=c_slug) products_list = Product.objects.filter(category=c_page,available=True) #filtering products according to category else: products_list = Product.objects.all().filter(available=True) ''' Paginator Code ''' paginator = Paginator(products_list,12) #limiting 6 products per category page try: page = int(request.GET.get('page','1')) #converting GET request to integer i.e page number 1 so we can store it in page variable except: page = 1 try: products = paginator.page(page) except (EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request,'shop/category.html',{'category':c_page,'products':products}) My Shops urls.py from django.urls import path from django.contrib import admin … -
Is the server running on host "db" and accepting TCP/IP connections on port 5432?
I have a Django project and a postgres database but I cannot dockerize that. Here is the docker-compose.yml : version: '3' services: database: image: postgres restart: always env_file: - database.env web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py createsu && python manage.py runserver 0.0.0.0:8000" volumes: volumes: - .:/code ports: - "8000:8000" depends_on: - database Here my Dockerfile : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ And my database.env : # database.env POSTGRES_USERNAME=admin POSTGRES_PASSWORD=pass POSTGRES_DBNAME=db POSTGRES_HOST=database POSTGRES_PORT=5432 PGUSER=admin PGPASSWORD=pass PGDATABASE=db PGHOST=database And here are the parameters from the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'admin', 'PASSWORD': 'pass', 'HOST': 'database', 'PORT': '5432', } } But I got that : django.db.utils.OperationalError: FATAL: password authentication failed for user "admin" Could you help me please ? Thank you very much ! I precise I created my database. -
Django load JSON data into model
I'm trying to load json data file and create Player class according to the json data. For models.py I have player class class Player(models.Model): pos = models.CharField(max_length=2, default="") name = models.CharField(max_length=30, default="") age = models.PositiveIntegerField() posRank = models.PositiveIntegerField() throwAtt = models.PositiveIntegerField() throwYd = models.PositiveIntegerField() throwTD = models.PositiveIntegerField() interception = models.PositiveIntegerField() rushAtt = models.PositiveIntegerField() rushYd = models.PositiveIntegerField() rushTD = models.PositiveIntegerField() rushAvgYd = models.FloatField() target = models.PositiveIntegerField() rec = models.PositiveIntegerField() recYd = models.PositiveIntegerField() recAvgYd = models.FloatField() recTD = models.PositiveIntegerField() totalTD = models.PositiveIntegerField() fumble = models.PositiveIntegerField() fpts = models.FloatField(null=True) ppr = models.FloatField() totGames = models.PositiveIntegerField() and for serializers.py I have player serializer written as below class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = ('name', 'pos', 'age', 'posRank', 'throwAtt', 'throwYds', 'throwTD', 'interception', 'rushAtt', 'rushYd', 'rushTD', 'rushAvgYd', 'target', 'rec', 'recYd', 'recAvgYd', 'recTD' 'totalTD', 'fumble', 'fpts', 'ppr', 'totGames') and inside views.py i have this class class PlayerView(generics.CreateAPIView): players = Player.objects.all() serializer = PlayerSerializer(players, many=True) def get(self, request): output = json.load('api/NewNFLdata.json') for player in output: newPlayer = Player(pos=player["FantPos"], name=player["Player"], age=player["Age"], posRank=player["PosRank"], throwAtt=player["Att"], throwYd=player["Yds"], throwTD=player["TD"], interception=player["Int"], rushAtt=player["Att.1"], rushYd=player["Yds.1"], rushTD=player["TD.1"], rushAvgYd=player["Y/A"], target=player["Tgt"], rec=player["Rec"], recYd=player["Yds.2"], recAvgYd=player["Y/R"], recTD=player["TD.2"], totalTD=player["TD.3"], fumble=player["Fmb"], fpts=player["FantPt"], ppr=player["PPR"], totGames=player["G"] ) newPlayer.save() return Response(serializer.data) I tried to do it by my own by looking up stack overflow … -
Graphene Django Image Field showing wrong path
I am trying to switch my axios queries to graphene-django but my images is mixed with both full path and server path: This is my schema: class ArticleType(DjangoObjectType): class Meta: model = Article fields = ("slug", "title", "excerpt", "content", "image") image = graphene.String() def resolve_image(self, info): """Resolve product image absolute path""" if self.image: self.image = info.context.build_absolute_uri(self.image) return self.image class Query(graphene.ObjectType): all_articles = graphene.List(ArticleType) def resolve_all_articles(self, info, **kwargs): return Article.objects.all() in graphiql the response is { "errors": [ { "message": "[Errno 2] No such file or directory: '/home/ytsejam/public_html/lockdown/yogavidya/media/http:/localhost:8000/graphql/5_135818877_742799629979350_7327381988945830866_o.jpg'", "locations": [ { "line": 6, "column": 5 } ], "path": [ "allArticles", 0, "image" ] }, ... ]} How can I fix my correct path ? Thanks -
How can I add a second dependent field to my current Django dependent drop down form?(Car Makes/Models/Years
Context I'm currently building a car dealership app and am struggling on a dependent search form. At the moment, it takes the users make selection and returns a list of models belonging to it that exist in the db. However now I am struggling to make a second dependent field where available years are provided based on the model chosen. Attempts Made The question text will already be very long with just the Ajax but essentially, I've tried creating a duplicate Ajax request,view and url with slightly different names and targeting the carmodel but all I got was no errors and no results. I've tried rendering two dicts from the one request which did actually get me the years to log in the console but I couldn't join the two dicts successfully nor could I work out how to render the years when I got them to log. I went over everything line and understand when/how/why it's targeting certain id's and creating new options for the form but I just can't get it to work when the model is chosen after the make. Code Here is a view of my models.py class CarMake(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name … -
How to load static files on heroku server?
I have successfully deployed my django project on heroku but my project is not looking as it looks on local server due to static files i guess. I am using django 3.1.4. And having issues with version control. here what its look on local : here what its look on server : settings.py: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] -
Django-import-export package post_save signal called twice
I am using the django-import-export package to import data from a model from the admin site. This model has a function for sending email that is executed with the post_save signal. The problem is that when the preview is generated (import confirmation) the function associated with the post_save is executed and then when I confirm the import, it is executed again, that is, the mail is sent twice. How to solve this problem? The following is the function with the @receiver decorator that uses the post_save signal @receiver(models.signals.post_save, sender=MiModel) def send_email(sender, instance, **kwargs): ..... server.sendmail(....) I am using Python==3.6.5, Django==3.0.5, django-import-export==2.5.0 -
Apache Django Internal Server Error (Ubuntu 18.04)
I have a Django wagtail application. I can run it in debug and I can run it on a django server but if I try to run it on my Ubuntu 18.04 server using Apache2 WSGI I get "Internal Server Error". Apache log: [Mon Jan 18 23:29:23.673557 2021] [mpm_event:notice] [pid 92324:tid 140613127453760] AH00491: caught SIGTERM, shutting down Exception ignored in: <function BaseEventLoop.__del__ at 0x7fe301c1fc10> Traceback (most recent call last): File "/usr/lib/python3.8/asyncio/base_events.py", line 654, in __del__ NameError: name 'ResourceWarning' is not defined Exception ignored in: <function Local.__del__ at 0x7fe301b95040> Traceback (most recent call last): File "/home/user/wow/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fe301b95040> Traceback (most recent call last): File "/home/user/wow/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fe301b95040> Traceback (most recent call last): File "/home/user/wow/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined [Mon Jan 18 23:29:24.194636 2021] [mpm_event:notice] [pid 92749:tid 139932982541376] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Mon Jan 18 23:29:24.194764 2021] [core:notice] [pid 92749:tid 139932982541376] AH00094: Command line: '/usr/sbin/apache2' [Mon Jan 18 23:29:31.468972 2021] [wsgi:error] [pid 92750:tid 139932932445952] WSGI without exception my wsgi … -
Django objects.get(): The QuerySet value for an exact lookup must be limited to one result using slicing
I'm trying to check if a user exists in the database based on email address, so I get the email and if that email exists, I want to return the username of that user alongside with some other data. I'm using objects.get() method to do so but I keep getting this error. Did some search on it, a couple of solutions were suggesting to do a filter and return the .first() object or instead of email=email, suggested to put email=email[0], but both of these approaches ended up giving me an empty array in response. Here's my Views.py: class CheckEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = CheckEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = Account.objects.filter(email=serializer.data['email']) if email.exists(): username = Account.objects.get(email=email) return Response({'is_member': True, 'username': username}) else: return Response({'is_member': False}) -
Django admin keeps loading the wrong template
Admin app keeps loading the wrong template "user/welcome.html". I've reinstalled django, confirmed that 'django.contrib.admin' is inside INSTALLED_APPS, switched 'APP_DIRS', inside TEMPLATES, to True and I've also checked the templates folder inside admin and confirmed that the correct index.html is there. If I delete user/welcome.html in order to throw an error the traceback is as follows: Request Method: GET Request URL: http://localhost:8000/admin Django Version: 3.1.5 Python Version: 3.8.5 Installed Applications: ['common_balance', 'users', 'social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\common_balance\templates\users\welcome.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\users\templates\users\welcome.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\contrib\admin\templates\users\welcome.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\contrib\auth\templates\users\welcome.html (Source does not exist) Traceback (most recent call last): File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\users\views.py", line 11, in welcome return render(request, "users/welcome.html") File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /admin … -
Join onto other table where there is no foreignkey relationship
I have one Django model with with "some_id" and many other models with "some_id" as primary key. class ModelA(models.Model): name = models.CharField(max_length=150) some_id = models.PositiveIntegerField() [...] # more fields class ModelB(models.Model): some_id = models.PositiveIntegerField(primary_key=True) [...] # more fields class ModelC(models.Model): some_id = models.PositiveIntegerField(primary_key=True) [...] # more fields How can I annotate a ModelA queryset with a boolean field if a row exists in ModelB/ModelC etc ------------------------------------------ | name | some_id | has_b | has_c | ----------------------------------------- | John | 1 | True | False | ------------------------------------------ Do I need to use ".extra()"? or some database expression I cant change the model/table to add the foreign key relationship. -
UNIQUE constraint failed: auth_user.username when trying to save the form
Whenever I try to register an account this error jumps out in the form.save() on the views.py code. I've tried some things but didn't work out. I don't know if it is because of verifiying problems or what. The problem is that I've tried many things to sort this out but can't find a definite solution. Thank you! views.py: from django.shortcuts import render from .scrapper import EmailCrawler from django.http import HttpResponse from celery import shared_task from multiprocessing import Process from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from asgiref.sync import sync_to_async from django.shortcuts import redirect from .forms import CreateUserForm from rest_framework.decorators import APIView from rest_framework.response import Response from leadfinderapp import serializers from django.contrib import messages def register(request): if request.user.is_authenticated: return redirect('login') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Account was created for' + user) return redirect('login') context = {'form':form} return render(request, 'leadfinderapp/register.html', context) models.py: from django.db import models from django.contrib.auth.forms import UserCreationForm from django import forms # Create your models here. class User(models.Model): first_name = models.CharField(max_length=40000) last_name = models.CharField(max_length=40000) email = models.EmailField(max_length=40000) password1 = models.CharField(max_length=40000) password2 = models.CharField(max_length=40000) class Emails(models.Model): name = models.CharField(max_length=40000) urls = models.URLField(max_length=200) emails = models.TextField() def __str__(self): return self.name forms.py: from … -
Is there a way to avoid CORS error while in production in NuxtJS?
I have been using NuxtJS locally alongside Django Rest Framework and there have been no issue. However, after deployment on Netlify I started getting CORS error - although, I have axios proxy set. I had to rerun npm run generate and run the generated file locally for which I get the same error. I later found out that proxy doesn't work with statically generated NuxtJS app. I have searched Google tirelessly but I can't seem to get a direct solution. I have to deploy this app on Netlify without having access to Nginx or Apache server. Please can anyone suggest a simple solution to avoid CORS error 405. The repository containing the code is located here -
Data from form doesn't save at database ( can't validate )
Always, whni I try to add some content with my post form I'l always have an validation error I don't correctly understand how to use checkbox validation All data print at console with csrf token, but can't save at db models.py class Film(models.Model): title = models.CharField('Название фильма', max_length=255) #slug = models.SlugField(unique=True, max_length=55) description = models.TextField('Описание фильма', null=True) main_image = models.ImageField('Постер', upload_to='images/film_poster') image1 = models.ImageField('Первое изображение', upload_to='images/') image2 = models.ImageField('Второе изображение', upload_to='images/') image3 = models.ImageField('Третее изображение', upload_to='images/') image4 = models.ImageField('Четвёртое изображение', upload_to='images/') image5 = models.ImageField('Пятое изображение', upload_to='images/') trailer_link = models.URLField('Ссылка на трейлер') two_d = models.BooleanField('2Д',default=False) three_d = models.BooleanField('3Д',default=False) i_max = models.BooleanField('I_MAX', default=False) duration = models.CharField('Длительность фильма', max_length=55) first_night = models.DateField(verbose_name='Дата премьеры', null=True) There is my view's: views.py def film_page(request): error = '' if request.method == 'POST': form = FilmForm(request.POST) if form.is_valid(): form.save() return redirect('film_list') else: error = 'Что-то пошло не так' form = FilmForm() data = { 'form': form, 'error': error, } return render(request, 'adminLte/film/film_page.html', data) That's mine Html-file {% extends 'adminLte/base.html' %} {% block film %} <li class="nav-item"> <a href="{% url 'film_list' %}" class="nav-link active"> <i class="fas fa-film"></i> <p> Фильмы </p> </a> </li> {% endblock %} {% block content_title %} <h1 class="m-0">Форма добавления фильма</h1> {% endblock %} {% block main_content … -
How do I iterate dictionary with lists as values in Django template?
I have a dictionary with lists as values (truncated to give you an example): imageFiles {'R01': ['02secparking27.jpg', '10-2017-ff-detail-1200x627.jpg', '1200x820.jpg', '12539233_web1_180704-VMS-parking-lot.jpg', '16.12.01-519196006.jpg',], 'R02': ['asdasd.jpg','12131asad.jpg','asdasdasd.jpg']} In the template, I am trying to access the image names by iterating but I am getting no values. {% for keys,values in imageFiles %} {% for x in values %} <p> {{X}} </p> {% endfor %} {% endfor %} getting error "Need 2 values to unpack in for loop; got 9." I also tried imageFiles.items as suggested in other posts and it doesn't seem to work. What am I doing wrong? Wracking my brain here. -
How to correctly write the location of the template file in settings (Django)
Issue: I cannot find the reason why the app cannot find the HTML page. I believe it`s in the way how the settings templates are coded. Possible solutions: I have tried to change the Directory of the templates files, but it didn`t change anything. views.py from django.shortcuts import render from .models import Chantier, Backup, Asset, Note, Issue from django.contrib.auth.decorators import login_required @login_required(login_url="/login/") def index_site(request): return render(request, 'chantiers/index_site.html') urls.py from django.conf.urls import include, url from django.urls import path from . import views from django.contrib import admin from django.conf import settings admin.autodiscover() from django.conf.urls.static import static app_name = 'chantiers' urlpatterns = [ url(r'^index_site$', views.index_site, name='index_site'), ] settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).parent CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url # add this urlpatterns = [ path('admin/', admin.site.urls), # Django admin route path("", include("authentication.urls")), # Auth routes - login / register path("", include("app.urls")), path("sites/", include("chantiers.urls")), ] In the core/templates folder, I am creating a … -
Django Add to a field in Models.py
I have this code in models.py like so: class Post(models.Model): likes = models.PositiveIntegerField(default=0) I also have this template called home.html: {% extends "blog/base.html" %} <p>Like!</p> <!-- onclick of p above, add one to likes at models.py --!> {% endblock content %} So how would I actually implement this? I want, on the click of the paragraph, to add one to the likes field in the post model. I am beginner.