Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ManyToManyField object automatically saves itself
I am trying to create an Ecommerce website using Django. I have orderProducts as a ManyToMany field to the Cart object. The question is why whenever I create an OrderProduct object, any existing Cart automatically saves the orderProduct in itself. Here is my model: class OrderProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.product.name def delete_from_cart_url(self): return reverse("delete_from_cart", kwargs={ 'product_name' : self.product.name }) class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) products = models.ManyToManyField(OrderProduct) def __str__(self): return self.user.username This is the add_to_cart function, even when I commented out the cart.products.add code, OrderProduct is still added to the carts. def add_to_cart(request,product_id): product = get_object_or_404(Product,pk=product_id) order_product,created = OrderProduct.objects.get_or_create(product=product,user=request.user) cart_qs = Cart.objects.filter(user=request.user) if cart_qs.exists(): cart = cart_qs[0] if cart.products.filter(product__name=product.name).exists(): order_product.quantity += 1 order_product.save() else: return redirect("cart") #cart.products.add(order_product) return redirect("cart") else: cart = Cart.objects.create(user=request.user) #cart.products.add(order_product) return redirect("products") -
Django inlineformset_factory access child objects from parent
I have models ProductA and ProductB. and I have a form that can add productBs to As. class ProductBForm(forms.ModelForm): class Meta: model = ProductB exclude = () ProductBFormSet = inlineformset_factory( ProductA, ProductB, form= ProductBForm, fields=['city', 'country'], extra=3, can_delete=True ) Is there any way I could access ProductB objects from a view that has ProductA object? I'm using DetailView for this. -
best way to Implement Order scenario in e-commerce and keep Cart updated in django
I have to store orders with a foreign key relation to a product like this class Orders(models.Model): order_number = models.AutoField(primary_key=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) ordertime = models.DateTimeField(auto_now_add=True) customer= models.ForeignKey(Customer, on_delete=models.CASCADE) order_status = models.CharField(max_length=50) is_placed=models.BooleanField(default=False) and its have a relation with product 'Accommodation' like this class OrderAccommodation(models.Model): order=models.ForeignKey(Orders, on_delete=models.CASCADE) orderAccomodation = models.ForeignKey(Accommodation, on_delete=models.CASCADE) orderRoom = models.ForeignKey(Room, on_delete=models.CASCADE) roomQuantity=models.IntegerField(default=0) roomTotalPrice=models.DecimalField(max_digits=10, decimal_places=2) checkIn = models.DateField() checkOut = models.DateField() adult=models.IntegerField(default=0) child=models.IntegerField(default=0) customerFirstname=models.CharField(max_length=50, null=False, blank=False) customerLastname=models.CharField(max_length=50, null=False, blank=False) customerEmail=models.CharField(max_length=50, null=False, blank=False) customerMobile=models.CharField(max_length=50, null=False, blank=False) Now scenario is like 1 order can have many Accommodation products. when a user add accommodation to Order I save that and when user delete I am deleting from order with id. But this order is in cart until its not final .Is it good to save that all data in order table until its not checkout and paid ? should I create a new tables for cart or I am doing it right ? like just putting a field is_placed=false untill order is not placed -
How do you pass variables from an html file to a python file on a django webserver with Jinja?
I want to know how to pass a variable from an html file into a python script. For example, html file takes a variable from python, and then the user updates the variable on the website, then the html file sends the updated variable to the python script. I know sending looks like this, but what about receiving? from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'personal/home.html') def contact(request): return render(request, 'personal/basic.html',{'content':['If you would like to contact me, please email me.','dfdfdfy@gmail.com']}) -
How do I write a DRF Serializer that combines four models with foreign keys?
Good afternoon, I am confused about how to return the data I am after (or perhaps I have not set up the models efficiently). My app has Users and Groups. Each User is part of a group, each group has a leader and an ambassador (which are Users). To accomplish this, I set up the following models: class Groups(models.Model): group_name = models.CharField(max_length=35) group_description = models.CharField(max_length=255) def __str__(self): return "{}".format(self.group_name) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=35) group = models.ForeignKey(Groups, on_delete=models.CASCADE, related_name="group") class Ambassadors(models.Model): group = models.ForeignKey(Groups, on_delete=models.CASCADE, related_name="ambassador") ambassador = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="ambassador") class GroupLeaders(models.Model): group = models.ForeignKey(Groups, on_delete=models.CASCADE, related_name="leader") group_leader = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="leader") What I would like to return are the group fields along with the associated ID and name of the Ambassador and Leader for the group. I created a serializer for the Ambassador & GroupLeaders Models, then added them to the Groups serializer, but I am not really understanding what steps to take an how to set this up. Thanks for any guidance. BCBB -
Django - Failed to register a ServiceWorker
Trying to register a ServiceWorker inside a django served template: Inside base.html I have: <script> if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker .register('/static/js/sw.js/') .then(reg => console.log('Service Worker: Registered')) .catch(err => console.log(`Service Worker: Error: ${err}`)); }); } </script> However, console logs: Service Worker: Error: SecurityError: Failed to register a ServiceWorker for scope ('http://127.0.0.1:8000/static/js/sw.js/') with script ('http://127.0.0.1:8000/static/js/sw.js/'): The script has an unsupported MIME type ('text/plain'). Most of the answers here on SO seem to be related to serving the app via a node.js server (or related to create-react-app), and couldn't figure out to solve this with django. Does this works with a django server? Or is it impossible to test serviceworkers locally? -
Deployment django in iss 7
I'm new on django and I'm trying to deploy a Django Project in IIS and I'm getting some errors when I try to browse in. Can you help me solve this erros? features: IIS7/ Windows Server 2008 R2/ Python 3.7.4/ django 2.2.4 I'm using wfastcgi as interface. Follow the web.config file: <configuration> <system.webServer> <handlers> <remove name="DjangoAppIIS" /> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\nmcscript\appdata\local\programs\python\python37\python.exe|c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="firstsite.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\django\firstsite" /> <!-- Optional settings --> <add key="DJANGO_SETTINGS_MODULE" value="firstsite.settings" /> </appSettings> </configuration> Follow the errors below: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = import(module_name, fromlist=[name_list[0][0]]) File ".\firstsite\wsgi.py", line 16, in application = get_wsgi_application() File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\django\contrib\auth\models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\django\contrib\auth\base_user.py", line 7, in from … -
pip install doesnt add anything to pipFile or pipFile.lock
when I try to install a package to the Django with pip install terminal shows the package is installed and I can see the progress but nothing appear inside the Pipfile or Pipfile.lock. Steps that I followed: pip install elasticsearch-dsl package installed on the terminal (saw that multiple times) Requirement already satisfied: six in d:\development\pythonsetting\lib\site-packages (from elasticsearch-dsl) (1.12.0) Requirement already satisfied: python-dateutil in d:\development\pythonsetting\lib\site-packages (from elasticsearch-dsl) (2.8.0) Requirement already satisfied: elasticsearch<7.0.0,>=6.0.0 in d:\development\pythonsetting\lib\site-packages (from elasticsearch-dsl) (6.4.0) Requirement already satisfied: urllib3>=1.21.1 in d:\development\pythonsetting\lib\site-packages (from elasticsearch<7.0.0,>=6.0.0->elasticsearch-dsl) (1.25.7)``` checked my pipfile: name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] black = "*" pylint = "*" [packages] django = "*" djangorestframework = "*" django-rest-knox = "*" [requires] python_version = "3.7" [pipenv] allow_prereleases = true How can I add this package to my django project -
ListCreateAPIView: How can I cache a serialized QuerySet?
I have a DRF class with a single method get_queryset(). I would like to add caching to the serialized queryset by intercepting the request before get_queryset gets called, but after custom middleware/authentication has been run. Here is a trivial example of what I'm after: class FooList(generics.ListCreateAPIView) permission_classes = (permissions.IsAuthenticated,) serializer_class = FooSerializer def intercept_for_caching(self): user = self.request.meta_data['user'] cached_data = cache.get(f'FooStuff:{user.pk}') if cached_data: return Response(cached_data) else: new_data = ? # retrieve serialized queryset cache.set(f'FooStuff:{user.pk}', new_data) return Response(new_data) def get_queryset(self): user = self.request.meta_data['user'] return Foo.objects.filter(user=user) Are there any methods I can hook into? I am aware that cache_page is designed for this use case (https://www.django-rest-framework.org/api-guide/caching/), but I haven't been able to get it to work with our custom middeleware. -
Reverse not found with slug field
I am getting error while using get_absolute_url with slug field. Have tried few suggestions which is already exist in stack but didn't worked. Can anyone help me with this please. Please refer this link for traceback. models.py Codes in models. from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) draft = models.BooleanField(default=False) publish = models.DateTimeField(auto_now=False, auto_now_add=False) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="hieght_field") hieght_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updates = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def get_absolute_url(self): return reverse('post:detail', kwargs={'slug':self.slug}) Views.py codes in views. def post_list(request): queryset_list = Post.objects.active() if request.user.is_staff or request.user.is_superuser: queryset_list = Post.objects.all() query = request.GET.get('q') if query: queryset_list = queryset.filter( Q(title__icontains=query) ).distinct() context = { 'object_list':queryset_list, 'posts': page, "page_request_var": page_request_var, } return render(request, 'index.html', context) urls.py urls mapping. urlpatterns = [ path('detail/<slug:slug>/', views.detail, name='detail'), ] html page code in index.html {% for obj in object_list %} <div class="container"> <p class="card-text">{{obj.content|linebreaks|truncatechars:120}}</p> <a href="{{obj.get_absolute_url}}" class="btn btn-primary">View</a> </div> {% endfor %} -
I have changed the folder name containing my django app now I'm getting "OSError"
I have accidentally renamed my main folder containing django app and all the files now when I run the 'runserver' command I get the following traceback OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''. I even have changed the folder name back to original but I still am getting the same error. P.S. 'runserver' command was working fine before altering the name of the folder. -
How to test an UpdateView in Django?
I'm trying to test a view (UpdateView) in Django but this doesn't work. Is a view that is used to edit user first name and last name (basic). This is the view: class UserProfileEditView(LoginRequiredMixin, UpdateView): model = User template_name = 'user/edit.html' fields = ['first_name', 'last_name'] def get_success_url(self): redirect_to = self.request.GET.get( 'next', reverse('main:user_detail', args=[self.request.user.pk]) ) return redirect_to In the urls.py file I have this path: path( 'user/<pk>/edit/', views.UserProfileEditView.as_view(), name='user_edit' ), And lastly here is the test I've written where I would only like to test that a user can change his first name to blank but this doesn't work: class TestModel(TestCase): def test_blank_first_name(self): user = factories.UserFactory() post_data = { 'first_name': '', 'last_name': user.last_name } response = self.client.post( reverse('main:user_edit', kwargs={'pk': user.pk}), post_data ) self.assertEqual(response.status_code, 302) user.refresh_from_db() self.assertEqual(user.first_name, '') This is the error when I run python manage.py test: AssertionError: 'laugh' != '' It mean that the first_name didn't change from 'laugh' to '' like was expected. What do I do wrong? -
What does the post() method do on a DeletionMixin in the Django source code?
I am learning Django and trying to understand DeleteView from first principals. In the source code for the DeletionMixin there is both a delete method and a post method: class DeletionMixin: """Provide the ability to delete objects.""" success_url = None def delete(self, request, *args, **kwargs): """ Call the delete() method on the fetched object and then redirect to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect(success_url) # Add support for browsers which only accept GET and POST for now. def post(self, request, *args, **kwargs): return self.delete(request, *args, **kwargs) What is the difference between these two methods and when are they called? Is the delete() method only called on a request.GET? For example, am I correct that the delete method overrides the standard delete method on models.Model? Why is post used? For reference the other classes defined in the Django source code are here: class BaseDeleteView(DeletionMixin, BaseDetailView): """ Base view for deleting an object. Using this base class requires subclassing to provide a response mixin. """ class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView): """ View for deleting an object retrieved with self.get_object(), with a response rendered by a template. """ template_name_suffix = '_confirm_delete' Please could you help me understand the … -
Heroku oTree MTurk creating sessions takes too long
I have just deployed my oTree application on Heroku, and I would like to use it to create a MTurk HIT. Everything works fine when I create a session (Sessions -> Create New Session -> For MTurk) with a small number of participants or a small number of rounds. However, my application is supposed to have 96 participants (so, according to MTurk, 96x2 participants) and around 200 (or more) rounds. What happens is that my application is constantly stuck on the creating session page, with the bar going up and down, but not doing anything. I have let it run for hours, and it just did not succeed. The same happens if I use the create session command without MTurk. On the logs: heroku[web.1]: Process running mem=515M(100.8%) heroku[web.1]: Error R14 (Memory quota exceeded) ... heroku[web.1]: Error R14 (Memory quota exceeded) heroku[web.1]: Process running mem=666M(130.1%) And it just keeps increasing. I have seen this question, but I am not using gunicorn and heroku restart did nothing. I have never used Heroku before, so I am using this as procfile. web: otree runprodserver1of2 worker: otree runprodserver2of2 Is this correct? Do you have any suggestions? Could this be fixed by upgrading something on … -
How to set environment variables for django project ? [Beginner]
I know how to use with python dotenv. but i would like to know with django-environ. Like I would like to access with os.environ.get(''). I know how to access but doesn't know hot to set them. -
Different between RESTApi and backend
Recently i'm learning django and developing some simple applications, when uploading on github i got confused that what is the difference between backend and api according to me backed is used by frontend to render the data from database, to perform some calculations on the data, to interact with the database, to call relevant views/templates, to check authentication and some other stuff and front end is used to show that t=data to the user e.t.c. now my question is where the api comes into picture? Is it necessary to write a RESTFUL service for our web? -
django-environ dictionary format
I'm having a difficult time trying to understand how to write data to the .env file as to get a dictionary. The docs say this: dict (BAR=key=val;foo=1.1;baz=True) #environ.Env(BAR=(dict(value=unicode, cast=dict(foo=float,baz=bool)), {})) In my .env file i have something like this EMAIL=host=xx;port=xx;user=xx;pass=xx;tls=True However, i really don't know what to pass to the casting in the settings.py file -
Django Selenium TDD self.browser.get(self.live_server_url) error
I am learning TDD by the "Obey the testing goat book", but I am trying to do it with Django 3. If anyone knows it, I am at Chapter 6. My code is: class VisitorTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Chrome() self.browser.implicitly_wait(2) def tearDown(self): self.browser.quit() def test_starting(self): print(self.live_server_url) self.browser.get(self.live_server_url) and in console I am getting Creating test database for alias 'default'... System check identified no issues (0 silenced). DevTools listening on ws://127.0.0.1:52187/devtools/browser/e9a03a04-819e-40a3-a0e4-bd4133d8f6cb http://localhost:52180 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52204) ---------------------------------------- ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52202) Exception happened during processing of request from ('127.0.0.1', 52203) Traceback (most recent call last): Traceback (most recent call last): File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) Traceback (most recent call last): File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 724, in __init__ self.handle() File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socketserver.py", line 724, in __init__ self.handle() File "C:\Users\Alex\PycharmProjects\goat\lib\site-packages\django\core\servers\basehttp.py", line 172, in handle self.handle_one_request() File "C:\Users\Alex\PycharmProjects\goat\lib\site-packages\django\core\servers\basehttp.py", line 172, in handle self.handle_one_request() File "C:\Users\Alex\PycharmProjects\goat\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Alex\PycharmProjects\goat\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Alex\AppData\Local\Programs\Python\Python36\lib\socket.py", line … -
How to make changes to the database? (DRF)
In the model of the Post object, I have field created = models.DateTimeField field (auto_now_add = True) There is another field end_time, in which - today's date + 1 month in advance. That is, if a post was created, then it will have today's date in the created field (January 5, 2020), and in the end_time field it will be a month ahead (February 5, 2020). def next_month(): now = timezone.now() return now + relativedelta(months=+1) end_time = models.DateTimeField(default=next_month, blank=True, editable=False) To all this, I'm need to add the is_actual field, in which - @property def is_actual(self): return bool(self.end_time and self.end_time > now()) But in this case, I can not use the filter to display the fields, where is_actual == true. For me, a filter using this field is very important. What needs to be done so that I can apply a filter by the is_actual field? As far as I understand, here you need to make once a day, for example, changes to the database. But how? To write some kind of custom script, or to do it somehow using Django methods? -
FieldError at /admin/login/ after customizing default User model
So I customized my default User model because i didn't like the default fields the model had, i wanted to add my own fields and completely override the default. Now when ever i go to localhost:8000/admin/, I login and get this error: FieldError at /admin/login/ Cannot resolve keyword 'username' into field. Choices are: admin_email, admin_gender, admin_password, admin_position, admin_username, dateregistered, emailaddress, farmadministrator, farmemail, farmname, farmpassword, farmphonenumber, groups, id, is_active, is_staff, is_superuser, last_login, logentry, password, socialaccount, storefeedsale, storemedictaionsale, user_permissions The django traceback doesn't link the error back to my code code rather to some django code; Traceback: /home/thefixer/django_stuff/django_job/lib/python3.6/site-packages/allauth/account/auth_backends.py in authenticate ret = self._authenticate_by_username(**credentials) … ▶ Local vars /home/thefixer/django_stuff/django_job/lib/python3.6/site-packages/allauth/account/auth_backends.py in _authenticate_by_username user = filter_users_by_username(username).get() … ▶ Local vars /home/thefixer/django_stuff/django_job/lib/python3.6/site-packages/allauth/account/utils.py in filter_users_by_username ret = get_user_model().objects.filter(q) … ▶ Local vars so im very confused please i need help. my custom User model which i also renamed to recordBuddyUser; from django.db import models from django.utils import timezone from django.contrib.auth.models import ( PermissionsMixin, AbstractBaseUser, BaseUserManager, ) # Custom models to override django default User and handle all User intercations class User_manager(BaseUserManager): # companylogo, companyletterhead): def create_user(self, companyname, companyemail, companyadministrator, companyphonenumber, companypassword): companyemail = self.normalize_email(companyemail) user = self.model(companyname=companyname, companyemail=companyemail, companyadministrator=companyadministrator, companyphonenumber=companyphonenumber, companypassword=companypassword, ) # companylogo=companylogo, companyletterhead=companyletterhead # ) … -
Possible to use django authentication for standalone YouTrack
I love PyCharm, so I thought I'd give YouTrack a try. I used run-docker-container-as-service instruction, and I was able to create a service. I can start and stop the service with no issues. Using a browser, I was able to do configuration, I can create users, issues, etc. On the same system (Ubuntu 18.04.3 LTS) I'm also running a django application. I would like for my django application users to submit issues, check status on issues, and possibly update issues they have submitted. I want to make it as simple for my users as possible, so I would like to use django authentication for my YouTrack. That way, once a user is logged into my application, they don't need to go through a separate authentication process to use YouTrack. It seems YouTrack offers multiple different authentication methods, but I don't see a django option. Is it possible? -
Questions about django-haystack when using Solr as a search engine
When django-haystack uses Solr as a search engine, can it only search accurately? How can I fuzzy search? -
What is the best way to connect a JavaScript front end framework (like React or Vue) to a Rest API?
I'm building a single page web application with either React or Vue on the front end and a Django API on the backend. What is the best way to link the frontend with the API? Do I just host the front end and backend separately and submit HTTP requests to the API or is there a way to "bind"the frontend and backend into one single application? I'm interested in knowing what the best practices are. -
Count annotation adds unwanted group by statement for all fields
I want to generate the following query: select id, (select count(*) from B where B.x = A.x) as c from A Which should be simple enough with the Subquery expression. Except I get a group by statement added to my count query which I can't get rid of: from django.contrib.contenttypes.models import ContentType str(ContentType.objects.annotate(c=F('id')).values('c').query) # completely fine query with annotated field 'SELECT "django_content_type"."id" AS "c" FROM "django_content_type"' str(ContentType.objects.annotate(c=Count('*')).values('c').query) # gets group by for every single field out of nowhere 'SELECT COUNT(*) AS "c" FROM "django_content_type" GROUP BY "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model"' Which makes the result be [{'c': 1}, {'c': 1}, {'c': 1}, {'c': 1},...] instead of [{c:20}]. But subqueries have to have only one row of result to be usable. Since the query is supposed to be used in a subquery I can't use .count() or .aggregate() either since those evaluate instantly and complain about the usage of OuterRef expression. Example with subquery: str(ContentType.objects.annotate(fields=Subquery( Field.objects.filter(model_id=OuterRef('pk')).annotate(c=Count('*')).values('c') )).query) Generates SELECT "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model", (SELECT COUNT(*) AS "c" FROM "meta_field" U0 WHERE U0."model_id" = ("django_content_type"."id") GROUP BY U0."id", U0."model_id", U0."module", U0."name", U0."label", U0."widget", U0."visible", U0."readonly", U0."desc", U0."type", U0."type_model_id", U0."type_meta_id", U0."is_type_meta", U0."multi", U0."translatable", U0."conditions") AS "fields" FROM "django_content_type" Expected query: SELECT "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model", (SELECT COUNT(*) … -
how to work with two forms in django Detailview
I have a comment section in django blog and there are two forms one is for comment another is for reply to the comment but the comment form is working fine and reply form doesn't work! i was trying to do but getting error... IntegrityError at /page/9/ FOREIGN KEY constraint failed... appreciate to your help :) Thank you. views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" context_object_name = 'post' form = CommentForm() def get_object(self): obj = super().get_object() if self.request.user.is_authenticated: PostView.objects.get_or_create( user=self.request.user, post=obj ) return obj def get_context_data(self, **kwargs): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] context = super().get_context_data(**kwargs) context['most_recent'] = most_recent context['page_request_var'] = "page" context['category_count'] = category_count context['form'] = self.form return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) form = ReplyForm(request.POST)# how to work with this form like above from if form.is_valid(): post = self.get_object() form.instance.user = request.user form.instance.post = post form.save() return redirect(reverse("post-detail", kwargs={ 'pk': post.pk })) models.py class Reply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() comment = models.ForeignKey('Comment', related_name='replies',default=False, null=True, on_delete=models.CASCADE) def __str__(self): return self.content class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() post = models.ForeignKey('Post', related_name='comments', default=False, on_delete=models.CASCADE) def __str__(self): return self.content