Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at /assignment/get/ Field 'zip' expected a number but got 'zip'
While storing data from csv file to database I am getting error ValueError at /assignment/get/ Field 'zip' expected a number but got 'zip'. model.py from django.db import model # Create your models here. class csvData(models.Model): zip=models.IntegerField() lat=models.IntegerField() lng=models.IntegerField() views.py import csv from .models import csvData def get(request): fname="uszips.csv" with open(fname) as csvfile: csv_reader=csv.reader(csvfile, delimiter=',') for row in csv_reader: csvdata=csvData() csvdata.zip=row[0] csvdata.lat=row[1] csvdata.lng=row[2] -
Django migrations aren't applying?
When running my server I get the message: You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): app_name I've tried python3 manage.py migrate, but that gives this result Operations to perform: Apply all migrations: app_name Running migrations: No migrations to apply. Where do I need to look to fix this? I've deleted migrations a few times, which I realise is a bad move but I can't wipe the db either at this point. -
How to create a stateful WSGI Python web app
I would like to create a python web api where in-memory state can be shared between requests. I understand that the recommended/best practice for this is to use memcached or redis. However, I do not want to use these, I want to have a local shared memory option: I will only ever run this application on one server. No clusters no load balancing no need to share memory between nodes. I'm also just interested to know, what if I wanted to write a cache service like memcached myself, how would I do it without using memcached?! My current understanding is that Gunicorn spawns multiple different processes, and "recycles" web workers, meaning any "global" variable is not going to be around consistently between requests. I therefore reason that either I would need to find way to serve the wsgi app using only one process, and then share memory between threads, or I would need to find a way to share memory between processes. In either event though, how would I set that up if gunicorn is in control of the processes? And how would I prevent recycling of web workers losing the state? I've also seen some recommendations to use gunicorns … -
load static and DOCTYPE html position in django views
I am new to Django and have trouble understanding the difference between the position of lines shown below: {% load static %} <!DOCTYPE html> In the above code, the PyCharm shows error but if I change the position as shown below, it works as intended: <!DOCTYPE html> {% load static %} Can anyone explain how this works or if I am doing it the wrong way? Thanks!! -
Target WSGI script '/opt/python/current/app/github/wsgi.py' cannot be loaded as Python module
I am trying for two days to deploy my django project on aws. But i am getting one error after another. After lots of searching for answers. This is the last error that i am not able to overcome. I am following these guides: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/ After all of it. When i try to access my site.It shows 500 Server Error. In Logs it Shows Target WSGI script '/opt/python/current/app/github/wsgi.py' cannot be loaded as Python module. Another question on net answered to comment the Database lines in settings file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } After it my site loads. But then the problem is there is not database. So it throws another error settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. So now i am struck here. I have looked at every related question tried there solution but nothing is working. It is my first time trying AWS and it is turning out to be very hard. I deployed my project on heroku successfully but heroku does not support cron job and i really need something like cron job for my project. -
Nginx not serving media files. Dockerizing django/nginx/gunicorn/postgresql
I have a project running in 3 docker containers. One is for django project itself, another one for postgres and the third one for nginx. My static files are served just fine while all media files are not found. However every file which was uploaded is properly saved in web container in media folder. Here is the docker-compose file: version: '3.8' volumes: postgres_data: static: services: db: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: . restart: always command: gunicorn foodgram.wsgi:application --bind 0.0.0.0:8000 volumes: - ./static:/static - ./media:/media ports: - "8000:8000" depends_on: - db env_file: - ./.env nginx: build: context: . dockerfile: nginx/Dockerfile ports: - "8080:80" volumes: - ./static:/etc/nginx/html/static - ./media:/etc/nginx/html/media depends_on: - web Here is the dockerfile: FROM python:3.8.5 WORKDIR /code COPY . /code RUN pip install -r /code/requirements.txt Here is the nginx.conf: events {} http { include mime.types; server { location / { proxy_pass http://web:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; } location /static/ { autoindex on; root /etc/nginx/html/; } location /media/ { autoindex on; root /etc/nginx/html/; } } } and finally nginx dockerfile: FROM nginx:latest COPY nginx/nginx.conf /etc/nginx/nginx.conf What do I miss? -
Static Files are set but not working. I keep getting 500 error
Can someone please look at the way I have my static files set up and tell me if there is something I am missing? Thank you. STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' -
How can I access to EmbedVideoField from Wagtail?
How can I access to EmbedVideoField from Wagtail? I'm getting a message "Unresolved reference 'EmbedVideoField' ". How can I import it? -
How to use bootstrap with django rest framework?
Recently I began to develop a REST API with Django REST Framework. I want to change the bootstrap, and I used the The Browsable API as a guide. But, every time I followed the instructions to override the bootstrap template, the appearance of the site changes, but the DELETE button doesn't work. I add to the setting.py: TEMPLATES = [ ..., 'DIRS': [os.path.join((BASE_DIR), 'templates/')], ..., ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') I created a folder static/css where is the file bootstrap.min.css. I also created a folder templates/rest_framework where is the file api.html with the following code. {% extends "rest_framework/base.html" %} {% block bootstrap_theme %} <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> {% endblock %} {% block bootstrap_navbar_variant %}{% endblock %} What could I be doing wrong? -
Cannot redirect to specific path name in urls.py
I have a issue in django project where I want to redirect to a specific path using its name. My code looks like this. It doesn't redirect to a path name but It redirect towards http://127.0.0.1:8000/ perfectly. I googled and also searched it in stack overflow but I didn't find any question related to this. What can be the problem and solution to it. I followed tutorial and there his code his working fine and redirecting well. urls.py from django.contrib import admin from django.urls import path from .views import * urlpatterns = [ path('', index, name='myhomepage'), path('order', order), path('signup', signup) ] And in views.py the code goes like this: from django.shortcuts import render, redirect from django.http import HttpResponse from .models.product import Product from .models.category import Category from .models.customer import Customer # Create your views here. def index(request): # calling get_all_product() method from products products = None categories = Category.get_all_categories() category_id_from_server = request.GET.get('category') if category_id_from_server: products = Product.get_all_product_by_category_id(category_id_from_server) else: products = Product.get_all_product() data = {} data['products'] = products data['categories'] = categories return render(request, 'index.html', data) def order(request): return render(request, 'orders.html') def signup(request): if request.method == 'GET': return render(request, 'signup.html') else: postdata = request.POST first_name = postdata.get('firstname') last_name = postdata.get('lastname') phone_number = … -
Django Select a valid choice.[...] is not one of the available choices. in a dynamically generated form
I am making a quiz application and I want to make a dynamic form to render the questions. I use two widgets in my questions (widgets.RadioSelect and widgets.CheckboxSelectMultiple) to render the question's choices. when I submit the form I get the following error: Select a valid choice.['option1', 'option2'] is not one of the available choices. rises only from questions with the second widget eg:widgets.CheckboxSelectMultiple. The RadioSelect submits successfully. forms.py: class QuestionForm(forms.Form): def __init__(self, fields, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) # Init form fields for field in fields: self.fields[field['name']] = forms.ChoiceField( label=field['label'], choices=field['choices'], widget=getattr(widgets, field['widget']), required=False ) views.py: def quiz(request, quiz_id): quiz = get_object_or_404(QCM, pk=quiz_id) if request.method == 'POST': if request.POST['action'] == 'Save': form = QuestionForm(data=request.POST) if form.is_valid(): print('form is valid :)') form.save() else: print('form is not valid :(') else: form = QuestionForm() context = { 'form': form, } return render(request, 'quiz/quiz.html', context) quiz.html {% extends "quiz/first.html" %} {% load staticfiles %} {% block main %} <form method="POST" class="form-horizontal" id="qcm_form" enctype="multipart/form-data"> <div class="row"> <div class="col-md-12"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label class="field-label" for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %} <span class="text-danger">*</span>{% endif %}</label> {{ field }} </div> {% endfor %} </div> </div> <input type="submit" … -
Why when i try to create a user in django the form doesn't react?
I tried to make a Customer: models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=10, null=True) email = models.CharField(max_length=40, null=True) with the use of this form forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'placeholder': 'username'}), 'email': forms.TextInput(attrs={'placeholder': 'email'}), 'password1': forms.TextInput(attrs={'placeholder': 'password'}), 'password2': forms.TextInput(attrs={'placeholder': 'repeat password'}), } html <form method="post"> {% csrf_token %} <ul class="list-group list-group-flush"> <li class="list-group-item"><p>{{ form.username }}</p></li> <li class="list-group-item"><p>{{ form.email }}</p></li> <li class="list-group-item"><p>{{ form.password1 }}</p></li> <li class="list-group-item" style="border-bottom: 1px solid #e4e5e6;"><p>{{ form.password2 }}</p></li> </ul> <input class="btn btn-primary" type="submit" type="button" style="width: 27%;margin-left: 63%;margin-top: 4%;"> </form> views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name='customer') user.groups.add(group) user.objects.create( user=user, name=user.username, ) return redirect('/') return render(request, 'register_page.html', { 'form': form, }) but when I click submit nothing happens and it doesn't create a record. Please help :( dasdsadasdasdasdfasewgaggiuhihqworeghoashgiiasigjioasigjiaipgjiaiasoopijpgjiaspjgpisapigaspj -
how to differentiate two forms in a django template?
I'm creating forms directly in a django html template. In this template I have 2 forms. {% extends 'base.html' %} {% block title %} <title>Add Groups</title> {% endblock %} {% block content %} <h1>Add Groups</h1> <form method="post"> {% csrf_token %} <label>User</label> <input type="text" name="user_name"/> <label>Password</label> <input type="text" name="password"/> <input type="submit" value="Submit"> </form> {% if groups %} <form method="post"> {% csrf_token %} {% for group in groups %} <div class="div_group"> <h3> <input type="checkbox" name="{{group.id}}" value="{{group.name}}"> {{group.name}}</h3> <div> <span>Id:</span> {{group.id}} <br> <a href="{{group.link}}">{{group.link}}</a> <br> <span>Role:</span> {{group.role}} <br> <span>Tags:</span> {{group.tags}} </div> </div> {% endfor %} <input type="submit" value="Add Grupos"> </form> {% endif %} <br> {% endblock %} In the views.py im trying to differentiate from the forms. I've made it asking for fields that only appear in the first form def admin_add_group(request): if request.user.is_staff and request.user.is_staff: context = {} if request.method == 'POST': if 'user_name' in request.POST: user_name= request.POST['user_name'] mendeley_password = request.POST['password'] try: # login mendeley md.authenticate(mendeley_user, mendeley_password) groups = md.get_groups() context['groups'] = groups except Exception as exc: context['errors'] = [str(exc)] else: c = request.POST print(c) # redirect to groups view. return render(request, 'admin_add_group.html', context) else: context = {} return render(request, 'admin_add_group.html', context) Is there another way to know what form is makin … -
How to create multiple first in first out queues in celery?
I have a Django webservice running on one machine that submits jobs to a celery worker running on another machine. Here is what my models.py looks like: class Department(models.Model): name = models.CharField(max_length=200) class Employee(models.Model): name = models.CharField(max_length=200) department = models.ForeignKey(Department) This is what my celery systemd service file looks like this: [Unit] Description=celery daemon After=network.target [Service] Type=forking User=<user> Group=<group> WorkingDirectory=<path_to_working_directory> ExecStart=celery multi start worker -A project --pidfile=<process_id_path> \ --concurrency=1 --logfile=<path_to_logfile> --loglevel=debug ExecStop=celery multi stopwait worker -A project --pidfile=<process_id_path> \ --concurrency=1 --logfile=<path_to_logfile> --loglevel=debug ExecReload=celery multi refresh worker -A project --pidfile=<process_id_path> \ --concurrency=1 --logfile=<path_to_logfile> --loglevel=debug [Install] WantedBy=multi-user.target Currently, I use a Django signal that creates a new queue every time a new department is added. However if I set the concurrency to 1 in my systemd file then the worker runs only one job at the time. And if i don't mention concurrency then it sometimes runs multiple jobs from the same queue parallelly. I want it to run multiple jobs parallelly, but at a given time only one from each queue should be running. For example. Lets say there are 3 departments A,B,C. This creates 3 queues, one for each department, queueA, queueB, queueC. I want the worker to be concurrently … -
Generating Django HTML template with JavaScript
I used this function to download the PDF version of HTML template, but it didn't work, here is the function: <script> function getPDF() { var HTML_Width = $(".canvas_div_pdf").width(); var HTML_Height = $(".canvas_div_pdf").height(); var top_left_margin = 15; var PDF_Width = HTML_Width + (top_left_margin * 2); var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2); var canvas_image_width = HTML_Width; var canvas_image_height = HTML_Height; var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1; html2canvas($(".canvas_div_pdf")[0], { allowTaint: true }).then(function(canvas) { canvas.getContext('2d'); console.log(canvas.height + " " + canvas.width); var imgData = canvas.toDataURL("image/jpeg", 1.0); var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]); pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height); for (var i = 1; i <= totalPDFPages; i++) { pdf.addPage(PDF_Width, PDF_Height); pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height); } pdf.save("HTML-Document.pdf"); }); }; </script> It works only when the HTML snippet doesn't contain Django tags or variables, here is an example where it worked: <button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button> <div class="canvas_div_pdf" style="margin-left:100px;"> <h1>title</h1> <p> Content.</p> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script> <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script> And here is where it didn't work: <button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button> <div class="canvas_div_pdf" style="margin-left:100px;"> <h1>{{qr.title}}</h1> <p> {{qr.content}}</p> </div> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> … -
Django Project - Update made inadvertently now failing
I am working on a Django Project 3.0.7 using Python 3.8. Something was updated inadvertently [like the title says] and I can't seem to figure out what it is. Any assistance is appreciated, full traceback below: File "C:\Program Files (x86)\Python383-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python383-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python383-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Program Files (x86)\Python383-32\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File … -
I can't find which algorithm should i use to solve this problem
I'm working on a project that will track the attendance and leaving of employees in a company. Each employee has a mobile application connected to the web server, once he reached his working area (each employee has a specific working area) he can log in using the mobile application (he can't log in outside his working area, we depend on Google APIs). For some restriction reasons from HR (i will not deep dive into details of that), Each 10mins the employee will automatically logout from the application and he needs to sign in again in the same working area. I will not mention a lot of details about the application to save your time but we can grasp from previous statements that each user will have multiple sign in time and sign out time at the same day, here is the DB model that will handle this: class SignInOutLogs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) signin_time = models.DateTimeField(verbose_name="Sign in Time") signout_time = models.DateTimeField(blank=True, null=True, verbose_name="Sign Out Time") Our company has 1500 employees, we want to ensure that each one of them has attended 8 hours at work, after a lot of talking with HR, he told me … -
How to display the field "label" in django's builtin password validation errors?
I am using Django's builtin authentication class views and need to customize the error message displayed when password validation fails. For example, in the builtin PasswordResetView, if I try to change my password to test, the following errors will display in my template: new_password2 This password is too short. It must contain at least 8 characters. This password is too common. I would like to change new_password2 to New Password. Here is the relevant part of my template for the PasswordResetView: {% extends 'registration/base.html' %} {% block card_body %} <div class="form-group"> <label for="old_password"> Old Password: {{ form.old_password }} </label> </div> <div class="form-group"> <label for="new_password1"> New Password: {{ form.new_password1 }} </label> </div> <div class="form-group"> <label for="new_password2"> Confirm Password: {{ form.new_password2 }} </label> </div> <div class="form-group"> <input type="submit" value="Change" class="btn float-right login_btn"> </div> {% endblock card_body %} {% block card_footer %} {% if form.errors %} <p class="d-flex justify-content-center links"> {{ form.errors }} </p> {% endif %} {% endblock card_footer %} -
Add styling to django Password reset forms
I want to add styling to django's default password reset form such as classes and placeholders I have the following in my urls.py from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ # Password reset paths path('password_reset/', auth_views.PasswordResetView.as_view(template_name="main/password_reset.html"),name="reset_password"), path('password_reset_sent/', auth_views.PasswordResetDoneView.as_view(template_name="main/password_reset_sent.html"),name="password_reset_done"), path('reset_password/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="main/reset_password.html"),name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="main/reset_password_complete.html"),name="password_reset_complete"), ] in the templates <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Send email" class="btn btn-primary" > </form> -
I need a way to pass unique object id in my django function based list view
I have been stucked on this for a couple of days, all help would be really cherished. I have a list and detail view which are function based views, my detail view works perfectly because i am able to pass the "/str:pk/" at the end of the url and also with the request as(def po_detail(request, pk)) which in turn i am able to pass into my view functions and they all successfully return the unique id i desire. I have a custom queryset i have written to help me get the sum total amount of some payments and return it in both the list and detail view. The issues now is that i am not able to get each unique items in my list view page because i am not able to pass the pk into the url and the request function as the object i used it for in detail function has access to the pk. I would love if any one can provide an hint, suggestion, or solution. Thanks, Oyero H.O Below is my model class PurchaseOrder(models.Model): created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) po_type = models.ForeignKey(PurchaseOrderType, on_delete=models.SET_NULL, null=True) status = models.CharField(choices=STATUS, max_length=15) supplier_ID = models.ForeignKey(Supplier, on_delete=models.SET_NULL, null=True) order_date … -
Django 'No file chosen' in FileInput
I have a project here. I am able to add photos through the /admin panel. I tried to create a form so that I can add a photo not by going thro' the admin panel. I get an error of file chosen. I can't tell where my problem is. My model class Photos(models.Model): Photo = models.ImageField(upload_to='background',blank=True,null=True) class Meta: ordering = ('-pk','Photo') def __str__(self): return('Photos') My forms.py class AddPhotosForm(forms.ModelForm): class Meta: model = Photos fields = ("Photo",) widgets = { "Photo":forms.FileInput(),} My views.py class AddPhotosView(CreateView): model = Contact form_class = AddPhotosForm template_name = "add_photo.html" success_url = reverse_lazy('photos') urls.py path('add_photo',AddPhotosView.as_view(), name='add_photo'), My add_photo.html {% extends "base.html" %} {% block title %} Add Photo {% endblock %} {% block content %} <hr> <article class="container" > <div class="btn-primary" style="padding:10px;border-radius:10px">Add Photo</div> <hr> <div> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-outline-primary">Add</button><br><hr> </div> </div> </article> {% endblock %} -
Pass a queryset as the argument to __in in django?
I have a list of object ID's that I am getting from a query in an model's method, then I'm using that list to delete objects from a different model: item_ids = {item.id for item in self.items.all()} other_object = OtherObject.objects.get_or_create(some_param=some_param) other_object.items.filter(item_id__in=item_ids).delete() What I don't like is that this takes 2 queries (well, technically 3 for the get_or_create() but in the real code it's actually .filter(some_param=some_param).first() instead of the .get(), so I don't think there's any easy way around that). How do I pass in an unevaluated queryset as the argument to an __in lookup? I would like to do something like: other_object.items.filter(item_id__in=self.items.all().values("id")).delete() -
Filtering a reverse lookup in Django template
I have a model that looks like this class Invoice(models.Model): inv_number = models.CharField(max_length=10, primary_key=True) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) inv_date = models.DateField() class Txn(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.PROTECT) transaction_date = models.DateField() reference = models.CharField(max_length=12) amt = models.IntegerField() I would like to display a report in my template that lists filtered invoices each with a sub-list of filtered transactions. In my view I have done the following: invoice_list = Invoice.objects.filter(customer=customer) Which I pass into my template. In the template, I do something like the following: {% for invoice in invoice_list %} {{ invoice.inv_number }}, {{ invoice.customer}}, {{ invoice.inv_date }} {% for txn in invoice.txn_set.all %} {{ txn.transaction_date }}, {{ txn.reference }}, {{ txn.amt }} {% endfor %} {% endfor %} This works great to show the entire transaction list per filtered invoice. The question is, how does one also filter the list of transactions per invoice in the template - what if I wanted just the transactions within a certain date range or that match a specific reference? Is there maybe a way to pass a filter to the txn_set queryset per invoice in the view before putting the main queryset in the context and without converting them to lists? Thank you … -
Django queryset get names of model fields
I want to get field names of Django model through queryset. Models.py: class User1(models.Model): types1 = ( ('a', 'a'), ('b', 'b'), ('c', 'c'), ) types2 = ( ('a', 'a'), ('b', 'b'), ('c', 'c'), ) q1 = models.CharField ( 'Today1', max_length=200, choices=types1, blank=True, null=True, default='---------' ) q2 = models.CharField ( 'Today2', max_length=200, choices=types2, blank=True, null=False, default='---------', ) After queryset, I want to get [q1,q2] or something similar to this but containing only field names. -
Code runs in Google Collab but not on local machine python
I'm running a TensorFlow model and when I try to run it on google collab it runs fine but if I run the same code on my local machine it gives me the following error: C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py:1472: RuntimeWarning: invalid value encountered in less if self.monitor_op(current - self.min_delta, self.best): Traceback (most recent call last): File "lstm_var_1.py", line 363, in <module> callbacks=[es], steps_per_epoch= len(generator_train_var)) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\kerashypetune\kerashypetune.py", line 460, in search **all_fitargs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 66, in _method_wrapper return method(self, *args, **kwargs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\training.py", line 876, in fit callbacks.on_epoch_end(epoch, epoch_logs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py", line 365, in on_epoch_end callback.on_epoch_end(epoch, logs) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\callbacks.py", line 1485, in on_epoch_end self.model.set_weights(self.best_weights) File "C:\Users\Shaikh Abuzar\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1519, in set_weights if expected_num_weights != len(weights): TypeError: object of type 'NoneType' has no len() If anyone can help me it would be really great. https://colab.research.google.com/drive/1kQ2KeiSXEbLRJ3tooJ8A6-tg0oqmNBRR?usp=sharing Thanks in advance.