Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Jquery doesn't work suddenly even though nothing changed.. ..is not defined
Jquery stopped working suddenly today even though I didn't change anything. I thought js file cannot be loaded from AWS S3 correctly and moved the part to html file but still doesn't work. here is my html <button class="btn btn-outline-warning" onclick="deleteEntry(this)" data-id="{{ entry.pk }}">Delete</button> ... <script> var csrf_token = '{{ csrf_token }}' function deleteEntry(this) { if (confirm("Are you sure you want to delete this entry?")) { var $this = $(this) $this.closest('tr').remove() var id = $this.data('id') $.ajax({ url:'/feeds/delete/' + id, method: 'DELETE', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) }, }) } } </script> SCRIPT1048: SCRIPT1048: The use of a keyword for an identifier is invalid my_feeds (339,22) SCRIPT5009: SCRIPT5009: 'deleteEntry' is not defined How can I fix this? -
how to create a queryset for a multi blogging app where I can get tags for nth post on nth blog by nth user?
I have a couple of django models for my blogging app created for the purpose of learning from online resources. I have searched StackOverflow for similar questions but could not find useful answers. Hence, I am here to ask for help. Here is how my models look like class Blog(models.Model): owner = ForeignKey('auth.User', on_delete=CASCADE, related_name='blog') blog_name = CharField(max_length=100) class Post(models.Model): author = ForeignKey('auth.User', on delete=CASCADE post_title = CharField(max_length=125) post_body = TextField for_blog = ForiegnKey(Blog, on_delete=CASCADE) class Tag(models.Model): tag_name = CharField(max_length=50) class PostTag(models.Model): post_id = ForeignKey(Post, on_delete=CASCADE) tag_id = ForeignKey(Tag, on_delete=CASCADE) class Meta: unique_together = ('post_id', 'tag_id') Any help or direction will be useful. -
How can I fix errors on this page?
These errors occur when you enter the admin page. I want to fix this. Help me. problementer image description here Source code urls.py-fistsite from django.contrib import admin from django.urls import path, include from polls import views urlpatterns = [ path('', views.index, name='index'), path('/polls', include('polls.urls')), path('/admin', include('polls.urls')) ] urls.py-polls from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/result/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] -
Unable to get pygal charts on pdf generated from html rendered via pygal
I am generating graph based reports and using Pygal library for it. I am able to get the graphs on html page but when I convert it into a pdf using wkhtml2pdf I am not able to get any graph. I am rendering and putting the rendered charts in a list and then displaying them in a loop in my html template def get_report_pdf(self, report, from_date=None, to_date=None): svgs = report.get_all_charts(from_date, to_date) html_string = loader.render_to_string('reporting/report- template.html', { 'charts': svgs }) html = HTML(string=html_string) pdfkit.from_string(html_string, '/tmp/report- {}.pdf'.format(report.id), options={'dpi': 300}) fs = FileSystemStorage('/tmp') with fs.open('report-{}.pdf'.format(report.id)) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report-{}.pdf"'.format(report.id) pdf.close() return response My html template is as follows <html> <body> {% for chart in charts %} <div class="py"> {{chart|safe}} </div> {% endfor %} <body> </html> get_all_chart() method returns a list of rendered chart objects I am getting a blank pdf currently. I want the svg charts to be displayed on it. -
Sharing python object within different views
I am working on django (Python 3.5.2) and I want to share the object among different views, i.e. I want to create a user object during login and share it among different views. Is it possible? If yes, how can it be done? -
How to set up a server of multiple Django projects that require virtual environments?
I currently am renting out a virtual machine through a web hosting service with the intention of hosting a django website on it via IIS. I am planning on hosting multiple django websites on it, all within separate virtual environments. I heard through multiple django tutorials that using django (and other dependencies) within virtual environments is good practice, so I created a virtual environment (virtualenv) on my virtual machine and pip installed django (and mysqlclient for connections to my database within my django website). Locally, this would work fine. All I have to do to get my website to work is to activate my virtual environment by going to my virtual environment's Script directory and passing the parameter "activate", and then change directory to my django project and run manage.py runserver. If I were to skip the step where I activate my virtual environment and instead just run manage.py runserver, I would obviously get an error, because django nor mysqlclient exist globally, but rather only in the virtual environment. This begs the question: in production, how am I supposed to activate the virtual environments for each Django website, and THEN launch the server? I have only ever found tutorials online … -
Issue with crsf in Django
I m trying to learn django and I'm to implement csrf token for some senstive actions. But when I intercept the request/response I get csrf_token in every request in cookie field and the webpages where I have actually implemented the csrf_token, in those request I get another csrf token as csrfMiddleware parameter in data. So I want to know why do I get two csrf_tokens in my request and response. POST /demo/login/ HTTP/1.1 Host: xx.xx.xx.xx:8000 User-Agent: xxxxxx Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Referer: http://xx.xx.xx.xx:8000/demo/login/ Content-Type: application/x-www-form-urlencoded Content-Length: 125 Connection: close Cookie: csrftoken=n4bSbWP8p9Uce3b5iAxI0UvDG0qQq7B3OwBXisww754LYztEm0wFf9ARLpVM2v7W Upgrade-Insecure-Requests: 1 csrfmiddlewaretoken=VIqUszlij0OLyTgYEp7V2TRsNUtBqkISmaQZz52G1WYkipyxIP6Sh8WGSjYx2IeL&username=qwerty6&password=password%40123 -
How to send a long url with get method to server
I have want to send a long url with GET, and I also need to add the url in the GET link, like this(React): let urlParam = { apply_user: this.state.apply_user, order_id: this.state.order_id, begin_date: this.state.begin_date, end_date: this.state.end_date, status: this.state.status, execute_mode: this.state.execute_mode, page: page, pageSize: this.state.pageSize, otype:'all', } history.pushState(null, null, '?'+concatURLParams(urlParam)) then I can get all message from the url, like this : http://cmdb.server.com/page/machine/list/?page=1&ips=172.17.10.3%20172.17.10.4%20172.17.10.9%20172.17.10.10 but in fact, the param is so long , there are lots of ip need to send. And I use uwsgi to run my django project, I set buffer-size to 65536. official doc tell me the max size is 64k, but it got this, too. invalid uwsgi request (current strsize: 21600). skip. [pid: 15947|app: -1|req: -1/7] () {0 vars in 31 bytes} [Mon Jan 14 11:18:52 2019] => generated 0 bytes in 0 msecs ( 500) 0 headers in 0 bytes (0 switches on core 0) this is my uwsgi.ini: [uwsgi] socket=127.0.0.1:9090 chdir=/home/ops/cmdb_futu/jumpserver module=jumpserver.wsgi master=true buffer-size=65536 vacuum=true processes=8 max-requests=2000 chmod-socket=664 vacuum=true pidfile=uwsgi.pid and I set nginx large_client_header_buffers and client_header_buffer_size to 64k, too. But I don't make it for a long time. someone know why and help me. -
Cannot assign "<SimpleLazyObject: <User: JohnDoe12>>": "Profile.user" must be a "User" instance
I have two models class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Profile(models.Model): user = models.OneToOneField(User,default=None, null=True,on_delete=models.CASCADE,) name = models.CharField(max_length=128) #actual creator's name In the forms.py class ProfileForm(forms.ModelForm): class Meta: exclude = ['user'] # fields = '__all__' model = models.Profile In views.py def TestPage(request): form = ProfileForm if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): form_instance=form.save(commit=False) form_instance.user = request.user form_instance.save() return render(request,'test.html') else: print('ERROR FORM INVALID') return render(request,'accounts/update_profile.html',{'form':form}) I think there is an issue with the line form_instance.user = request.user. I am getting an errorCannot assign ">": "Profile.user" must be a "User" instance. To Profile.user I want save current user. could some help me with this? Thanks. -
Django update_or_create and if value equal then pass
I use update_or_create this function a while time, but I want to set a judgment to detect the value is equal what I update then pass if not, then update or create (I don't want to waste my session to do the meaningless update, like value 123 update to 123) kwargs['time'] = "2018-01-01 00:00:00" kwargs['id'] = 1 update_kwargs['value'] = 123 instance, created = MyModel.objects.update_or_create(**kwargs, defaults=update_kwargs) -
Django - Update existing form based on current logged in user
My current form submits but makes additional listings in the django admin. I just need this form to update the values in the django admin based on the current user and not repeat. Screenshot below. For example: when user spidey677 submits form: name, address, zip code and mobile number would need to get updated on every form submission as oppose to making additional rows of information. I'm new to django so this may be a basic question. What’s the best way to execute this with my current code? Any help i gladly appreciated, Cheers Screenshot user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): image … -
keeping data between parameterized tests with pytest-django
I'm trying to put together a series of stories with the pytest.parameterize mark as such: conftest.py: from django.conf import settings import pytest @pytest.fixture(scope='session') def django_db_modify_db_settings(): pass @pytest.fixture(scope='session') def pytest_configure(): settings.configure( INSTALLED_APPS=[ 'django.contrib.contenttypes', 'django.contrib.auth', ], DATABASES=dict(default=dict( ENGINE='django.db.backends.sqlite3', NAME=':memory:', )) ) test_db.py: import pytest from django.contrib.auth.models import Group @pytest.mark.parametrize('name,count', [ ('test', 1,), ('staff', 2), ]) @pytest.mark.django_db(transaction=True) def test_group(name, count): Group.objects.create(name=name) assert Group.objects.count() == count py.test output: $ py.test test_db.py ============================================ test session starts ============================================= platform linux -- Python 3.7.2, pytest-3.10.1, py-1.5.4, pluggy-0.7.1 rootdir: /home/jpic/src/djcli, inifile: plugins: mock-1.5.0, django-3.4.2, cov-2.6.0 collected 2 items test_db.py .F [100%] ================================================== FAILURES ================================================== ____________________________________________ test_group[staff-2] _____________________________________________ name = 'staff', count = 2 @pytest.mark.parametrize('name,count', [ ('test', 1,), ('staff', 2), ]) @pytest.mark.django_db(transaction=True) def test_group(name, count): Group.objects.create(name=name) > assert Group.objects.count() == count E assert 1 == 2 E + where 1 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98>>() E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98>> = <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98>.count E + where <django.contrib.auth.models.GroupManager object at 0x7f351e01ef98> = Group.objects test_db.py:12: AssertionError As you can see, the first test passes which means that one group was created and that one group was left. In the second test you can see the test fail because the … -
Django Rest Framework RetreiveAPIView get() returned 2 results
I have a django project with a django rest framework. I am trying to use the Retreive API View to return the members details. I want to grab all the member records based on a parameter that is passed in teh url with the groups name. I tried using the .get() and .filter(). The .get() returned an error of returning more than 2 items. The .filter() is not part of the dict. I tried .list and .retrieve How can I retreive the data objects based with more than 1 item. Here is my View that I am calling. class MemberDetailView(RetrieveAPIView): queryset = Member.objects.all() serializer_class = MemberSerializer def get_object(self): return self.queryset.filter(group__name=self.kwargs.filter('name')) model class Member(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) host = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.group.name + ' - ' + self.user.username urls path('members/', MemberListView.as_view()), path('members/<name>', MemberDetailView.as_view()), -
Docker Compose, Django: role "_" does not exist
Context I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named teddycrepineau (as opposed to using the default postgres user and db). System/Version python: 3.7 django: 2.1 OS: Mac OS High Sierra What error am I getting When running docker-compose up with my custom role and db, I am getting the following error django.db.utils.OperationalError: FATAL: role "teddycrepineau" does not exist. When running the same command with the default role and db postgres Django is able to start normally. My understanding was that running docker-compose up would create the role and db passed as environment variable. What I have tried so far I read multiple threat on this site, GitHub, and docker: tried to delete my container and rebuilt it with formatting as suggested here Went through this GitHub issue Tried to move my environment variable from .env file the environment inside my docker-compose.yml file and rebuild my container Files docker-compose.yml version: '3' volumes: postgres_data: {} services: postgres: image: postgres volumes: - postgres_data:/var/lib/postgresql/data env_file: .env ports: - "5432" django: build: context: teddycrepineau-backend dockerfile: … -
Django Celery: Function only runs once within True While Loop
Background: I am using celery to run a python script within a django environment to measure weight from a load cell using a raspberry pi. I am measuring a bottle of water and it relays the information to the webserver. The python code below runs perfectly when ran in a python environment outside of celery, but when it is ran by a celery worker, the value from the hx.get_weight(5) function within the while loop never changes after the first iteration. This coded runs fine and the hx.get_weight(5) returns a different value everytime (weight is changing) when not ran by a celery worker. So, I believe it is celery that is causing this issue. import RPi.GPIO as GPIO import time import sys from .hx711 import HX711, L287 app = Celery('robobud', broker='redis://localhost:6379/0') log = logging.getLogger(__name__) @app.task async def pump(program_id, amount1, amount2): def cleanAndExit(): print ("Cleaning...") GPIO.cleanup() print ("Bye!") sys.exit() ### Weight Class hx = HX711(5, 6 ) hx.set_reading_format("LSB", "MSB") hx.set_reference_unit(112) hx.reset() hx.tare() ### Weight while True: try: val = hx.get_weight(5) print val hx.power_down() hx.power_up() time.sleep(1) -
Django link tableCheckBoxColumn to DB entry
I have a model class MyModel(models.Model): enabled = models.BooleanField(default=False) col_1 = model.CharField(max_length=20) col_2 = model.CharField(max_length=20) ... and a table class MyTable(table.Tables) enabled = tables.CheckBoxColumn(accessor='enabled') col_1 = tables.Column() col_2 = tables.Column() ... In my view I later get the queryset as a dataframe, do stuff with them and render them def index(request): context = dict() template = 'myindex/index.html' entries= MyModel.objects.all() df = dpd.read_frame(entries) ... do stuff with df ... context['my_table'] = MyTable(df.to_dict(orient='records')) return render(request, template, context) Which I then render {% load django_tables2 %} <html> <body> {% render_table table %} </body> </html> I am looking for a way to update the database when the checkboxes get clicked. So far, the checkboxes dont even take the values from the database but are all unchecked. Any pointers on what a good way is to achieve this? Thanks -
Django - How to update model fields in django admin?
How do I set my current form to update the model fields in the django admin on form submit based on the current logged in user and not repeat form submissions in the django admin? This may be a stupid question but I'm new to django. Any help i gladly appreciated, Cheers Screenshot user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=CustomUser) user_profile/views.py from django.http import HttpResponse, … -
items components in nativescript not populating the response from django api
I have simple django api which provide a list of movies title with their ids. I have created a movies service in type script which performs the get operation and get the list of movies title and id. In native script I have two files, items.component.ts import { Component, OnInit } from "@angular/core"; import { MovieService } from "../services/movie.service"; @Component({ selector: "ns-items", moduleId: module.id, templateUrl: "./items.component.html", providers: [MovieService] }) export class ItemsComponent implements OnInit { items; constructor(private movieService: MovieService) { } ngOnInit(): void { this.movieService.getMovies().subscribe( movies => { this.items = movies; console.log(movies); }, error => { console.log('error', error); } ); } } and items.component.html <ActionBar title="Movie Rater App" class="action-bar"> </ActionBar> <StackLayout class="page"> <ListView [items]="items" class="list-group"> <ng-template let-item="item"> <Label [nsRouterLink]="['/item', item.id]" [text]="item.title" class="list-group-item"></Label> </ng-template> </ListView> </StackLayout> I am getting blank screen on the app in the emulator - just the action bar title. No exception in logs I validated API is running fine and even I can see the response in console (i.e. output of console.log(movies)). Any help will be appreciated. -
Django nested inlines
I'm working on a custom Django CMS plugin and encountered a situation where I need nested inlines. Below are my model structures. class Link(NavLink): card = models.ForeignKey('CardPanel', related_name='card_links') class CardPanel(models.Model): title = models.CharField(max_length=50) image = FilerImageField(null=True, blank=True, related_name="navigation_vertical_link_image") link_description = HTMLField(blank=True, null=True, max_length=150) button_link_internal = PageField(blank=True, null=True) button_link_external = models.URLField(blank=True, null=True) plugin = models.ForeignKey('Panel') class Panel(CMSPlugin): pass What I ideally need is nested inlines. So as Link model has m:1 relationship with CardPanel and CardPanel has m:1 relationship with the Panel model, I want to be able to add multiple CardPanels containing multiple Link models. What is the best way achieving this through the ModelAdmin in Django? -
Append to QuerySet Items
Item Model (represents a product, like a MacBook) class Item(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL) introduction = models.DateField(auto_now=True) is_retired = models.BooleanField(default=False) tags = models.ManyToManyField(Tag) def __str__(self): return self.name OnHand Model (represents a serialized MacBook) class OnHand(models.Model): name = models.CharField(max_length=100) serial = models.CharField(max_length=80) asset = models.CharField(max_length=20) product = models.ForeignKey(Item, blank=True, null=True, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag) def __str__(self): return self.serial Index View Index Function def index(request): items = Item.objects.all() context = { 'items':items, } print(items) return render(request, 'index.html', context) Template/Table <table class="table table-hover"> <thead class="thead-light"> <tr> <th>Item Id</th> <th>Title</th> <th>Manufacturer</th> <th>On Hand</th> <th>Category Id</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.pk }}</td> <td>{{ item.name }}</td> <td>{{ item.manufacturer }}</td> <td>{{ item.quanity }}</td> </tr> {% endfor %} </tbody> </table> This application is an Inventory Management System which can take in Items such as a MacBook Pro or iPhone 6, and OnHands which are serialized instances of these Items. In my Index Function I am passing the result of an all() query to the Index View in context. I can query OnHand.objects.filter(product_id=item.pk) to get the quanity of each Item, however, in my current way of doing things I'm unsure how I can pass … -
Specify django-rest-framework field for serializer after request?
I've got the following code: models.py class Interview(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text="The Primary Key of the Interview") organization = models.ForeignKey(Organization, on_delete=models.CASCADE, help_text="The Primary Key of the Organization in the interview") question = name = models.CharField(max_length=200, help_text="The Question") serializers.py class InterviewSerializer(serializers.ModelSerializer): class Meta: model = Interview fields = ('organization', 'question') views.py class InterviewViewset(viewsets.ModelViewSet): """ API endpoint that allows Interviews to be viewed or edited. """ serializer_class = InterviewSerializer Right now, the request body to create an interview requires these fields: { "organization": "string", "question": "string" } I'd like the organization for the Interview to automatically be set to the current users organization (request.user.Organization - I've got a custom User model). How can I do this elegantly for my viewset? -
My definiton (loop) doesn't work other pages
I view my categories on my navbar using loop. Navbar is include in layout and layout extended in all templates. I put loop in navbar for showing categories. If I put my context to index definition It is working, but how can I show my loop at all pages? I think I need global definiton. Mine is Django 2.1.2, Python 3.5 view.py: def index(request): products = Product.objects.filter() catloops = Category.objects.filter() context = { "products":products, "catloops":catloops, } return render(request,"index.html", context) def cat_nav(request): catloops = Category.objects.filter() context = { "catloops":catloops, } return render(render, "????", context) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('',views.index, name="index"), path('about/',views.about, name="about"), path('products/',include("product.urls")), path('user/',include("user.urls")), path('products/',views.products, name="products"), path('myorders/',views.myorders, name="myorders"), path('dashboard/',views.dashboard, name="dashboard"), path('myprofile/',views.myprofile, name="myprofile"), path('????',views.cat_nav, name="cat_nav"), #user/register.. geldiğinde git user app'inden al ] navbar.html: <li class="nav-item dropdown menu-large"><a href="#" data-toggle="dropdown" class="dropdown-toggle">Categories <b class="caret"></b></a> <ul class="dropdown-menu megamenu"> <li> <div class="row"> <div class="col-lg-6"><img src="{% static 'img/template-homepage.png' %}" alt="" class="img-fluid d-none d-lg-block"></div> <div class="col-lg-3 col-md-6"> <h5>Used Products</h5> <ul class="list-unstyled mb-3"> {% for category in catloops %} <li class="dropdown-item"><a href="/products" class="nav-link">{{category.category_name}}</a></li> {% endfor %} If I put my context to index definition It is working, but when I go to other pages (urls) I can't see my categories. -
How do I write a Django ORM query that searches for a value that is close but doesn't exceed a certain other value?
I'm using Python 3.7 with Postgres 9.5. I would like to write a Django ORM query if possible. I have the below model class PageStat(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, ) elapsed_time = models.IntegerField(default=0) score = models.IntegerField(default=0) What I would like to do is write a query that, for a given article and elapsed time (an integer in seconds), I would like to write a query taht returns the PageStat object with the greatest elapsed time value that doesn't exceed the argument. So, for example, if my table had these values article_id elapsed_time ================== 1 10 1 20 1 30 2 15 And I did a search with article ID "1" and elapsed time" 15", I would like to get back the first row (where article_id = 1 and elapsed_time = 10), since "10" is the greatest value that is still less than 15. I know how to write a query for just finding the stat with the article, PageStat.objects.filter(article=article) but I don't know how to factor in the time value. -
Model field missing in admin
The invoice_date field on one of my models is not showing up in my admin. invoice_date = models.DateField(auto_now=True, auto_now_add=False, null=True, blank=True) I've tried the following: renaming the field running makemigrations/migrations restarting the server deleting cookies I can successfully write to the field and pull data from it, so it appears to be there and functioning as desired. I just can't see it in the admin. I have no special code in my admin.py. I've just registered the model admin.py from userorders.models import UserCartItem admin.site.register(UserCart) Any suggestions are welcome! Thanks! -
My django form returns empty cleaned_data
I have a simple Form, view and a html that renders the form. but the problem is that the form always returns form.is_valid == False. So I have checked the cleaned data but I noticed that self.cleaned_data returns an empty list. Here is the relevant code: class GraphForm(forms.Form): from_month = forms.DateField(widget=forms.Select(choices=MONTHS)) from_year = forms.DateField(widget=forms.Select(choices=YEARS)) to_month = forms.DateField(widget=forms.Select(choices=MONTHS)) to_year = forms.DateField(widget=forms.Select(choices=YEARS)) def clean(self): return self.cleaned_data <<< will always stay be empty def showgraph(request): if request.method == 'POST': form = GraphForm(request.POST) if form.is_valid(): >>> will never happen <<< ... ... ... else: form = GraphForm() return render(request, 'graph.html', {"form": form}) <form method="post"> {% csrf_token %} {{ form.from_month }} {{ form.from_year }} <br> {{ form.to_month }} {{ form.to_year }} <br> <p align="center"> <button type="submit" class="btn btn-primary">send</button> </p> </form> Can anyone help with this peculiar problem?