Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django object of type 'method' has no len()
I just added pagination to a ListView in Django, but it is returning object of type 'method' has no len() error, even though I am overriding the get_queryset method and it is not returning anything different from the queryset. The view causing the error looks like this: class ProductList(ListView): paginate_by = 10 model = Product context_object_name = 'products' template_name = 'catalog/product/product_list.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def queryset(self): categories = Category.objects.filter(company=self.request.user.profile.company) return Product.objects.filter(category__in=categories) def get_context_data(self, **kwargs): context = super(ProductList, self).get_context_data(**kwargs) context['customers'] = Customer.objects.filter(company=self.request.user.profile.company) context['categories'] = Category.objects.filter(company=self.request.user.profile.company) return context How am I supposed to paginate with an overriden queryset without it showing this error? -
How can group this relations on Django Rest Framework
Currently, I've the next models: class Variant(models.Model): name = models.CharField('name', max_length=60) class VariantValue(models.Model): value = models.CharField('value', max_length=60) variant = models.ForeigKey('variant', to=Variant, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField('name', max_length=60) I want to get the next json result: { "name": "My product", "variants": [ { "variant_id": 1, "values": ["Value 1", "Value 2", "Value 3"] }, { "variant_id": 2, "values": ["Value 4", "Value 5", "Value 6"] }, ] } It's possible with a Serializer or do I've to make the json manually? I just have the next ModelSerializer: class ProductModelSerializer(serializers.ModelSerializer): variant_list = serializers.SerializerMethodField('get_variant_list', read_only=True) class Meta: model = Product fields = [..., 'variant_list'] def get_variant_list(self, obj): variant_list = VariantValue.objects.filter(product_id=obj.id) variant_list_grouped = variant_list.values('variant', 'value').annotate(count=Count('variant')) res = [] for variant in variant_list_grouped: pass return [] Thanks! -
MultiValueDictKeyError at /signup/ 'password11'
I'm trying to signup user but getting some weird error. please help me to solve it This is my view file with the function named signup def signup(request): if request.method=='POST': username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password11 = request.POST['password11'] if password1==password11: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('/account') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('/account') else: user=User.objects.create_user(username=username, password=password1, email=email) user.save(); auth.login(request,user) print('user created') else: messages.info(request,'Password not Matching') return redirect('/account') return redirect('/') else: return render(request,'account.html') And this is my signup file. I've save file with the name account.html. <form id="regform" style="margin-top: -40px;" action="/signup/" method="post"> {% csrf_token %} <input type="text" placeholder="Username" name="username"> <input type="email" placeholder="Email" name="email"> <input type="password" placeholder="Password" name="password1"> <input type="password" placeholder="Confirm Password" name="Password11"> <button type="submit" id="btn2">Register</button> <div> {% for message in messages %} <h6>{{message}}</h6> {% endfor %} </div> </form> -
docker-compose.yml for production - Django and Celery
I'm looking to deploy a simple application which uses Django and celery. docker-compose.yml: version: "3.8" services: django: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - "8000:8000" environment: - DEBUG=1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=djcelery.backends.database:DatabaseBackend depends_on: - redis celery: build: . command: celery -A core worker -l INFO volumes: - .:/usr/src/app environment: - DEBUG=1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=djcelery.backends.database:DatabaseBackend depends_on: - django - redis redis: image: "redis:alpine" volumes: pgdata: Dockerfile: FROM python:3.7 WORKDIR /app ADD . /app #Install dependencies for PyODBC RUN apt-get update \ && apt-get install unixodbc -y \ && apt-get install unixodbc-dev -y \ && apt-get install tdsodbc -y \ && apt-get clean -y # install ODBC driver in docker image RUN apt-get update \ && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \ && curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list \ && apt-get update \ && ACCEPT_EULA=Y apt-get install --yes --no-install-recommends msodbcsql17 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && rm -rf /tmp/* # install requirements RUN pip install --trusted-host pypi.python.org -r requirements.txt EXPOSE 5000 ENV NAME OpentoAll CMD ["python", "app.py"] Project Directories: When I run "docker-compose up" locally, the celery worker is run and I am able to go to localhost:8000 to … -
Django - 404 static in Docker on react app
I have backend on Django and storefront/dashboard on React. Django in docker container. Dockerfile (Django) ### Build and install packages FROM python:3.8 as build-python RUN apt-get -y update \ && apt-get install -y gettext \ # Cleanup apt cache && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements_dev.txt /app/ WORKDIR /app RUN pip install -r requirements_dev.txt ### Final image FROM python:3.8-slim RUN groupadd -r saleor && useradd -r -g saleor saleor RUN apt-get update \ && apt-get install -y \ libxml2 \ libssl1.1 \ libcairo2 \ libpango-1.0-0 \ libpangocairo-1.0-0 \ libgdk-pixbuf2.0-0 \ shared-mime-info \ mime-support \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN mkdir -p /app/media /app/static \ && chown -R saleor:saleor /app/ COPY --from=build-python /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=build-python /usr/local/bin/ /usr/local/bin/ COPY . /app WORKDIR /app ARG STATIC_URL ENV STATIC_URL ${STATIC_URL:-/static/} RUN SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic --no-input EXPOSE 8000 ENV PYTHONUNBUFFERED 1 CMD ["gunicorn", "--bind", ":8000", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "saleor.asgi:application"] When I go to the Dashboard and access objects with pictures, I get error: error on Dashboard Thanks for help me! -
Fill list using Counter with 0 values
Is possible to have a count of how many times a value appears in a given list, and have '0' if the item is not in the list? I have to use zip but the first list have 5 items and the other one created using count, have only 3. That's why I need to fill the other two position with 0 values. -
Django - export one-to-many in csv using one row per foreign key
I have a postgres database in Django and one of the tables has a foreign key and a number of entries. I want to generate a csv file with one row per foreign key. i.e. this is the table AuthorID Bookname Price 1001 “I love django” 3.40 1001 “Python is cool” 4.20 1002 “Pandas is cool” 5.10 The resulting csv should look like this AuthorID,Bookname1,Price1,Bookname2,Price2 1001,I love django,3.40,Python is cool,4.20 1002,Pandas is cool,5.10,, Can you help me with that? Is there a native way to do it in Django or in Postgres using raw sql? Thanks -
Question about EnviromentFile config setting for Gunicorn and Django production, do I need to use it?
I have a Django app in production, using gunicorn for help. I have a question about the setting EnviromentFile, should I refence the venv path for my project? Is it mandatory? The reason why I'm not adding it in my service file, is because I'm not serving any variables through the env. /etc/systemd/system/gunicorn.service : [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/alpha/project ExecStart=/home/user/alpha/project/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project.wsgi:application [Install] WantedBy=multi-user.target Do I still need to add, EnviromentFile,to my file above? And if I do, is referencing the activation needed? Like so: EnviromentFile=PATH/TO/venv/bin/activate? -
How do I get datatables to work with bootstrap4 tabs in Django templates?
I have a Django template with multiple tables. I am using Bootstrap 4 with datatables. I wanted to put my tables in tabs, and that is giving me problems. If the tables are not in tabs, this code works fine: $(document).ready(function() { $('.datatable').DataTable( { dom: 'Blfrtip', buttons: [ 'copy', 'csv', 'excel', 'print' ] } ); } ); I looked at these two links: Scrolling and Bootstrap tabs and Hidden initialisation. And got the snippet at the bottom of this post to work as datables (though the table widths have issues in Django). However, that snippet only works with hard-coded tables. In my Django template, I am using template tags to loop through query strings like this: {% if items %} <table class="table table-striped table-valign-middle datatable" id="data"> <th>Item Table</th> <thead> <tr> <th>Title</th> <th>Price</th> <th>Date</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.item.title|truncatechars:25 }}</td> <td>{{ item.price }}</td> <td>{{ item.date }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <div class="text-center font-weight-bold"> No items </div> {% endif %} In Django using the snippet example, if I replace the first tab's hard coded table with that template for loop, the datatable only works for the first tab (i.e., no … -
PUT POSTGRESQL DATABASE ONLINE
I'm working on a Django Project in which I'm using a postgresql database. Now I have to put my project online on python anywhere, but I looked at some videos and they put the database on AWS. I don't understand why can't I put also the database on python anywhere but I have to put it on AWS for example. I'm sorry if it is a dumb question but this is my first experience with backend. -
How to send a JavaScript variable to Django to use in views.py
I have a model that contains information about the different buildings being displayed on my website. When a user selects one of the buildings I would like that information to be displayed. When the user selects a building, a JavaScript variable contains the building name that the user selected. How can I send this variable to my views.py so I can get the building object specified by the "name" JavaScript variable? Here is what I currently have for my views.py, the building name "Harris" is hard coded in. This is where I would like to put the JavaScript variable, so I can display the buildings information depending on which one the user selects. from django.shortcuts import render from django.http import HttpResponse from .models import Building def index(request): buildings = Building.objects.get(buildingName = "Harris") return render(request, 'index.html', {'buildings': buildings}) I am new to Django so any information is helpful. Thanks -
How to use django ORM to query database
I have a model called 'dboinv_product' and this model has a field called 'product_name' I need to use Django ORM in my views.py file to pull ALL the product names. The goal is to put it into a list this way I can serialize it using JSON. Does anyone know which Django command(s) can be used to produce this list? Essentially, I need the equivalent of "SELECT ALL product_name FROM dbo.inv_product" -
Algorithm: track relationship changes of 3 elements
I want to log changes in 2 elements related to a 3rd one, but I can't come up with a nice algorithm to it. Let there be 3 objects (or components) that can be installed one inside the other (like russian dolls), and their state change when you put them in or take them out: A is installed in B and B is installed in C. A is taken out of B, but B still is in C. (A becomes avaiable) A and B are taken out of C. (A and B become available) I have 3 different classes defining the 3 components, but I'm not sure how to log the changes... on the same object? on a different class just for logging? Is there a pattern I should use as a base case? COMPSTATUS = ((1,'Available'),(2,'In use')) class A(models.Model): id = models.AutoField(primary_key=True) class B(models.Model): id = models.AutoField(primary_key=True) compA = models.ForeignKey(A, on_delete=models.PROTECT) status = models.CharField(max_length=2,choices=COMPSTATUS,default='1') class C(models.Model): id = models.AutoField(primary_key=True) compB = models.ForeignKey(B, on_delete=models.PROTECT) status = models.CharField(max_length=2,choices=COMPSTATUS,default='1') -
django tcp connection to models, FATAL: sorry, too many clients already database
First, let me say that I am new to Python i connected to djnago with tcp socket and i run the server with custom script and setup.djangu(), i get , create, and updated models with tcp and works fine , but problem is if 100 user coonected to a socket and be online i get this exception conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: sorry, too many clients already And I'm going to have a lot more online users than that,this is interesting to me i get online query from from django.db import connection and i see just two connection is online, if i connected with django plugin why other connections wont show, My question is how can I control postgress connections and use one or multi conecction to database, not per user in django with tcp connection, and i can work with django syntax ? thanks -
How to use dynamic urls to go to a database item
How do I make my website that going to the url 'mywebsite.com/1/' would show an item in the database that's id is 1 (and the same for /2/, /3/, etc.)? All the tutorials I have found are for setting up 'urls.py' in the older versions of Django. -
filter queryset of unique objects in django
Hi, I have a model in django lets say UserProfile and it has some data as like this. I want to filter over this model in such a way that if there are multiple records for same user_auth_id (for example user_auth_id=279) then I will take the last one. By this way I want to get the queryset from this model. What will be the filter expression here? From this example my queryset will be [247, 248, 249, 250, 251, 252, 312, 254, 255, 260, 262] -
Respect django tables order
is there any way to make django respect the data base order once I make migrations?, I constantly make some changes and when I see the data base tables the order changes and it is a bit disgusting. -
Django redirect URLs in modal forms
I am new with Django so I created a delete_orders modal form and now I want to redirect to the true path after deleting the order. My views.py is something like: def deleteOrder(request, order_id): order_item = Order.objects.get(id=order_id) customer = order_item.customer.username url = request.META['HTTP_REFERER'] parsed_url = urlparse(url) url_path = parsed_url.path if '/panel/profile/' in url_path: url_path = '/panel/profile/' + customer if request.method == 'POST': order_item.delete() return redirect(url_path) context = {'order_item': order_item} return render(request, '', context) And my urlpatterns is: path('<int:order_id>', views.deleteOrder, name='delete_order'), I want to know if it is a good practice to do the job or we have some other standard solutions? -
How to link some users with an OAuth application to allow or deny authentication based on that application in django-oauth-toolkit?
I'm using django-oauth-toolkit to do user authentication with DRF, my goal is to allow or deny authentication based on the OAuth application linked to the user. Let's say that I have application-one with user-a linked to it and application-two with user-b linked to it, now if user-a or user-b tries to provide different client_id:client_secret than the one for that OAuth application each one is linked to it, authentication should be denied. That's useful because if I created two OAuth applications, one for android users and the other for web users I can deny authentication for users who are not linked to with requested OAuth application or allow access for users who are linked to the correct OAuth application. I didn't find anything useful in the docs or over the internet about linking some users or for that purpose although it sounds very helpful, so any tips or suggestion will be appreciated. Thanks -
Django 2.2 ORM Exclude Not Working as expected
Im trying to get all customer list form Cust models that not having a record in Stat (ForeignKey), Django 2.2 class Cust(models.Model): name = models.CharField(max_length=50) active = models.BooleanField(default=True) class Stat(models.Model): cust = models.ForeignKey(Cust, on_delete=models.PROTECT, null=True) date = models.DateField(null=True, blank=True) im trying this but doestn work, month = datetime.now() month = month.strftime("%Y-%m") inner_qs = Stat.objects.filter(date__icontains=month) data = Cust.objects.exclude(id__in=inner_qs) print(inner_qs) print(data) The query above returning: <QuerySet [<Stat: Ruth>]> <QuerySet [<Cust: Jhonny>, <Cust: Rony>, <Cust: Sinta>, <Cust: Ruth>]> As you can see, i need the result [<Stat: Ruth>] excluded from the data queryset/list. but what i expected is: <QuerySet [<Stat: Ruth>]> <QuerySet [<Cust: Jhonny>, <Cust: Rony>, <Cust: Sinta>> -
Django model linked to multiple model objects
I'm new to Django and am looking to create a surveys which contains a: subject area a sub-domain subject response option to that sub-domain The best I can do right now is create a survey object linked to a single sub-domain and a single response. Is there a way to return JSON for a survey linked to ALL defined subjects and related sub-domains? Or at least, have a way to create a survey with all subjects and sub-domains? -
how to connect to main db use django pytest
I am using django and pytest in my project. I need to write tests based on data in the main database. But pytest cleans up and creates a clean database every test run session. I need to use the main db, which is specified in settings.py. I need a way without copying all the data of the main database to the test one! import pytest @pytest.mark.django_db def test_my_user(): me = User.objects.get(username='me') assert me.is_superuser I want the information to be taken from the main database in this case -
django-rest-auth: avoid password and email being same
I am using django rest auth for registration. I am using email as login and the below are my settings ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = 'http://localhost:3000/login' I am trying the api end point rest-auth/registration/ Now if i pass email and password same, it does not raise password validaiton error. these are my password validators: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] How to ensure the password is not similar to email using dango rest auth -
Finding the Time Range to restrict the events occuring on same time in calendar. (django)
The Problem is, I want to restrict overlapping of events occuring on same date and same time. I want to show the overlapping Error to the user when he registered an Event on same date having same time i am unable to query the time range between start_time and end_time. Kindly suggest me the best way to restrict overlapping. models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_date = models.DateTimeField(auto_now_add=True) group = models.ForeignKey(Group , on_delete= models.CASCADE , null= True , blank=True) priority = models.ForeignKey('Priority' , on_delete= models.CASCADE , null= True , blank=True) @property def get_html_url(self): url = reverse('event-detail', args=(self.id,)) return f' <a href="{url}"> {self.title} </a>' def create_event(slef): return f"http://localhost:800/event/create/" # def get_event_in_current_date(self): # # print(Event.objects.filter(date= self.date)) # return Event.objects.filter(date= self.date) @property def get_all_events(self): if Event.objects.filter(date= self.date).count() >1: url = reverse('event-all', args=(self.date, )) return f' <a href="{url}"> ... </a>' return "" @property def get_all_events_by_group(self): print(self.group) if Event.objects.filter(date= self.date , group= self.group ).count() >1: url = reverse('event-all-group', args=(self.date, self.group.name )) return f' <a href="{url}"> ... </a>' return "" def __str__(self): # print(self.date) return str(self.date) views.py class CreateEvent(LoginRequiredMixin , View): def post(self , request , *args , **kwargs): start_time … -
I want to keep data in my database after deletion and track it. How can I achive this goal?
i have a simple model Category. I want to soft delete instances and keep track of them in my db from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django_currentuser.middleware import get_current_user, get_current_authenticated_user from django_currentuser.db.models import CurrentUserField class Category(models.Model): name = models.CharField(max_length=80) created_on = models.DateTimeField("Created At", auto_now_add = True, null = True) created_by = CurrentUserField(related_name='created_by') updated_on = models.DateTimeField("Updated At", auto_now = True, null = True) updated_by = CurrentUserField(related_name='updated_by') deleted_on = deleted_by = def __str__(self): return self.name