Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't reduce the height of the textbox
Can't override and reduce the height of a bootstrap textbox. <div class="form-group row"> <label class="col-xl-3">Posted Speed Limit (mph)</label><input type="text" class="col-xl-1 ps" autocomplete="off" id="sl" onkeydown="return keyval(event)" onkeyup="return valkey(event)" name="num3" required="required"><span id="rspan" class="rspan"><span>&#9888;</span>Enter a numeric value > 0 and ≤ 90</span></input> </div> The above is my input tag and below is the css for class = "ps" .ps{ min-height: 2%; } I can't increase or reduce the height. when it comes to the width, I can increase it but can't reduce it. How do i solve this? -
Django: how to define a one-to-one relationship to a table in admin?
Good day, friends! I am trying to define a one-to-one relationship to an user in django admin. Below is my code in models.py in an app: from django.db import models class Tutor(models.Model): account = models.OneToOneField([A User from Admin]) # what should I code here? first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) What should I write instead of [A User from Admin]? Thanks. -
Javascript grade computation
How to compute grades using JavaScript in dynamic table <table id="blacklistgrid"> <tr id="tr"> <th id="th">Students Name</th> <th>Average</th> </tr> {% for student in teacherStudents %} <tr id="tr2"> <td id="td">{{ student.Students_Enrollment_Records.Student_Users }}</td> </tr> {% endfor %} </table> <button type="button" value="" class="save" onclick="doTheInsert()" title="Insert New Cell" id="save">&plus;&nbsp;Insert New Cell</button> <button type="button" value="" class="save" onclick="undoTheInsert()" title="Undo Recent Action" id="unsave">&times;&nbsp;Undo Recent Action</button> <script> function doTheInsert(){ let header=$("tr#tr"); // same as $.find("tr[id='tr2']") $('#th').after("<th data-id='header' id='header'><input type='date'></th>"); let rows=$("tr#tr2"); rows.append("<td data-id='row' id='newRows'><input type='text' name='needtocompute' id='number' /></td>"); } </script> after the teacher input the grades of the students it will automatic display the results in the average please help me -
i want to install Bookmark but cant't install... i don know why can't installing
i tried to 'pip install Bookmark(and opencv) ' but can't installing in Pycharm Terminal ( Professional and Communiy) i don't understand why dont install. plz help me my python version is 3.8.1 64 bit ( also try 3.7.6 64 bit) (venv) C:\Users\USER\PycharmProjects\untitled>pip install Bookmark Collecting Bookmark Could not find a version that satisfies the requirement Bookmark (from versions: ) No matching distribution found for Bookmark [enter image description here][1] -
How to update Cookiecutter Django config for existing project?
I have been building a project on top of cookiecutter django (https://github.com/pydanny/cookiecutter-django), with Celery turned off in the cookiecutter generation settings. However, now I'm finding I need Celery. Is there a way I can flip a config, turn Celery on, and re-generate boilerplate in this current project? Otherwise, what I plan to do is create a new cookiecutter project with the new settings and then inspect files and differences and import changes by hand (which is tedious and potentially imperfect). -
How to get variable from PHP file in Django(python) subprocess?
There is a php file like this. /* main_app/test.php */ /* I can't modify this file. */ <? $test_a = "this is test a."; $test_b = "this is test b."; $test_c = "this is test c."; ?> and my python(views.py) code is def point_charge(request): import subprocess proc = subprocess.Popen("php /main_app/test.php", shell=True, stdout=subprocess.PIPE) script_response = proc.stdout.read() print(script_response) return render(request, 'main_app/sub_pointcharge.html') I want to get the value of "test_a" from "python print". The code I expect is like.. print(script_response.test_a) this is test a. Can I? thank you. -
Cannot log on in Django admin page
After using python manage.py createsuperuser to create an administrator user in Django 3.0.2, I cannot log on in the default admin page with that user. The server will stop once I enter the correct username and password. Then I got some error messages on terminal. [07/Jan/2020 09:24:22] "GET /admin/ HTTP/1.1" 302 0 [07/Jan/2020 09:24:23] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 [07/Jan/2020 09:24:23] "GET /static/admin/css/base.css HTTP/1.1" 304 0 [07/Jan/2020 09:24:23] "GET /static/admin/css/login.css HTTP/1.1" 304 0 [07/Jan/2020 09:24:23] "GET /static/admin/css/responsive.css HTTP/1.1" 304 0 [07/Jan/2020 09:24:23] "GET /static/admin/css/fonts.css HTTP/1.1" 304 0 [07/Jan/2020 09:24:23] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 304 0 [07/Jan/2020 09:24:23] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 304 0 [07/Jan/2020 09:24:29] "POST /admin/login/?next=/admin/ HTTP/1.1" 200 2074 [07/Jan/2020 09:24:34] "POST /admin/login/?next=/admin/ HTTP/1.1" 200 2074 [07/Jan/2020 09:24:39] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Process finished with exit code -1 Sometimes, the server will stop even just after typing 127.0.0.1:8000/admin, and no error messages printed. But, default admin page works fine with Django 2.0. Currently, I am using Python 3.7 and Django 3.0.2, and my IDE is PyCharm. How to solve this problem or is it a bug with Django 3.0.2? -
Django Reportlab a list in list of lists isn't rendering
I am currently working on a project for my school. I need to generate a pdf file from a database that shows which classes have substitutions(if a teacher ill or etc.). I am using Django with Reportlab. Each class has to have its own table. This is my code so far: def some_view(request): elems = [] static_data = [['Datum', 'Tag', 'Pos', 'Lehrer', 'Fach', 'Raum', 'Klasse', 'Vertreter', 'Info', 'Art'], ] buffer = io.BytesIO() pdf = SimpleDocTemplate( buffer, pagesize=landscape(A4), ) substitution = Substitution.objects.all().values('klasse').distinct() data = [] i = 0 while len(substitution) > i: x = Substitution.objects.filter(klasse=substitution[i]['klasse']) i = i + 1 data = static_data + data for s in x: data = [ [s.date, s.date, s.period, s.absent_teacher, s.subject, s.room_name, s.klasse, s.substituting_teacher, s.substitution_message, s.substitution_kind], ] table = Table(data) elems.append(table) if len(substitution) <= i: pdf.build(elems) buffer.seek(0) return FileResponse(buffer, as_attachment=False, filename='hello.pdf') The code already generates the pdf and the substitution schedule, but I want to have the data from static_data = [['Datum', 'Tag', 'Pos', 'Lehrer', 'Fach', 'Raum', 'Klasse', 'Vertreter', 'Info', 'Art'], ] before every table(for better readability). I am trying to do this with data = static_data + data in the while loop (because every class can have multiple substitutions) but it is not adding … -
Change Image Source Without Reloading Page Using Django
I am trying to change an image's source dynamically when the user clicks on the element without reloading the page. If I understand correctly, an image's source needs to be assigned a value in relation to Django's static folder, for example "{% static 'images\settingsIcon.png' %}"; However, the {% ... %} expression only seems to get evaluated when the page loads and so the source cannot be found if I change it dynamically with myImgElement.src = "{% static 'images\settingsIcon.png' %}"; Is there a way to dynamically change the image source to a file inside Django's static directory? -
Django template lighbox2 pop-up
I am trying to integrate lightbox2 to have photo gallery just like -> https://lokeshdhakar.com/projects/lightbox2/ I am able to achieve the functionality like , forward arrow takes to next picture , and grouping the picture under one 'data-lightbox', However my problem is whenever i click the picture, it doesn't come as a pop-up , it loads at the end of the page. Looking forward to quick solutions for it :) -
Cannot resolve keyword 'is_active' into field
Trying to make a password reset view. I'm using the auth_views built in views ie PasswordResetView and PasswordResetConfirmView for resetting password. However I was getting this error Cannot resolve keyword 'is_active' into field. Choices are: active, admin, email, first_name, id, last_login, last_name, logentry, password, staff, timetables . Tried changing active to is_active and getting this error. django.core.exceptions.FieldError: Unknown field(s) (active) specified for User Not able to make migrations class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_first_name(self): if self.first_name: return self.first_name return self.email def get_last_name(self): return self.last_name def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.is_active -
Django rest framework authentication database error
I am trying to implement the django rest framework in my current project. The api engine is working with no security. I am trying to follow the steps given in the authentication page of django rest framework to add the authentication. When I am adding the following section to the settings.py, I get no error: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } but when I am adding 'rest_framework.authtoken' to the INSTALLED_APPS, and run the server, I get the follwing message: You have 2 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): authtoken. Run 'python manage.py migrate' to apply them. Then I tried running python manage.py migrate but I get the following errors: (raiotic-venv) username@username-VirtualBox:~/Servers/Repositories/raiotic-venv/raiotic$ python manage.py migrate Operations to perform: Apply all migrations: MainApp, admin, auth, authtoken, contenttypes, sessions Running migrations: Applying authtoken.0001_initial...Traceback (most recent call last): File "/home/username/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) File "/home/username/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 381, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: attempt to write a readonly database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File … -
LDAP Group Search needs Distinguished Name with django-auth-ldap Bind as User with Userid and Password
Problem: Binding and Authenticating as Userid at domain and then attempting to conduct a LDAP Group Search needs a variable that contains the Distinguished Name of the authenticated user. Needed: Variable containing user's Active Directory Distinguished Name of the authenticated user even when authenticating with userid and domain. Description: LDAP Group Search requires Distinguished Name of the user to be provided to LDAPSearch, however, when using django-auth-ldap to Active Directory with AUTH_LDAP_BIND_AS_AUTHENTICATING_USER=True and log in using Userid@domain as the format a variable containing the Distinguished Name of the authenticated user is needed to conduct the Group Search using LDAPSearch. In the use case described the django-auth-ldap %(user)s variable contains the userid. Output from Django console in development indicates successful binding to Active Directory when the Populating Django user text appears, then the LDAP error indicates improper Distinguished Name when attempting without the complete users Distinguished Name in the search. Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Populating Django user testuser search_s('testuser@test.local', 0, '(objectClass=*)') raised INVALID_DN_SYNTAX({'desc': 'Invalid DN syntax', 'info': "0000208F: NameErr: DSID-03100225, problem 2006 (BAD_NAME), data 8350, best match of:\n\t'testuser@test.local'\n"},) Versions of software Python 3.6.3, Django 3.0.1, django-auth-ldap 2.1.0 settings.py from os import environ, path import ldap … -
Rendering Received Webhook Payload by Django Views
Dev Platform: Python 3.6.2 Django 3.0 Windows 10 VScode Problem: I'm not able to render the received webhook payload on the django template via same view method or by redirect. Also I'm not able to use django sessions variable to pass payload data to another view. Seems like no session exist as per the print statements. Looks like I'm missing something cirtical. Details: settings.py My sessions middleware and installed app settings are properly set as well for cookie based sessions. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' I've configured my webhook url on mailchimp after exposing my local dev server using ngrok. For example 34nghirt345.ngrok.io/webhook and also in my url config as follows: urls.py path('webhook/', views.my_webhook_view), path('webhook/<str:some_id>/', views.webhook_renderer, name ="url_webhook_renderer"), I'm receiving webhook payload from mailchimp at the configured url path and is able to process the payload within the respective view method. views.py @csrf_exempt def my_webhook_view(request): # Mailchimp webhook receiver for mailchimp batch operations. context = {} if request.method == 'POST': print('Webhook Payload Received') logger.debug(f"Some ID: {request.POST.get('data[id]')}") payload_dict = {k:v for k,v in request.POST.items()} logger.debug(f"Dict of POST DATA: {payload_dict}") context … -
Rendering Received Webhook Payload by Django Views
Dev Platform: Python 3.6.2 Django 3.0 Windows 10 VScode Problem: I'm not able to render the received webhook payload on the django template via same view method or by redirect. Also I'm not able to use django sessions variable to pass payload data to another view. Seems like no session exist as per the print statements. Looks like I'm missing something cirtical. Details: settings.py My sessions middleware and installed app settings are properly set as well for cookie based sessions. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' I've configured my webhook url on mailchimp after exposing my local dev server using ngrok. For example 34nghirt345.ngrok.io/webhook and also in my url config as follows: urls.py path('webhook/', views.my_webhook_view), path('webhook/<str:some_id>/', views.webhook_renderer, name ="url_webhook_renderer"), I'm receiving webhook payload from mailchimp at the configured url path and is able to process the payload within the respective view method. views.py @csrf_exempt def my_webhook_view(request): # Mailchimp webhook receiver for mailchimp batch operations. context = {} if request.method == 'POST': print('Webhook Payload Received') logger.debug(f"Some ID: {request.POST.get('data[id]')}") payload_dict = {k:v for k,v in request.POST.items()} logger.debug(f"Dict of POST DATA: {payload_dict}") context … -
How to access model verbose_name in CreateView
When I want to access a model's verbose_name in a UpdateView or DetailView I can just use: self.object._meta.verbose_name However when using the CreateView the object obviously doesn't exist. How can I access the model verbose_name and pass it to def get_context_data(self)? Example: class CompanyCreate(CreateView): """Create company.""" model = Company def get_context_data(self): context = super(CreateView, self).get_context_data() context['model_name'] = self._meta.verbose_name return context -
Sending python processed Datatable data through ajax api call
I would like to implement server side processing with my Datatables in Django. The problem is that in each row of my table, I would like to use some python processing or logic to do a reverse lookup (as shown in my html) or some other operation. I am not sure how to send anything other than raw db data through my ajax call with my python api. What would my api look like, or if not handled by the api, what changes would I need to make to send my table over ajax? models.py class Test(models.Model): test_name = models.CharField(max_length=128) class FeatureDetail(models.Model): tests = models.ManyToManyField('Test', related_name='test_details', default='', blank=True) number = models.PositiveIntegerField(blank=True, null=True) template.html <table class="table table-bordered table-striped" id="dt-summary" width="100%" cellspacing="0"> <thead> <tr> <th></th> <th>Test Name</th> <th>Feature Number</th> </tr> </thead> <tbody> {% for test in test_list %} <tr> <td></td> <td>{{ test.test_name }}</td> {% with feature=test.test_details.all.0 %} <td>{{ feature.number }}</td> {% endwith %} </tr> {% endfor %} </tbody> </table> dttb.js var table2 = $('#dt-summary').DataTable( { "aLengthMenu": [ [25, 50, 100, 500, ], // -1], [25, 50, 100, 500, ] //"All"] ], "paging": true, "responsive": true, "processing": true, "serverSide": true, "ajax": { url: "{% url 'app:summary_json' %}", -
Brython vs JS Performance
Actually I am a Working in Python - Django. So I just heard that we can also run Python (Brython) in Browser instead of JS Code however it is just translating into JS but it's Still easier to code Python. So do the Performance remains same or there are some major difference because I am going to use Ajax alot. I need to know does that easy code worth it or not. -
Django Rest Framework ignore day, hour, minute, etc. for a DateField or DateTimeField
My app allows users to have one budget per day. I have everything (models, serializers, APIs) working with the models.DateField so that hours, minutes, etc. are ignored. Now I want to go even more coarse-grained and only allow one budget per month (i.e. ignore days). No need to worry about existing data. I'm okay with either 1) ignoring the day value in any POST/GET/etc requests or 2) returning a 400 when POSTing to a day other than the first (e.g. {'date':'2020-01-02', ...} would fail) How can I do this at the API, serializer, or Django model level? This requirement may change in the future, but I'm just looking for the easiest implementation for now. -
Getting reverse relationship model values django
I have the following models: class RestaurantItemImages(models.Model): restauraunt_item = models.ForeignKey('RestaurantItem',on_delete=models.CASCADE) image = models.ImageField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.restauraunt_item.name class RestaurantItem(models.Model): name = models.CharField(max_length=255) description = models.TextField() price = models.FloatField() restauraunt = models.ForeignKey('Restauraunt',on_delete=models.CASCADE) featured = models.BooleanField(default=False) popular = models.BooleanField(default=False) menu = models.ManyToManyField('MenuType') def __str__(self): return self.name I am using the following query to fetch details in my API view which returns the result as follows: featured_items = RestaurantItem.objects.filter(restauraunt__slug=slug).values('name','price','restaurantitemimages__image') "featured_items": [ { "name": "Lo Mein Lunch Special", "price": 700.0, "restaurantitemimages__image": "hero_WlE875w.jpg" }, { "name": "Lo Mein Lunch Special", "price": 700.0, "restaurantitemimages__image": "ASQ.png" }, { "name": "Boneless Spare Ribs Lunch Special", "price": 100.0, "restaurantitemimages__image": null }, { "name": "Vegetable Roll (1)", "price": 213.0, "restaurantitemimages__image": null } ] If you see the same item is being repeated multiple times for different images so is there a way i can have all the images within a single object. I have looked at prefetch_related too but it did not make sense to me in this case. -
Updating django object
I'm writing django website connected with web scraping and I stopped at updating my Driver object. I don't know why it doesn't work properly. Here is some HTML code. <form action="{% url 'update' %}" method="post"> {% csrf_token %} {% for driver in new_drivers %} <label for="{{ driver.time }}">{{ driver.driver_name }}</label> <input required type="radio" name="driver" value="{{ driver.time }}" id="{{ driver.time }}"> {% endfor %} <input required name="card" type="text" minlength="6" maxlength="6"> <button>START</button> My view. def update_driver(request): if request.method == "POST": update_form = UpdateForm(request.POST) if update_form.is_valid(): card = update_form.cleaned_data['card'] time = update_form.cleaned_data['driver'] driver = Driver.objects.filter(time=time).first driver.card = card driver.save() return redirect(index) And forms.py class UpdateForm(ModelForm): class Meta: model = Driver fields = ["card", "score", "time", "is_new"] Thank for you help in advance! -
How to overcome a ImportError?
In my project I want to realize a custom user model which is included in my users app and included to my settings, that has an entry for a project that is currently worked on. So my user model should look like this from django.db import models from django.contrib.auth.models import AbstractUser from api.models import Project class User(AbstractUser): current_project = models.ForeignKey( Project, on_delete=models.SET_NULL, null=True, ) While my Project model in the api app basically looks like from django.db import models from users.models import User class Project(models.Model): name = models.CharField(max_length=50) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="api_project_author", related_query_name="api_project_authors" ) edited_at = models.DateTimeField(blank=True, null=True) editor = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True, related_name="api_project_editor", related_query_name="api_project_editors" ) However if I run this I get an ImportError: cannot import name 'User' from 'users.models' which obviously happens because of the reference in my User model which then tries to import the User model because of its other references. So my idea was to create a new UserSetting model in the api app like class UserSetting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True) However I am not sure how to handle such kind of problems properly or avoid them. I am … -
Django migration fails when ExclusionConstraint is present
Iam trying to integrate an ExclusionConstraint into my model but when I try to migrate my PostgreSQL database it is failing. It is even failing when i try to implement the sample-code given by the Documentation (https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/constraints/) Iam running Django 3.0.2 and PostgreSQL 12 when I run the migration i get the following error: me@local % python3 manage.py makemigrations Migrations for 'app': app/migrations/0012_auto_20200106_1941.py - Create model Room - Create model Reservation - Create constraint exclude_overlapping_reservations on model reservation me@local % python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, hr, sessions, app Running migrations: Applying app.0012_auto_20200106_1941...Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedObject: data type integer has no default operator class for access method "gist" HINT: You must specify an operator class for the index or define a default operator class for the data type. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", … -
How do I include columns properly in a GROUP BY clause of my Django aggregate query?
I'm using Django and Python 3.7. I have the following model ... class ArticleStat(models.Model): objects = ArticleStatManager() article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats') elapsed_time_in_seconds = models.IntegerField(default=0, null=False) score = models.FloatField(default=0, null=False) I want to write a MAX/GROUP BY query subject to certain conditions, so I tried this def get_current_articles(self, article): qset = ArticleStat.objects.values('article__path', 'article__title', 'score').filter( article__article=article).values('elapsed_time_in_seconds').annotate(\ max_date=Max('elapsed_time_in_seconds')) print(qset.query) return qset However, the resulting SQL does not include the values I want to use in my GROUP BY clause (notice that neither "article" nor "score" is in the GROUP BY) ... SELECT "myproject_articlestat"."elapsed_time_in_seconds", MAX("myproject_articlestat"."elapsed_time_in_seconds") AS "max_date" FROM "myproject_articlestat" INNER JOIN "myproject_article" ON ("myproject_articlestat"."article_id" = "myproject_article"."id") WHERE ("myproject_article"."article_id" = 2) GROUP BY "myproject_articlestat"."elapsed_time_in_seconds" How do I modify my Django query so that the resulting SQL looks like -
Why isn't user like notifications setting saving but all the others are?
I'm trying to let users choose what notifications they get and for some reason the like notification setting is not being saved but all the other settings are. Also, I have a ModelForm as the form (just check boxes) where the users set their preferences but no matter what the setting is (meaning, if message_notifications is set to False) the check box for that setting shows as True (Box stays checked) when going back to the notification preferences page. The debug print("Debug 115 l_n:",l_n)shows the correct value but when I redirect to a different page (where I have another debug showing all the settings after saving) everything but the like_notifications have been saved. The default for all of the notification settings is True, but I don't see how that could effect the like_notifications since everything but that changes. View ... if request.method == "POST": form = NotifForm(request.POST) if form.is_valid(): user = CustomUser.objects.filter(id=request.user.id) c_n = form.cleaned_data['comment_notifications'] t_n = form.cleaned_data['tag_notifications'] m_n = form.cleaned_data['message_notifications'] p_n = form.cleaned_data['post_notifications'] f_n = form.cleaned_data['new_follower_notifications'] l_n = form.cleaned_data['like_notifications'] print("Debug 115 l_n:",l_n) friend_n = form.cleaned_data['friend_request_notifications'] request.user.comment_notifications=c_n request.user.tag_notifications=t_n request.user.message_notifications=m_n request.user.post_notifications=p_n request.user.new_follower_notifications=f_n request.user.like_notification=l_n request.user.save() request.user.friend_request_notifications=f_n request.user.save() print("DEBUG 124; user-like:",request.user.like_notification) return redirect("home") else: form = NotifForm() request.user.print_notif_settings() return render(request, 'acc_manage/notif_preferences.html', {'form': form})