Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on different user login render different html pages
On logging one user with sales role he should be shown sales html page and if marketing person logs in then the page for marketing will be shown. In same way I will be having 30 different logins and so 30 different pages. -
Django 3 - Align Radio Button Horizontally
I have created user signup form in Django3. In the form I want to have a radio button based choice selection for the user. The forms.py looks like class SignUpForm(UserCreationForm): .... subscription_choice = ( ('yearly', 'Yearly'),('monthly', 'Monthly'), ) subscription_type = forms.TypedChoiceField( choices = subscription_choice, widget = forms.RadioSelect(attrs={ "style": "display: inline-block" }) The model file looks like. class SignUp(AbstractBaseUser): subscription_choice = ( ('yearly', 'Yearly'),('monthly', 'Monthly'), ) email = models.EmailField(unique=True) firstname = models.CharField(max_length=150) lastname = models.CharField(max_length=150) phonenumber = models.CharField(max_length=14,primary_key=True) referral_code = models.CharField(max_length=150, default="None") subscription_type = models.CharField(max_length=10, default="monthly", choices=subscription_choice) .... I have tried some css tricks as suggested in some answers on SO but no luck. The result I am getting is vertical aligned (messy) radio buttons. Need some help. -
Edit ManyToMany Inline fields with self relationship in Django Admin change form
How can I get a model's fields to be editable in the Inline in a ManyToMany relationship when the relationship is with itself? class MyModel(models.Model): children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False ) class MyModelChildAdminInline(admin.TabularInline): """Inline for the intermediate table""" model = MyModel.children.through # Number of child-forms shown at the bottom of the Profile detail view extra = 0 fk_name = 'from_mymodel' raw_id_fields = ("to_mymodel",) fields = ('to_mymodel', 'field1', 'field2', 'field3', ) readonly_fields = ('field1', 'field2', 'field3',) def field1(self, obj): return obj.to_mymodel.field1 def field2(self, obj): return obj.to_mymodel.field3 def field3(self, obj): return obj.to_mymodel.field2 @admin.register(MyModel) class MyModelAdmin(VersionAdmin): inlines = (MyModelChildAdminInline, ) exclude = ('children', ) -
Django Cassandra Engine( Multiple keyspaces)
I have a django project in which I am using cassandra database, there are multiple cassandra keyspaces available in that project. I am basically using an id as an identifier to detect which keyspace the app should be using for different users. I tried to implement this approach through django multiple database router methods such as db_for_read() and db_for_write() but was gwtting an exception when I tried so: cassandra.cqlengine.CQLEngineException: Model keyspace is not set and no default is available. Set model keyspace or setup connection before attempting to generate a query. The code in my settings file is: DATABASES = { 'interview_service_1': {'ENGINE': 'django_cassandra_engine', 'NAME': 'interview_service_2', 'HOST': 'cassandra.cassandra', 'PORT': 9042, 'OPTIONS': {'replication': {'strategy_class': 'SimpleStrategy', 'replication_factor': 1}, 'connection': {'retry_connect': True, 'lazy_connect': True, 'protocol_version': 3}}}, 'interview_service_2': {'ENGINE': 'django_cassandra_engine', 'NAME': 'interview_service_3', 'HOST': 'cassandra.cassandra', 'PORT': 9042, 'OPTIONS': {'replication': {'strategy_class': 'SimpleStrategy', 'replication_factor': 1}, 'connection': {'retry_connect': True, 'lazy_connect': True, 'protocol_version': 3}}}, 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'assessment_service', 'HOST': 'cassandra.cassandra', 'PORT': 9042, 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 } }, 'connection': { 'retry_connect': True, 'lazy_connect': True, 'protocol_version': 3, 'load_balancing_policy': DCAwareRoundRobinPolicy(local_dc='datacenter1') } } } interview_service_1 and interview_service_2 are the keyspaces names which I am returning from my database router file. Is there a way through which … -
DJANGO: How can I duplicate attribute from other class?
I want to duplicate an attribute from other class. class PedidoCliente(Pedido): total_pagado = models.DecimalField(blank=True, max_digits=10, decimal_places=2,default = 0,verbose_name="Pagado $") # default 0 para el error for += int barril_encargado = models.DecimalField(blank=True, default=0, max_digits=10, decimal_places=2,verbose_name="Barr. entregados") fecha_entrega = models.DateField(verbose_name="Fecha Entrega") class DetallePedidoCliente(DetallePedido): comments = models.CharField(max_length=300, verbose_name="Comentarios") precio_venta = models.DecimalField(max_digits=16, decimal_places=2, default = 0) pedido = models.ForeignKey(PedidoCliente,on_delete=models.CASCADE) fecha_entrega = the same from PedidoCliente I'm new at OPP so sorry if it's a silly question. Thanks! -
Django - Creating a row in onther table before creating user
I have user, userprofile and company tables. I want to create a record in company table and then assign the id of the newly created company in the userprofile foreign key before creating the user. I think it can be done using pre_save signal but I am unable to figure how. Please help. -
How to access Django relations outside the django?
I have small project in django in which I need to access Django relations outside the Django project. I would like to get querySet of all logs related to player via command like player.logs.all(). Getting querySet through player.logs.all() works when I do it in django shell and when I do it in views.py, but it does not work from external file even when I set up django connection properly models.py class Log(models.Model): name = models.CharField(max_length=50) link = models.PositiveIntegerField(default=0, primary_key=True) class Meta: app_label = 'stats' def __str__(self): return self.name class Player(models.Model): logs = models.ManyToManyField(Log) name = models.TextField() steamid3 = models.CharField(max_length=20, primary_key=True) class Meta: app_label = 'stats' def __str__(self): return self.steamid3 external test.py import django from django.conf import settings settings.configure( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, 'NAME': 'stats', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } ) django.setup() from stats.models import * l = Log.objects.all() #Works players = Player.objects.all() #Works player = Player.objects.get(pk='[U:1:92778910]') #Works print(player.logs.all()) #Does not work Error I get after running test.py django.core.exceptions.FieldError: Cannot resolve keyword 'player' into field. Choices are: link, name -
Django cannot find "/media/image.png" when placed in root folder
I have the following structure my app/ |_my_app/ | |_templates/ |_static/ |_media/ |_utils/ |_main.py |_manage.py |_.gitignore and having the in template.html <img src="./media/image.png"> then it casts a GET 404 error Cannot find /media/image.png. I have also tried relative path (relative to the template i.e <img src="../../media/image.png">. Moving the media folder into static (and including {% load static %} I can do <img src="{% static '/media/image.png'"> without any issues. Why can't it find ./media/image.png in the first part? Is there a way to do the "static" trick but with another tag (say media) e.g <img src="{% media 'image.png' "> to avoid absolute paths? -
Django Google App Engine: 502 Bad Gateway, already installed package not recognized
I'm deploying Django in Google App Engine. I get 502 Bad Gateway and in the log I get the following error: 2021-03-08 12:08:18 default[20210308t130512] Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/srv/main.py", line 1, in <module> from django_project.wsgi import application File "/srv/django_project/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in … -
Geodjango map is not displaying in the template
Pointfield is used for location. The model is not displaying the geodjango map in the template. class ProfileCompletion(models.Model): fullname = models.CharField(max_length=120,default=None) address = models.CharField(max_length=800,default=None) location = models.PointField(default=Point(0, 0),geography=True) category = models.ForeignKey(Category,on_delete=models.SET_NULL, blank=True, null=True) coverpicture = models.ImageField(upload_to='images',default=None) departments = models.ManyToManyField(Department, related_name='departments',blank=True) services = models.ManyToManyField(Service, related_name='services',blank=True) bed_numbers = models.CharField(max_length=120,default=20) # latitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True) # longitude =models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True) user=models.OneToOneField(CustomUser,on_delete=models.CASCADE) def save(self, *args, **kwargs): self.latitude = self.location.y self.longitude = self.location.x super(ProfileCompletion, self).save(*args, **kwargs) def __str__(self): return self.fullname -
'RelatedManager' object has no attribute Error
MODELS.PY: class DosyaBilgileri(models.Model): sahisAdi = models.CharField(max_length=30, verbose_name='Şahıs Adı') slug = AutoSlugField(populate_from='sahisAdi', unique=True) class MateryalEkle(models.Model): dosyaBilgileriBaglanti = models.ForeignKey(DosyaBilgileri, on_delete=models.CASCADE, related_name='hangiDosya') marka= models.CharField(max_length=25, verbose_name='MATERYAL MARKA') slug = AutoSlugField(populate_from='materyalMarka', unique=True) class IslemYapModel(models.Model): materyalEkleBaglanti = models.ForeignKey(MateryalEkle, on_delete=models.CASCADE, related_name='hangiMateryal') kopya = models.CharField(max_length=25) slug = AutoSlugField(populate_from='imajTuru', unique=True) VIEWS.PY: def tutanaklar(request): dosyaBilgileriD = DosyaBilgileri.objects.all().order_by('-id') return render(request, 'delil/tutanaklar.html', {'dosyaBilgileriD':dosyaBilgileriD}) def paket(request, slug): DosyaBilgileriModelTumVeriler = get_object_or_404(DosyaBilgileri, slug=slug) buDosyayaAitMateryaller = DosyaBilgileriModelTumVeriler.hangiMateryal.all() return render(request, 'delil/paket.html', { 'DosyaBilgileriModelTumVeriler':DosyaBilgileriModelTumVeriler,'buDosyayaAitMateryaller':buDosyayaAitMateryaller }) def diger(request, slug): DosyaBilgileriModelTumVeriler = get_object_or_404(DosyaBilgileri, slug=slug) buDosyayaAitMateryaller = DosyaBilgileriModelTumVeriler.hangiDosya.hangiMateryal.all() return render(request, 'delil/diger.html', { 'DosyaBilgileriModelTumVeriler':DosyaBilgileriModelTumVeriler,'buDosyayaAitMateryaller':buDosyayaAitMateryaller }) URLS.PY urlpatterns = [ path('tutanaklar', views.tutanaklar, name='tutanaklar'), path('paket/<slug:slug>', views.paket, name='paket'), path('diger/<slug:slug>', views.diger, name='diger'), ] TUTANAKLAR.HTML {% if dosyaBilgileriD %} {% for tekil in dosyaBilgileriD %} <tr> <td class="align-middle ufo60"><i class="fas fa-signature mr-1 text-primary"></i>{{tekil.sahisAdi}}</td> <td><a href="{% url 'paket' slug=tekil.slug %} " type="button" class="btn btn-primary mt-3" >PEKET</a></td> <td><a href="{% url 'diger' slug=tekil.slug %} " type="button" class="btn btn-primary mt-3" >DIGER</a></td> </tr> {% endfor %} {% endif %} The link {% url 'package' slug = singular.slug%} works, but the link {% url 'other' slug = singular.slug%} does not work. and I get this error: 'RelatedManager' object has no attribute 'whichMaterial' I will be glad if you help. -
I am new to Celery and Django,How can i store all results from the celery response in a single variable
here im calling the celery task, and after compleating every task i want to store the results in a single variable views.py urls=["https//:.....com,https//:.....com"] for i in urls: r=process.delay(urls) tasks.py @app.task def process(url): r = requests.get(url, allow_redirects=True) return r -
how to update/change the interval of task in celery beat django during run tim?
I want to know how to change the interval of a task in django celery beat during run time? For instance, I have the code below: app.conf.beat_schedule = { 'every_5_seconds': { 'task': 'my_app.tasks.cpu', 'schedule': 5, } } Now, I start celery beat using redis as broker: Celery -A my_project worker -l info Celery -A my_project beat -l info The question is, how can I change/update the schedule to a new one (20 seconds instead of 5) while it's rinning and vise versa. Thanks -
something wrong when i open the localhost
AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\Users\Dell\Desktop\ecommerce\env\lib\site-packages\django\middleware\clickjacking.py, line 26, in process_response Python Executable: C:\Users\Dell\Desktop\ecommerce\env\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\Users\Dell\Desktop\ecommerce', 'c:\users\dell\appdata\local\programs\python\python39\python39.zip', 'c:\users\dell\appdata\local\programs\python\python39\DLLs', 'c:\users\dell\appdata\local\programs\python\python39\lib', 'c:\users\dell\appdata\local\programs\python\python39', 'C:\Users\Dell\Desktop\ecommerce\env', 'C:\Users\Dell\Desktop\ecommerce\env\lib\site-packages'] Server time: Mon, 08 Mar 2021 11:33:27 +0000 -
Automatic Refresh after the function is called
I am doing a Paypal integration to my web application. The code works, but I need to have a function that will automatically refresh the page after the payment. Where can I put the function for Auto-refresh the page and what would be the code? Apologies as I am new to JavaScript. Additional info: The main language that I use is Python/Django Framework, but to integrate Paypal payment, I need to use this code from Sandbox. <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=PHP"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); var total = '{{object.get_total}}' var orderID = '{{object.id}}' function completeOrder(){ var url = "{% url 'complete' %}" fetch(url, { method: 'POST', headers:{ 'Content-type' : "application/json", 'X-CSRFToken': csrftoken, }, body: JSON.stringify({'orderID':orderID, 'total':total}) }) } // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'pill', label: 'pay', height: 40 }, … -
How to use a boolean filter in django with toggle switch
I am very new in django and python. I am creating a small web app where i need to use django filters to pop up the users who are active using toggle switch when the toggle is on. If toggle switch is off then it shud list the inactive users in the User model How to implement this. I dont know how to do this pls help -
'ManyToManyDescriptor' object is not iterable
i have this in views: def watchlist(request): watchlist_list = User.watchlist context = { "watchlist_list": watchlist_list } and this in models: from django.contrib.auth.models import AbstractUser from django.db import models class all_auctions(models.Model): title = models.CharField(max_length= 14) description = models.TextField(blank=False) photo_url = models.CharField(max_length= 500) class User(AbstractUser): watchlist = models.ManyToManyField(all_auctions, blank = True, related_name = "watchlist") class bids(models.Model): bid = models.DecimalField(decimal_places = 2, max_digits = 100000) class comments(models.Model): comment = models.TextField(blank=False) and trying to do this in my watchlist.html (view all the auctions some1 has in their watchlist): {% extends "auctions/layout.html" %} {% block body %} <h2>Watchlisted Listings</h2> {% for watchlisted in watchlist_list %} <div> <div style = "width: 1400px; border: 1px solid grey;padding: 10px; margin: 10px; display:inline-block;" class = auction_class> <img src="{{watchlisted.photo_url}}" alt="no image"> <div style = "display:inline-block;"> <h2>{{watchlisted.title}}</h2> {{watchlisted.description}} </div> </div> </div> {% endfor %} {% endblock %} and as title suggests get error: 'ManyToManyDescriptor' object is not iterable. If i cant do it like this dont be mean and just say that i cant (because im sick of this people) but say how else to do this. And yes i did research. -
Django Query group_by datetime contains duplicate data of dates
Hi I've been trying to debug what's wrong with my Django query but I still couldn't figure it out. I have a model called 'Ticket', and it has a field called 'created', which is a datetime field. I am trying return an array of objects containing the count of tickets for each unique day (yyyy-mm-dd) within a given date range (from and to), but I get 1 duplicate date which is weird. Please see results below and my code. The date "2021-02-08" has 1 duplicate while others are all correct. When I checked the database the count for "2021-02-08" should only be 20, and the rest should be on "2021-02-09". Data returned in JSON: "activation_chart_data": [ { "date": "2021-02-08", "count": 20 }, { "date": "2021-02-08", "count": 31 }, { "date": "2021-02-09", "count": 32 }, { "date": "2021-02-11", "count": 15 }, { "date": "2021-02-12", "count": 51 }, { "date": "2021-02-15", "count": 1 }, { "date": "2021-02-16", "count": 4 }, { "date": "2021-02-18", "count": 15 }, { "date": "2021-02-23", "count": 5 } ] Django Query: Ticket.objects.filter(Q(created__gte=from_date) & Q( created__lte=end_date) & Q(type__slug='activation-code')).extra(select={'date': 'date(shop_ticket.created)'}).order_by('created__date').values('date').annotate(count=Count('created')) Raw Postgre SQL Query being executed: SELECT (date(shop_ticket.created)) AS "date", COUNT("shop_ticket"."created") AS "count" FROM "shop_ticket" INNER JOIN "shop_tickettype" ON ("shop_ticket"."type_id" … -
Why is the csfr exempt decorator not working?
I am trying to send a 'POST' request from AJAX with fetch to a Django view with a @csfr_exemptdecorator and I still get a 403 Forbidden (CSRF token missing or incorrect.): /profile/follow error. Can someone explain why? (Newbie here). This is the .js: function follow_user(user, follower, action) { fetch(`follow`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ user: user, follower: follower, action: action }) }) .then(response => response.json()) .then(data => { document.querySelector("#followers-count").innerHTML = `Followers: ${data.followers}` }); console.log(console.log(`Schiscia: ${follower} ${action} ${user} ${data.followers}`)); and the view is: @csrf_exempt def follow(request): if request.method == "POST": user = request.POST.get('user') follower = request.POST.get('follow') action = request.POST.get('action') target = User.objects.get(username=user) sourceusr = User.objects.get(username=follower) if action == 'follow': target.followers.append(sourceusr) sourceusr.following.append(target) return JsonResponse({'Following': target.following}, safe=False, status=201) -
'user' is not a registered namespace error in DJANGO
in my main project's urls.py : from django.contrib import admin from django.urls import path from .settings.base import APP_NAME from django.conf.urls import url,include from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi urlpatterns = [ url(r'^api/user/', include('user.urls', namespace="user")), ] in user app's urls.py : from django.conf import settings from django.urls import path from . import views app_name="user" urlpatterns = [ path('password_reset/', views.ResetPasswordRequestToken.as_view(), name="reset_password_request") ] Route is working on local very well. But on the production, route page is opening and I post email via api page, and then I get error below: How can I solve it ? -
sending post data from react to django rest showing 415 error
when i change fetch url from django url to webhook(dummy api key) it works but when comes to localhost it fails views class postlist(APIView): def get(self,request): mod = post.objects.all() serializer = postSerializers(mod,many=True) return Response(serializer.data) def post(self,request): pass class create(CreateAPIView): queryset = post.objects.all() serializer_class = postSerializers react component async postdata(){ try{ let result = await fetch('http://127.0.0.1:8000/api/create',{ method:'post', mode: 'no-cors', headers: { 'Accept': 'application/json', 'Content-type':'application/json' }, body: JSON.stringify({ title: 'workig hohoh', body: 'yes' }) }); console.log('Result: ' + result) } catch(e){ console.log(e) } } render() { <div> <button onClick={ () => this.postdata() }>post</button> </div> } } when posting it is saying 415 unsopperted media type , dont know whats happening? -
How can I populate my database with data for testing purpose
I am making a supplier management system for my project. I need a way such that I can populate my databse with about 50 different suppliers and also 1000 products so that it willl look good and a lot of tests will be able to be carried out on it. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) image = models.ImageField(upload_to='images/users', default='images/users/profile-pixs.png') USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_supplier == True: return User.get_email(self.user) + " - is_supplier" else: return User.get_email(self.user) + " - is_admin" class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() description = models.TextField() quantity = models.PositiveIntegerField() image = models.ImageField(upload_to='images/products', default='images/products/default-product.jpeg', blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True) country = CountryField(blank_label='(select country)') -
Why my django doesen't show up renders of models from tempates?
I'm trying to create a Django project site with movies. In templates, I specified the for loop and models.atribute, but they don't show up when I render the page. I created the models via django shell and I will attach the screenshot below. What is my mistake ? enter image description here index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1> This is the header</h1> {% for movie in movies %} <h1>Test</h1> <h1>{{ movie.title }}</h1> <p>{{ movie.description }}</p> <p>{{ movie.created_date }}</p> {% endfor %} <h2>But this is not header</h2> </body> </html> Views.py def Page(request): movies = Movie.objects.all() context = {'movie': movies} return render(request, 'index.html', context) Models.py class Movie(models.Model): movieid = models.IntegerField(null=True) title = models.CharField(max_length=30, blank=False, null=False) created_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=150,null=True) description = models.TextField(blank=True, null=True) poster = models.ImageField(upload_to="../MovieApp/movies/static/img/", default='../img/default-movie.png') class Meta: ordering = ["-created_date"] def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title -
Deploying Django on Google App Engine ==> ERROR: (gcloud.app.deploy) NOT_FOUND: Unable to retrieve P4SA(...)
I'm trying to deploy a Django application on Google App Engine. I followed the instructions given here. The only problem is that when I execute the command gcloud app deploy I than get the error: ERROR: (gcloud.app.deploy) NOT_FOUND: Unable to retrieve P4SA: [service-290226755412@gcp-gae-service.iam.gserviceaccount.com] from GAIA. Could be GAIA propagation delay or request from deleted apps. I didn't find anything online and can't get through. Thanks in advance! -
Chnage Dajngo Form filed choices when other filed value change
class mStockForm(forms.ModelForm): mStock_product = forms.ModelChoiceField( queryset=mProduct.objects.filter(), label='Select Milk Product', help_text="Choose from the list of milk products", required=True, ) # Want to access value here print(mStock_product.mProduct_id)#<-- want to access value here How to access values of form filed in form class of django The model of mProduct is : > class mProductUnit(models.Model): mProductUnit_id = models.AutoField(primary_key=True) mProductUnit_name = models.CharField(max_length=10) def __str__(self): return self.mProductUnit_name