Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM: How to use count method inside values_list method?
To simplify things, I need to perform this query: select state,count(*) from Airports group by state order by count(*) desc And the desired return from my query is a dictionary like this: { 'state1': value1, 'state2': value2, 'state3': value3, ... 'staten': valuen, } I did some research and seems I need to use aggregate and annotate but I'm kinda lost in how to perform this with values_list(). Can I use count inside it like this? Airport.objects.values_list('state', Airport.objects.count()).annotate('state').order_by(-Airport.objects.count()) -
docker compose up generate (2005, "Unknown MySQL server host 'db' (-2)") error
Hi all i'm trying to dockerize a django application with a connexion to the database. when i run docker compose up i get this error when the dockerfile is making migrations django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py makemigrations' returned a non-zero code: 1 here is my Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /SFP_ingestion WORKDIR /SFP_ingestion COPY . /SFP_ingestion RUN pip install -r requirements.txt RUN python generatemodel.py RUN python generateapp.py RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py migrate easyaudit CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and here is my docker-compose.yml services: db: image: mysql restart: always command: --default-authentication-plugin=mysql_native_password --mysqlx=0 environment: - MYSQL_HOST=localhost - MYSQL_PORT=3306 # cannot change this port to other number - MYSQL_DATABASE=sfp # name you want for the database - MYSQL_USER=root # change to whatever username you want - MYSQL_PASSWORD=password #change to the password you want for user - MYSQL_ROOT_PASSWORD=password #change to good root password ports: - "3306:3306" expose: - "3306" volumes: - "./db:/var/lib/mysql" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/SFP_ingestion restart: always ports: - "8000:8000" depends_on: - db -
django url tag with dynamic app_label
i'm trying to create a dynamic url tag for my class based listview. it's needed for a delete button on every list item it loops over. the issue is that I use this template in multiple apps and want to reuse it. what currently works: [filename.html] {% for file in object_list %} <tr> <td>{{file.name}} </td> <td>{{file.regExpFilename}}</td> <form class="delete-form" method="POST" action="{% url 'MyApp1:filenames_delete' pk=file.stream %}"> <button type="submit" value="delete" class="btn-delete" onclick="return confirm('Are you sure to delete {{file.stream}} {{file.regExpFile}}?')"> Delete </button> But I want to remove the 'MyApp' to make it reusable for multiple apps. Many Thanks, -
install django on suse linux enterprise server 11
I use SUSE Linux enterprise server 11 and try to install Django but these package not found on ZYPPER or YAST second question i want to know if i want to install SUSE Linux enterprise server 12 or 15 after using the registration code on the site then the time of it is ended i didn't want to buy activation code what happen is this close system ? -
No post found matching the query
class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' path('post//', PostDetailView.as_view(), name='post-detail') when i go to 127.0.0.1:8000/post/1, it says No post found matching the query enter image description here -
errors in django tests
im trying to run the following test but im not sure why its not working since when tests are ran a test db is created and that means that the newly created item gets an id of 1 but im still getting an error that no object matches the query model from django.db import models # Create your models here. class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] tests from django.test import TestCase from .models import Post # Create your tests here. class PostModelTest(TestCase): def setup(self): post = Post.objects.create(text="just a test") def test_text_content(self): post = Post.objects.get(id=1) expected_obect_name = f'{post.text}' self.assertEqual(expected_obect_name, 'just a test') here's the error -
what is mean by "Apply all migrations: admin, auth, authentication, contenttypes, sessions, sites" in Django Python 2.2 migrate command?
I am trying to migrate all the models in my Django project to a database, after migration, There are many tables missing in the database, but when I run python manage.py migrate there is no migration to apply, and what is this Operations to perform, and what exactly mean by Apply all migrations: adming, auth, authentication, contenttypes, sessions, sites ? -
Django - context - How to pass context to ALL views
Because I need to cycle through a model table to render the options/nav-links in the navbar, and the navbar is rendered on every page. Hence, I find myself passing in the same context to every class-based view and it's quite repetitive: class Xxx: ... def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['categories'] = Category.objects.get_categories_with_item() return context Is there a DRYer way to do this? Thanks!! PS. and also, is *args necessary in get_context_data method? I've seen code with it and code without -
Drop-down list in table rows django
How to display in the table rows a drop-down list whose data is taken from the database? At the moment, I just show the value from the database, and there is no drop-down list, although I specified the ModelChoiceField. My code: models.py class Technology(models.Model): technology_name = models.CharField(max_length=255, null=True) def __str__(self): return '%s' % (self.technology_name) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') qty = models.PositiveIntegerField(default=1) price = models.DecimalField(default=0.00, decimal_places=2, max_digits=20) technology_id = models.ForeignKey(Technology, on_delete=models.PROTECT, null=True) view.py class OrderUpdateView(UpdateView): model = Order template_name = 'order_update.html' form_class = OrderEditForm def get_success_url(self): return reverse('update_order', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) instance = self.object qs_p = Product.objects.filter(active=True)[:12] products = ProductTable(qs_p) order_items = instance.order_items.all() context.update(locals()) return context forms.py class OrderItemTable(ModelForm): technology_id = forms.ModelChoiceField(queryset=Technology.objects.all(), empty_label='') class Meta: model = OrderItem fields = ['product', 'qty', 'technology_id'] order_update.html {% for item in order_items %} <tr> <td>{{ item.product }}</td> <td>{{ item.qty }}</td> <td>{{ item.technology_id }}</td> </tr> {% endfor %} -
Django - How to change nav "active" class on different pages with base.html
I have my navbar on my base.html, so I extend it on all other pages. But I have a class "active" on the home page, so it also stays active in all other pages. <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" href="http://127.0.0.1:8000/backend/"> <i class="ni ni-shop text-primary"></i> <span class="nav-link-text">Dashboard</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes"> <i class="ni ni-ungroup text-orange"></i> <span class="nav-link-text">Clients</span> </a> </li> </ul> How can I change the active class to a different menu item based on the page I am? -
question regarding User model architecture
I would like to ask you about some architectural issues I face in my first django App in scope of User model. This App is used to manage employees and support their activities. Because I have no prior experience with Django I have decided to follow easiest path and use django built in User model. Based on it I have created a User model which should meet following requirements: there must be a User class, which represents App user and store all login data That User model must bee able to keep different attributes, specific for employee: like e.g. position, salary, There must be possibility to keep relations between Employees and Manager Each user needs to have its own profile which is used for customising App view Each user needs to belong to specific user groups which have a specific rights to view/modify/delete data from database - this is not implemented yet! As you can see on the diagram this model Is quite complicated and thus hard to manage. Even relativelly simple task (like get my manager id and assign a task for him) are complicated because I need to operate on 3 user classes (User, Employee, Manager) which keeps … -
Creating different admin that everyone has permission to see only the products he enter
I want to allow different sellers to see only their products on their ADMIN site, add products that only they will see (except the general manager) I attach the model of the products: class Item(models.Model): ***seller = models.ForeignKey(Seller, on_delete=models.CASCADE)*** name = models.CharField(max_length=20) manufacturer = models.CharField(max_length=20, blank=True) category = models.ForeignKey(Categories, on_delete=models.CASCADE) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_DEFAULT, default=types.item_types.GENERAL) slug = models.SlugField(max_length=200, db_index=True, blank=True) description = models.TextField(blank=True) image = models.ImageField(upload_to=r'ecommerce/pictures', blank=True) # adding date to the path? price = models.DecimalField(max_digits=10, decimal_places=2, blank=True) stock = models.PositiveIntegerField(blank=True) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) sales = models.BooleanField(default=False) Thanks to those who can advise me. -
Celery task as action in Django admin panel
I'm generating static website version through Django admin. It takes some time so I decided to use Celery. But it throws me this error: EncodeError at /admin/pages/project/ Object of type Project is not JSON serializable How can I call a command as action in Django admin panel using celery? admin.py from .tasks import command_task @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'updated', 'created', 'is_active') actions = ['export_to_static_version'] def export_to_static_version(self, request, queryset): if len(queryset) > 0: project = queryset[0] command_task.delay(project) models.py class Project(models.Model): dev_list = ['1', '2', '3', '4'] title = models.CharField(max_length=100) author = models.CharField(choices=dev_list), max_length=100, blank=True) comment = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) is_active = models.BooleanField(null=False, default=False) settings CELERY_BROKER_URL = 'amqp://localhost' CELERY_RESULT_BACKEND = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Berlin' CELERY_BEAT_SCHEDULE = {} celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'basic.settings.development') app = Celery('basic') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) tasks.py from celery import task from django.core.management import call_command @task def command_task(project): call_command('generate_static_website', id=project.id) -
Django Form: Only show manytomany objects from logged in user
The current problem is that my form shows the logged in user all Portfolios ever created. The form should only show portfolios that the logged-in user created. Something like this: associated_portfolios manytomany field = ...objects.filter(user=user_id) I'm not sure if this should be implemented in the forms.py or views.py and if so how. I've been going through the django documentation and found 'formfield_for_manytomany' but not sure if this is only meant for admin. Models.py class Portfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20) description = models.CharField(max_length=250, blank=True, null=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = RichTextUploadingField(blank=True, null=True) associated_portfolios = models.ManyToManyField(Portfolio, blank=True) created_on = models.DateField(auto_now_add=True, editable=False) Views.py class PostCreate(CreateView): model = Post form_class = PostCreateForm def formfield_for_manytomany(self, db_field, request, **kwargs): self.fields['associated_portfolios'] = Portfolio.objects.filter(user=self.request.user) return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs) forms.py class PortfolioCreateForm(ModelForm): class Meta: model = Portfolio fields = ['user', 'name', 'description'] class PostCreateForm(ModelForm): class Meta: model = Post fields = ['user', 'title', 'body', 'category', 'associated_portfolios'] -
Django Page not found (404) but URLs are correct
I encountered such an error, I get 404 error when trying to open the URL http://127.0.0.1:8000/account/ # apps/accounts/urls.py from django.urls import path from django.contrib.auth.views import LoginView from . import views urlpatterns = [ path('', views.index), path('login/', LoginView.as_view(template_name='account/login.html'), name="login") ] And the strangest thing is that if I add something like qwe/ in path http://127.0.0.1:8000/account/qwe it will work, and 2nd path login/ is working Can anyone tell me what the problem is? #apps/accounts/views.py from django.shortcuts import render, HttpResponse def index(request): return HttpResponse('<h1>Hello</h1>') Main urls.py #project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("apps.main.urls")), path('account/', include("apps.account.urls")), ] -
How to avoid "'NoneType' object has no attribute" in Django query
A very simple questions, when I do complex query in Django, filter by item's foreign key's foreign key is common. just like # find out which house's owner's manager's company have a specific car House.objects.filter(Q(owner__manager__company__cars=specific_car)) So I have to ensure every foreign key in the chain is not None. Any field in the chain is None will couse AttributeError: 'NoneType' object has no attribute That is a nightmare. I could deal with that in real object by house.owner or house.owner.manager but how can I deal with queryset? -
relation "<a new model>" does not exist
I have a Django project consist of several apps. I've added a new model on my settings app: class DataFrameAdjustment(models.Model): """Configure Database bunch settings""" bunch_size = models.PositiveSmallIntegerField( default=0, blank=True, null=True) timeout = models.CharField( max_length=3, choices=Strings.TIMEOUT, default="3", blank=True, null=True) def __str__(self): return f"{self.bunch_size} - {self.timeout}" class Meta: verbose_name = 'Data Frame Adjustment' verbose_name_plural = 'Data Frame Adjustments' At the moment, I'm dealing with the following error: from settings.models import DataFrameAdjustment df = DataFrameAdjustment.objects.all() print(df) # For test. Out: Out[11]: --------------------------------------------------------------------------- UndefinedTable Traceback (most recent call last) /usr/local/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 83 else: ---> 84 return self.cursor.execute(sql, params) 85 UndefinedTable: relation "settings_dataframeadjustment" does not exist LINE 1: ...e", "settings_dataframeadjustment"."timeout" FROM "settings_... ^ The above exception was the direct cause of the following exception: ProgrammingError Traceback (most recent call last) /usr/local/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() /usr/local/lib/python3.6/site-packages/IPython/lib/pretty.py in pretty(self, obj) 403 if cls is not object \ 404 and callable(cls.__dict__.get('__repr__')): --> 405 return _repr_pprint(obj, self, cycle) 406 407 return _default_pprint(obj, self, cycle) /usr/local/lib/python3.6/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle) 693 """A pprint that just redirects to the normal repr function.""" 694 # Find newlines and replace them with p.break_() --> 695 output = … -
How to save image on shared host filestorage from django app?
I have made an app using django and deployed it to heroku. I am using mysql database from a shared host & its working . I want to save my image file on shared host public_html folder & i created a folder named media inside public_html. So i changed the media url & root in django settings , the link is working but images doesn't save on public_html folder.But if i manually upload image in cpanel public_html folder then i can access it from my app. But i can not send image to that shared host. here is my settings.py: MEDIA_URL = f'http://www.example.com/media/' MEDIA_LOCATION = "media" -
Send X-CSRF Token to a Django server using XHTTP Request or jQuery Ajax
I've been trying to make a POST to my Django application via XHTTP Request and jQuery with no correct result at all. The fact is that the Django app is on one of my subdomains, and the web app is in another, not being part of the Django app, just only a separated app. I've been reading the docs, but none of this works. All of my subdomains are in the ALLOWED HOSTS list and in the CORS ORIGIN WHITELIST, and the petition works correctly with GET, but POST returns me a Forbidden 403 error telling CSRF Cookie not found. This is the code of my petition. var petition = new XMLHttpRequest(); petition.open('POST','http://localhost:8000/login/',true); petition.setRequestHeader("X-CSRFToken",sessionStorage["csrf_token"]); petition.send() I already have stored the CSRF cookie in the session storage with this function. function storeCSRFToken(){ var token; $.ajax({ url : 'http://localhost:8000/token', type: "GET", dataType : "json", success: function( data ){ token = data.csrf_token; sessionStorage['csrf_token'] = token; } }); } Any clue of what is going wrong? -
How to update multiple objects in django rest framework?
I am trying to update multiple objects using IDs which i am passing in every objects that need to be updated but can't find any way to do it successfully. Here is my code models.py class EventTicket(models.Model): id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable=False) name = models.CharField(max_length=250) description = models.TextField(max_length=1000) views.py ``` class EventTicketView(APIView, PaginationHandlerMixin): permission_classes = (AllowAny,) def get_object(self, ticket_id): try: return EventTicket.objects.get(id=ticket_id) except EventTicket.DoesNotExist(): raise status.HTTP_400_BAD_REQUEST def patch(self, request, *args, **kwargs): for each_ticket in request.data: ticket_id = self.get_object(each_ticket['ticket_id']) serializer = EventTicketSerializer(instance=ticket_id,data=request.data,partial=True) if serializer.is_valid(): serializer.save() result = { 'message': "updated sucessfully" } return Response(result, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ``` ``` serializers.py ``` ``` class EventTicketSerializer(serializers.ModelSerializer): class Meta: model = EventTicket fields = ['name', 'description'] ``` I have to send data like list of multiple objects ::: [ { "ticket_id": "054665ea-4fde-11ea-94b2-9f415c43ba4c", "name": "chris", "description":"The golden ticket for day only", }, { "ticket_id": "054656ea-4fde-11ea-94b2-9f415c43ba4c", "name": "daut", "description":"The premium ticket for day only", } ] -
Django smtp gmail not working in production
I'm using django to send email through gmail smtp. It only works, however, before deployment. In production or deployment whatever you call, when I try to send email it keep being loaded forever and only says 'Server Error 500'. Below is part of my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config['EMAIL_USER'] EMAIL_HOST_PASSWORD = config['EMAIL_PASS'] Below is .../django_project/users/views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in.') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required() def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) What's confusing is my tutorial videos didn't put any from django.core.mail import send_mail or something. So I'm not sure whether the view.py above is the one that … -
'int' object has no attribute 'disabled' Django
I am trying to pass a specific value to a field in django form but keep getting this error: 'int' object has no attribute 'disabled' Forms.py class AllotmentDocketForm(forms.ModelForm): class Meta: model = AllotmentDocket fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['sales_order'].queryset = MaterialRequest.objects.filter(is_allocated=False) self.fields['transaction_no'].disabled = True max_quant = AllotmentDocket.objects.filter(transaction_no__isnull=False).aggregate(Max('transaction_no')) max_quantity = max_quant.get('transaction_no__max') print("max transaction_no", max_quantity) self.fields['transaction_no'] = max_quantity + 1 Why is it not allowing me set transaction_no to a value ? -
NameError: name 'Model' is not defined after importing models in a newly created file
I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this. Here is a screenshot showing where the file is located. How I'm importing the models in the utilities.py file from .models import * Error -
Create json file for many to many fields in django
model.py class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Question(models.Model): name = models.CharField(max_length=255) Tag_name = models.ManyToManyField(Tag) I need to create json to insert data using inside both models, for tags I have created the json but I don't get how to create json for Question model to insert data directly from it. Tag json look like: [ { "name": "a" }, { "name": "b" } ] Since Tag_name is many to many field it create 2 tables in sqlite but I want to add data using one json only.How to make a json so that data in both table get inserted ? -
RelatedObjectDoesNotExist. User has no profile
I've read some other answers for this (almost) question but they didn't help. I have the following 2 files mixed for user and profile apps(?). In other answers they said this happens if you don't use >objects.get_or_create or not making signals.py file you'll get this error but I've gone through both of those ways and no results. This is the traceback I get: Environment: Request Method: GET Request URL: http://127.0.0.1:3000/profile/ Django Version: 3.0.3 Python Version: 3.7.3 Installed Applications: ['blog', 'users', 'crispy_forms', 'django_cleanup', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/wss/Desktop/projects/python/django/mahour_sanat/mahoursanat/users/views.py", line 38, in profile p_form = ProfileUpdateForm(instance=request.user.profile) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 225, in inner return func(self._wrapped, *args) File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 423, in __get__ self.related.get_accessor_name() Exception Type: RelatedObjectDoesNotExist at /profile/ Exception Value: User has no profile. forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() …