Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a TypeError while trying to make a unique page in Django
I'm making a picture gallery web-app. I want to make some of displayed photos to belong to a specific collection. Each collection is supposed to have its own page that displays all of the pictures that belong to it. The name of each unique page is supposed to be photo_collection model, which I added to the class Image in models.py. But for some reason, I get TypeError at /projects/sample_collection_name/ - photo_collection() got an unexpected keyword argument 'photo_collection' No idea what's causing this error. I tried renaming the photo_collection function (it has the same name as my model), but it didn't work. models.py class Image(models.Model): title = models.CharField(max_length=300) image = models.ImageField(null=True, blank=True, upload_to='images/') pub_date = models.DateTimeField('Date published', default=timezone.now) photo_collection = models.CharField('Photo collection', max_length=250, null=True, blank=True) views.py def photo_collection(request): image = Image.objects.all() return render (request, 'photo_app/collection.html', context={'image': image}) urls.py urlpatterns = [ #some other patterns here path('projects/<str:photo_collection>/', views.photo_collection, name='photo_collection'), ] gallery.html {% if i.photo_collection != Null %} <a href="{% url 'photo_collection' i.photo_collection %}">{{i.photo_collection}}</a> {% endif %} -
Django template language if tag not working
I have a django template with an update form, for an invoices application. I want to allow to update the record after it was saved. One of the model fields is manager which is a foreign key: class Invoice(models.Model): manager = models.ForeignKey(User, on_delete=models.CASCADE,null=True ,blank=True) The problem is that I don't to display the manager's user id, but his/her first name, so I want to populate the select tag with all manager's first name. I have tried this: <select id="id_manager" name="manager"> {% for manager in managers %} {{ manager }} || {{ initial_manager }} {% if manager == initial_manager %} <option value="{{ manager.user.id }}" selected>{{ manager.user.first_name }}</option> {% else %} <option value="{{ manager.user.id }}">{{ manager.user.first_name }}</option> {% endif %} {% endfor %} </select> This is the views.py part: managers = Profile.objects.filter(Q(role = 'manager') | Q(role = 'cfo') | Q(role = 'ceo') | Q(role = 'sec')) projects = Project.objects.all() form = InvoiceForm(instance = invoice) initial_manager = invoice.manager return render(request, "invoice/update.html", {'form': form, 'managers':managers, 'projects':projects, 'initial_manager':initial_manager}) I have added this to see the values of the variables: {{ manager }} || {{ initial_manager }} and I see for example " 102 || 102 ", which means that they are equal but the if … -
Django won't stop throwing error even though I have removed the problem code [closed]
I replaced this line of code... customer.sources.create(source=token) with customer = stripe.Customer.create_source(userprofile.stripe_customer_id, source=token) in my django project. But the django won't stop throwing error stripe error -
What's a reverse foreignkey and a normal foreignkey
This a question from a Django noob, my question goes thus; What is the difference between a normal foreignkey and a reverse relation and what is the difference. I always thought; method 1 class State(models.Model): name = models.CharField() class Country(models.Model): name = models.CharField() state = models.ForeignKey(State) # normal foreignkey method 2 class Country(models.Model): name = models.CharField() class State(models.Model): name = models.ForeignKey(Country) # reverse relation What is the main difference and what is the benefit, when to use it and how to use it especially if I want to use reverse relation for example; create multiple instance of state in a django form. -
Can help to resolve this issue please? [closed]
enter image description here I upgraded Ubuntu Version, and with that python also upgraded. But my project was running in a lower version, I set a lower python version, and I tried everything but still facing this issue. Help me to resolve this issue. Thank you soo much in advance. -
Deploying Django Project but using Google Cloud SQL
I'm trying to deploy a todo-list django app (https://gitlab.com/learning-python8/django-project) in google app engine I have this error message: ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: could not resolve source: googleapi: Error 403: 1026004585917@cloudbuild.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object., forbidden Now the project is a way for me to study app deployment in GCP. The project is using an sqlite database for user along with it's todo data. If I understand the error right, It asks me to create a Google Cloud SQL. Would that be the correct process? I will be studying SQL to use online database for this project. -
FieldError: Cannot resolve keyword 'get_str' into field while using @property method in values_list() in a QuerySet
I have a model named Invitation, where I have created a property method which returns the value returned by __str__() method, like below: class Invitation(models.Model): @property def get_str(self): return self.__str__() Now, I am trying to use this property method in QuerySet's values_list() method as below: Invitation.objects.values_list("pk", "get_str") But I am getting following error: Cannot resolve keyword 'get_str' into field. Choices are: accepted_at, created_at, created_by, created_by_id, expiration_date, id, invited_to, invitee_first_name, invitee_last_name, is_canceled, secret, sent_to Full Traceback of error is: Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py, line 2107, in add_fields join_info = self.setup_joins( … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py, line 1773, in setup_joins path, final_field, targets, rest = self.names_to_path( … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py, line 1677, in names_to_path raise FieldError( … Local vars During handling of the above exception (Cannot resolve keyword 'get_str' into field. Choices are: accepted_at, created_at, created_by, created_by_id, expiration_date, id, invited_to, invitee_first_name, invitee_last_name, is_canceled, secret, sent_to), another exception occurred: /app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/mixins.py, line 73, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py, line 119, in dispatch … -
How shoud I fix ERROR with pip install psycopg2==2.7.*?
I am trying to put my app that I created on server www using heroku. But when I put to my terminal on Ubuntu pip install psycopg2==2.7.*, I get this error: ERROR: Command errored out with exit status 1: command: /home/marcin/Python/learning_log/ll_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-c67buptz/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-c67buptz/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-c67buptz/psycopg2/pip-egg-info cwd: /tmp/pip-install-c67buptz/psycopg2/ Complete output (28 lines): running egg_info creating /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info writing /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/SOURCES.txt' /home/marcin/Python/learning_log/ll_env/lib/python3.8/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) /home/marcin/Python/learning_log/ll_env/lib/python3.8/site-packages/setuptools/command/egg_info.py:643: SetuptoolsDeprecationWarning: Custom 'build_py' does not implement 'get_data_files_without_manifest'. Please extend command classes from setuptools instead of distutils. warnings.warn( Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs … -
Django ORM: select until value in column changes
I want to get newest events until the first change. This is my data (sorted by timestamp): # EventModel id | event | timestamp ---+-----------+----------- 1 | birthday | 5 2 | birthday | 4 3 | wedding | 3 4 | null | 2 5 | birthday | 1 This is my desired output: <QuerySet [{'id': 1, 'event': 'birthday', 'timestamp': 5}, {'id': 2, 'event': 'birthday', 'timestamp': 4}]> Please note that there is also event=birthday where id=5, but I don't want it in the output. The newest event can be null and that's ok. I tried with Subquery: from django.db.models import Subquery subquery = EventModel.objects.order_by("-timestamp").values("event")[:1] EventModel.objects.filter(event=Subquery(subquery)) But this gives me also row with id=5. -
DeleteView is missing a queryset
So i'm working on an inventory app, a django-app where you can handle inventory in a company. I've been using mostly class-based so far in my views.py, and i can already create and edit all of my models using class-based views. So when it comes to the generic.DeleteView, i have some problems. This is my function in views.py: class DeleteItemView(DeleteView): model: Item success_url: reverse_lazy('inventory_app:items') template_name = 'inventory/detail_pages/item_detail.html' And this is my URL to the function: path('items/<int:pk>/delete/', views.DeleteItemView.as_view(), name='delete_item') When i call this url with a button, this error appears: DeleteItemView is missing a QuerySet. Define DeleteItemView.model, DeleteItemView.queryset, or override DeleteItemView.get_queryset(). So i heard online that this appears when /<int:pk>/ is missing in the url. But i have it in mine, so whats the problem here? Thank you already -
my css codes does not work on some parts of my django project
So i am building a website with django but my css code working some parts while some parts dont. this is my home.html {% extends 'base.html' %} {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static '/static/css/home.css'%}"> <script src="{% static 'fontawesomefree/js/all.min.js' %}"></script> <link href="{% static 'fontawesomefree/css/all.min.css' %}" rel="stylesheet" type="text/css"> </head> <body> {% block content %} <div class="container"> <div class="card"> {% for product in product_list %} <div class="image"> <img src="{{ product.image }}" alt="{{product.title}}"> </div> <div class="content"> <div class="product-name"> <h3>{{product.title}}</h3> </div> <div class="price-rating"> <h2>13.40$</h2> </div> <div class="rating"> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> </div> </div> {% endfor %} </div> </div> {% endblock %} </body> </html> and this is home.css * { margin: 0; padding: 0; box-sizing: border-box; } body { display: flex; justify-content: center; align-content: center; min-height: 100vh; background: #dcdcdc; } .image { width: 10%; } .container { position: relative; width: 1200px; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) } I can change color of page but i cannot change the display or i cannot change sequence of items. image of my site so do you people have any idea to fix this issue? and my codes are not conflicting because i … -
Django poll - change from only one seleted option (radio) in multiple selection (checkbox) and register all togheter
I made a poll app in django. It work ok but what i want to change is the selection an register vote option. Now i can select and register one option ('participanti') (radio btn select) and i want to be able to let the user to select more than one "participanti" (1 or 1 to maximum 3 ) in the same instance and after submit to register all the option/participanti selected (1 or 2 or all maximum 3 that user selected) . I don't know how to approach this kind of mechanism. Please help me with a solution. Thank you very much. Below mai settings models class Campanie(models.Model): ..... class Participanti(models.Model): campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE) nume_participant = models.CharField(max_length=200, verbose_name='nume') dep_participant = models.CharField(max_length=200, verbose_name='departament') votes = models.IntegerField(default=0) def __str__(self): return self.nume_participant class Meta: verbose_name = 'Participanti' verbose_name_plural = 'Participanti' views.py def votare_campanie(request): campanie = get_object_or_404(Campanie) try: participant_votat = campanie.participanti_set.get(pk=request.POST['participanti']) except (KeyError, Participanti.DoesNotExist): return render(request, 'campanievot/campanie.html', { 'campanie' : campanie, 'error_message' : "Trebuie sa votezi cel putin un coleg", }) else: participant_votat.votes += 1 participant_votat.save() messages.success(request, "Multumim pentru feedback!") return redirect('campanievot:index') template.html <form action=" {% url 'campanievot:votare_campanie'%} " method="post" > {% csrf_token %} {% for p in campanie.participanti_set.all %} {% if p.dep_participant … -
TimeoutError at /index
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond -
('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)
I am trying to connect sql server 2019 (running on another server) with Django project in AWS Lambda environment (Amazon linux) but I am not able to establish connection between django and the sql server database and I get error ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect) Below are the steps I am following to deploy to AWS lambda Spinning docker image with command: docker run -t -i -p 8000:8000 -e AWS_PROFILE=zappa -v "/task" -v C:\Users\Ishan/.aws/:/root/.aws --rm zappa-docker-image dockerfile from lambci/lambda:build-python3.7 #make this default working directory WORKDIR /task #expose tcp port 8000 for debugging EXPOSE 8000 #Prompt to remind you are in zappashell RUN echo 'export PS1="\[\e[36m\]zappashell>\[\e[m\] "' >> /root/.bashrc CMD ["bash"] Once environment is up, I setup msodbcdriver17 using below commands taken from Microsoft's online setup guide: RUN curl http://mirror.centos.org/centos/7/os/x86_64/Packages/unixODBC-2.3.1-14.el7.x86_64.rpm > /tmp/unixODBC-2.3.1-14.el7.x86_64.rpm RUN yum -y install /tmp/unixODBC-2.3.1-14.el7.x86_64.rpm RUN curl http://mirror.centos.org/centos/7/os/x86_64/Packages/unixODBC-devel-2.3.1-14.el7.x86_64.rpm > /tmp/unixODBC-devel-2.3.1-14.el7.x86_64.rpm RUN yum -y install /tmp/unixODBC-devel-2.3.1-14.el7.x86_64.rpm RUN curl https://packages.microsoft.com/config/rhel/7/prod.repo > /etc/yum.repos.d/mssql-release.repo RUN ACCEPT_EULA=Y yum -y install msodbcsql17 Path of msodbcsql17 is /opt/microsoft/ Result of odbcinst -j unixODBC 2.3.1 DRIVERS............: /etc/odbcinst.ini SYSTEM DATA SOURCES: /etc/odbc.ini FILE DATA SOURCES..: /etc/ODBCDataSources USER DATA SOURCES..: /root/.odbc.ini SQLULEN Size.......: 8 SQLLEN Size........: … -
Example of updating fields without views.py?
Can you please provide an example of vievs.py updating(or crating) fields without using forms.py? -
twilio python cannot send dynamic messages
i am facing issues regarding sending twilio messages from python back-end code. I am able to send static messages to the phone but when i create dynamic messages the messages is send successfully but not able to received in the device. customerName = request.data.get('fullName') phoneNumber = "+91" + request.data.get('phoneNumber') bodyM = f'Hey {customerName} worth' print(bodyM) serializer = UserSerializer(data=data) if serializer.is_valid(): collection_name.save(data) message = client.messages.create(to=phoneNumber , from_="+16104865966", body=bodyM) Adding code for better understanding of the issue i am facing -
Getting Error while reloading the matplotlib plot without refreshing the page
I am trying to reload the matplotlib figure without refreshing the page and using Slider to change the slice number using django, matplotlib, mpld3, and javascript. The slider changes the slice number before generating the new plot matplotlib throws an error. File "D:\Django_Projects\Django_Gliomai\BraTS\show.py", line 25, in plot_1 plt.imshow(original[x,:,:,i], cmap='bone') File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib_api\deprecation.py", line 459, in wrapper return func(*args, **kwargs) File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib\pyplot.py", line 2660, in imshow sci(__ret) File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib\pyplot.py", line 3032, in sci return gca()._sci(im) File "D:\Django_Projects\Django_Gliomai\virtual_env\lib\site-packages\matplotlib\axes_base.py", line 2155, in _sci raise ValueError("Argument must be an image, collection, or " ValueError: Argument must be an image, collection, or ContourSet in this Axes -
Django dynamic template filter tag
is it possible to make a dynamic tag inside a if tag my view is this {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK.{{DYNAMIC}} %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} {% endfor %} I want filter this by date. Like an input for date and it would show my ' <td> like I have it in my template -
How to delete latest record if it is matched with today date in django
I want to delete the record if it is matched with today's date and new record should replace with old record if it matches I wrote code like below but it's not deleting the record new record also adding Def addEscalatedcount(request): dataDict=Helix.fectEscalted() ifdataDict['error']==False: ESC=Escalated_count.object.all() If ESC: recdate=ESC[0] if str(recdate.last_run.date)[0:10]==str(datetime.date.today())[0:10]: Escalated_count.get(id=recdate.id). delete () ESC=addEscalatedSerializer(data=dataDict['data'],many=True) if ESC.is_valid(): ESC.save() return jsonResponce("data saved",safe=False) -
is it normal to have meta data outside head Django templates
i have three templates home, navbar, base and footer. navbar and footer are included in base and base in extended in every other template (home). this is base.html: {% load static %} <head> <link rel="stylesheet" href="{% static 'base.css' %}"> <link rel="stylesheet" href="{% static 'navbar.css' %}"> <link rel="stylesheet" href="{% static 'footer.css' %}"> </head> {% include 'navbar.html' %} <div id="all"> <div id="bg"> <img id="l1" src="{% static 'img/bg-layer-1.svg' %}"> <img id="l2" src="{% static 'img/bg-layer-2.svg' %}"> </div> {% block content %} {% endblock %} </div> {% include 'footer.html' %} this template represents navbar.html and footer.html: {% load static %} <div class="wrapper"> <ul id="navbar"> <li class="left"> <a href="{% url 'index'%}">Home</a> </li> <li class="right"> <a href="{% url 'account'%}">Account Managment</a> </li> <li class="right"> <a href="{% url 'contests'%}">Contests</a> </li> </ul> </div> <script src="{% static 'navbar.js' %}"></script> this is home.html: {% extends 'base.html' %} {% load static %} <html lang="en"> {% block content %} <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" /> <title>Home Page</title> <link rel="stylesheet" href="{% static 'home.css' %}"> </head> <body> <div class="content"> <table border="0"> <tr> . . . </tr> </table> </div> </body> </html> {% endblock %} technically everything works fine from styling to html elements order in view, but when i inspect … -
I need to upload data from REST API on front-end using vue.js framework but not using vue.js cli
I'm trying to get the data from rest api using vue.js. But it's not working , I've started learning vue.js just now I've tried to implement many logic but still it doesn't gives the appropriate output. Here's my views.py file # Create your views here. class TaskViewSet(ModelViewSet): renderer_classes = [TemplateHTMLRenderer] template_name = 'templates/list.html' def list(self,request): queryset = Task.objects.all() serializer = TaskSerializer(queryset,many=True) context = { 'serializer' : serializer.data } return Response(context) Here's my list.html file <!DOCTYPE html> <html lang="en"> {%load static%} <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"> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js" integrity="sha256-Gs0UYwrz/B58FsQggzU+vvCSyG/pewemP4Lssjzv8Ho=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue- resource.min.js" integrity="sha256-OZ+Xidb5+lV/saUzcfonHJQ3koQncPy0hLjT8dROdOU=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue- resource.min.js" integrity="sha256-OZ+Xidb5+lV/saUzcfonHJQ3koQncPy0hLjT8dROdOU=" crossorigin="anonymous"></script> <title>Document</title> </head> <body> <h3>Tasks Display Here</h3> <div id="app" v-for="task in tasks"> {{task.data}} </div> <script> var app = new Vue({ el : '#app', data:{ tasks : [] } }, methods : { async getData(){ try { // fetch tasks const response = await this.$http.get('http://localhost:8000/api/tasks/'); // set the data returned as tasks this.tasks = response.data; } catch (error) { // log the error console.log(error); } }, }, created(){ this.getData(); } } </script> </body> </html> I have mentioned my API url from where the data is getting retrieved but still the vue.js script is unable to collect the data … -
Cannot see foreign key values in the template
This is my 2nd week learning Django. I'm trying to get comfortable with Django Template Language. I'm trying to make an Inventory app with 4 models. The views for them are class-based. The templates for Ingredient and Menu work as expected. However, I'm struggling with trying to loop through values from the Purchase model which has a foreign key field 'menu_item'. The template is not showing anything from the for loop. I've referred numerous articles here to find most of them use function-based views. I've tried using {% for purchase in purchase_set %}, {% for purchase in purchase_set.all %}. I know the object to iterate over is a query-set. I cannot figure out what to do? MODELS.PY from django.db import models # Create your models here. class Ingredient(models.Model): Pounds = 'lbs' Ounces = 'oz' Grams = 'gms' Eggs = 'eggs' Piece = 'piece' Litre = 'litre' unit_choices = [(Pounds, 'lbs'), (Ounces, 'ounces'), (Grams, 'grams'), (Eggs, 'eggs'), (Piece, 'piece'), (Litre, 'litre')] id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) unit_price = models.FloatField(default=0.0) quantity = models.FloatField(default=0.0) unit = models.CharField(max_length=10, choices=unit_choices) class Meta: ordering = ['id'] def __str__(self): return self.name class MenuItem(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) price = models.FloatField(default=0.0) class Meta: ordering = … -
How to create Basic PWA (progressive web apps) using django
I'm new to PWA with django. Can anyone suggest me a basic PWA app with django(with code). I tried working with the basic web app suggested in the geeks for geeks website (https://www.geeksforgeeks.org/make-pwa-of-a-django-project/) but it didn't work as the instructions were not enough. I'm unable to load the manifest in the devtools >> apps. I tried them as per the instructions in the site by adding the manifest code in settings but it did not create any manifest.json file in the templates. So please suggest me a basic code to make a pwa app with django. Thank you in advance. -
What to do if value is different than all the defined choices for Django field choices?
I am currently working on a Django web application. I have defined a model as follows: class MyModel(models.Model): fav_subject_choices=[ ('physics', 'Physics'), ('chem', 'Chemistry'), ('math', 'Maths'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) student_name = models.CharField(max_length=100) fav_subject = models.CharField(max_length=50, choices=fav_subject_choices, default='physics') Here, I want to provide a dropdown of choices so that Admin can select favorite subject for students. For which I have defined choices and provided the same inside the field. However, the data of students is coming from an API which may have favorite subjects of students different from the choices I have defined, for example, a student can have 'English' as his/her favorite subject. This is fine as I don't want to change the data which is already there, instead I want to add favorite subject only for students whose data for favorite subject is missing. How can it be done? Is there an option where a field can have a value other than the choices defined? PS. This is just a dummy scenario which I have created. But it's exactly the same as the problem I am facing. -
error while loading the data using jinja2 conditional operators
I have 2 models Staff and Hod where user is OneToOnefield of User model. Now in hod.html template I want display list of all staff using jinja2 for loop Loop works perfectly but I want to display the staff which has same branch/department and the year When I use this if statement I don't get any staff which has same department and year models.py class Hod(models.Model): id = models.AutoField(primary_key=True) user=models.OneToOneField(User, on_delete=models.CASCADE) hod_of_year=models.ForeignKey(Year,on_delete=models.DO_NOTHING) hod_of_department=models.ForeignKey(Course,on_delete=models.DO_NOTHING) #..... class Staff(models.Model): id = models.AutoField(primary_key=True) user=models.OneToOneField(User, on_delete=models.CASCADE) teacher_of_year=models.ForeignKey(Year,on_delete=models.DO_NOTHING) teacher_of_department=models.ForeignKey(Course,on_delete=models.DO_NOTHING,null=True) #.... hod.html <tbody> {% for staff in staffs %} {% if user.hod.hod_of_year == staff.teacher_of_year and user.hod.hod_of_department == staff.teacher_of_department %} <tr> <td style="color:white;">{{staff.user.first_name}}</td> <td style="color:white;">{{staff.user.last_name}}</td> <td style="color:white;">{{staff.mobile_no}}</td> <td style="color:white;">{{staff.user.email}}</td> <td style="color:white;">{{staff.identity_no}}</td> <td style="color:white;">{{staff.class_alloted1}}</td> <td style="color:white;">{{staff.class_alloted2}}</td> <td style="color:white;">{{staff.class_coordinator_of}}</td> <td style="color:white;">{{staff.teacher_of_year}}</td> <td style="color:white;">{{staff.mentor_of}}</td> <td style="color:white;">{{staff.teacher_of_subject}}</td> <td style="color:white;">{{staff.teacher_of_department}}</td> <td> <form action="{% url 'deletestaffdatahod' staff.id %}" method="post" class="d-inline"> {% csrf_token %} <button type="submit" value="Delete" class="btn btn-warning">Delete</button> </form> </td> </tr> {% endif %} {% endfor %} </tbody> Similarly I have one more student model and I used the same logic but I get the students of same branch and year student.html <tbody> {%for student in students%} {% if user.hod.hod_of_year == student.year and user.hod.hod_of_department == student.branch %} <tr> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> …