Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin.autodiscover fails to discover "primary" admin.py
My models won't show up in the admin panel, and I suspect it's because admin.py isn't being discovered. Also, all the models work as expected in the application; I can import two.MyModelB and use it in the shell, in my web-app, etc. root/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'one', 'two', etc] root/urls.py: from django.contrib import admin print("### Running admin-autodiscover ###") admin.autodiscover() Note that I don't usually use admin.autodiscover(), but it was a suggestion I came across when I was searching for solutions to this. Including it (or not) makes no difference either way. root/admin.py: from django.contrib import admin from django.conf import settings from one.models import MyModelA from two.models import MyModelB print("### This should be discovered! ###") class MyModelAdmin(admin.ModelAdmin): readonly_fields = ('id',) # Register your models here. admin.site.register(MyModelA, MyModelAdmin) admin.site.register(MyModelB, MyModelAdmin) superuser confirmed: console output: (env) PS E:\Django> python manage.py runserver Watching for file changes with StatReloader Performing system checks... ### Running admin-autodiscover ### System check identified no issues (0 silenced). Django version 4.1.5, using settings 'root.settings' Starting development server at http://127.0.0.1:8000/ The statement from urls.py is output, but not the one from admin.py. I assume that indicates there's some malfunction with django.contrib.admin, but it's far beyond my knowledge. Curiously, making admin.py … -
Querying for model based on file name
I've got a filename: filename = 'myfile.txt' I'd like to be able to query for it. summernoteimages = UserFile.objects.filter( Q(file__name=filename) ) I'm getting the following error: Unsupported lookup 'name' for FileField or join on the field not permitted. -
My Tamil letters are not displaying in Pdf file in Django
views.py def pdf(request,songsheetname): username=request.user.username printsong=Songsprintform.objects.all().filter(username=username,removesong='0', addsheetstatus='0',songsheetname=songsheetname,songprintstatus='1') countsong=Songsprintform.objects.all().filter(username=username,removesong='0', addsheetstatus='0',songsheetname=songsheetname,songprintstatus='1').count() songid = [] for i in printsong: songid.append(i.songprintid) recentsongs=SongList.objects.all().filter(id__in=songid) template_path = 'pdf.html' context = {'recentsongs':recentsongs} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="songs.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response django template <html> <head> <title>Page Title</title> <meta charset="utf-8"> <style> div { column-count: 2; column-width: 300px; } </style> </head> <body> <div class="col-md-6"> {% for i in recentsongs %} <p class="float-left">{{i.body |linebreaks}}</p> {% endfor %} </div> </div> </body> </html> This is my code... Here I'm converting my Django template(html) page into pdf. All are Working fine but here my content are in Tamil. But here it displays as an Square box instead of Tamil Letters .whenever my click my button on see that pdf file it always shown as an square box. I don't Know why.Please help me... -
How to implement a specific parser (Chinese) for PostgreSQL full text search in Django?
I want to implement PostgreSQL full text search in Django 4.0. for Chinese language. The question already arise in 2010 but there wasn't any suitable solution and they had to move to SQL Server. In 2015 a PostgreSQL extension for full-text search of Chinese appeared (here). Is it possible to implement that parser using Django? Any reference/pointers on how to do it really appreciated. -
Can't get full url of Image Field Django Rest
I have two serializers: class AlbumImageSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField('get_url') def get_url(self, obj): return obj.image.url class Meta: model = AlbumImage fields = ['id', 'url'] class PhotoAlbumSerializer(serializers.ModelSerializer): photos = AlbumImageSerializer(many=True, read_only=True) class Meta: model = Pet fields = ('id', 'name', 'photos') And i read that to display full url of image it's enough to pass a request context to serializer call, like: serialized = SomeSerializer(some, context={"request": request}) And when you use ViewSet you don't need to do anything, DRF will automatically pass the request context while initializing the serializer. I am using ViewSets like: class PhotoAlbumViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, GenericViewSet): serializer_class = PhotoAlbumSerializer but still my get-request returns response like: "url": "/media/images/photo.jpg" How can i get "url": "127.0.0.1:8000/media/images/photo.jpg" In my case? -
Download and export data to CSV
I have managed to develop an export button which allows users to download all approved orders `def orders_download(request): response=HttpResponse(content_type='text/csv') response['Content- Disposition']='attachment;filename="all_orders.csv"' query=Order.objects.all() writer=csv.writer(response) writer.writerow(['DESCRIPTION','COST','QUANTITY','TOTAL_COST','CATEGORY','STATUS','DATE_ORDERED']) return `response its downloading but not returning all rows as required. what is it am missing? have tried looping but its returning one row multiple times -
How to implement 3x3 grid for listview in django?
I have a ListView for a blog with fields of title, text and image in the shape of a card. I want to display them in a grid but the default renders these items in vertical format. How to implement grid for these items? -
Call js function every time DjangoForm is loaded?
I have next form: class ExampleForm(forms.ModelForm): class Meta: model = ExampleModel fields = ['field1', 'field2', 'field3'] widgets = {'field1': forms.Select(attrs={'onchange': 'onchangeJsFunction()'})} So far i have been able to add onchange property to my select field that calls 'onchangeJsFunction()' every time 'field1' value is changed. My next goal is to add a function that is going to be executed every time form is loaded, and i am not sure how to do it. I have tried adding onload property to a input field this way: ... widgets = {'field_2': forms.TextInput(attrs={'onload': 'onloadJsFunction();'})} ... but it does not give any results so far. How am i supposed to execute certain JS function every time my Django Form is loaded? -
How to run a java script (or some) with ajax from a separate file?
I have several ajax scripts in the base body django template. I want to run them in a separate js file, but the scripts do not work from a file. My script in the body template (this is a working code.): <!--Add product to the cart after press Add button--> <script> $(document).on('click', '#add-button', function (e){ e.preventDefault(); var prodid = $('#add-button').val(); $.ajax({ type: 'POST', url: '{% url "add_cart" %}', data: { product_id: $('#add-button').val(), quantity: $('#qty').val(), csrfmiddlewaretoken: '{{csrf_token}}', action: 'POST' }, success: function (json) { document.getElementById('cart_icon_count').innerHTML = json.qty; }, error: function(xhr, errmsg, err) {} }); }) </script> Than delete script from body and copy in js file: my_js.js $(document).on('click', '#add-button', function (e){ e.preventDefault(); var prodid = $('#add-button').val(); $.ajax({ type: 'POST', url: '{% url "add_cart" %}', data: { product_id: $('#add-button').val(), quantity: $('#qty').val(), csrfmiddlewaretoken: '{{csrf_token}}', action: 'POST' }, success: function (json) { document.getElementById('cart_icon_count').innerHTML = json.qty; }, error: function(xhr, errmsg, err) {} }); }) and in the body: <script src="{% static 'js/my_js.js' %}"></script> The usual java script function works this way, but for some reason this script does not. Any ideas for running one or more of these scripts from a separate file? -
django-filter, how to use for manytomanyfiled
how can use django-filters for ManyToManyField class PostFilter(django_filters.FilterSet): title = CharFilter(widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "ady"}), field_name="title", lookup_expr="icontains") tagList = ModelChoiceFilter(field_name="tagList", queryset=Tag.objects.all(), widget=forms.Select( attrs={"class": "form-control"})) class Meta: model = Post fields = ["title", "tagList"] exclude = ["image", "like", "seen", "share"] -
firebase-admin adding a random alphanumeric key to the realtime database when using push()
I am using the Python firebase-admin library to integrate Django rest framework and Firebase Realtime storage. I am using the push() function to create a new child node. However, the function adds an alphanumeric key to each child. Is there a way I can avoid that and add my own custom keys to the data? See example below: def post(self, request): """Function to handle post requests Args: request (_type_): _description_ """ # Get the data to be posted from the request name = request.POST.get('name') age = request.POST.get('age') location = request.POST.get('location') # Set the reference to the database ref = db.reference('/') # Push the data to the database ref.push({"user1" : { 'Name': name, 'Age': age, 'Location': location }}) return JsonResponse({"message": "Data posted successfully"}, status=200) When I run this, the node is created as follows { "data": { "-NNzIPh4SUHo6FLhs060": { "user1": { "Age": "20", "Location": "US", "Name": "Dummy name 2" } }, "user2": { "Age": "22", "Location": "count1", "Name": "Dummy 1" } } } The -NNzIPh4SUHo6FLhs060 key is created which I want to customize. -
Vs Code + Python : What means VS (Pylance) autocomplete suggestion for get_success_url()
When I define `get_success_url' in my views, if I accept Pylance Autocomplete suggestion, I got this : def get_success_url(self) -> str: return super().get_success_url() Didn't find anywhere how to use this. By my side, I'm use to do : def get_success_url(self, **kwargs): return reverse_lazy('name_space:url_name', kwargs={'pk': foo}) How to (can I) use pylance's suggestion to achieve the same result as my method -
i need to be solve these python dgango errors
Using the URLconf defined in Organic_Species.urls, Django tried these URL patterns, in this order: [name='index'] signup [name='signup'] admin/ ^media/(?P.*)$ The current path, signup.html, didn’t match any of these i need to solve these errors -
Cannot serve media files with nginx
I am using django-cookiecutter for project, I cannot serve media files with nginx: and not getting any errors, django works fine. I am new to docker, I think problem with volumes idk as django docker files are auto created. Searched some questions but didn't help. Dockerfile ARG PYTHON_VERSION=3.10-slim-bullseye FROM python:${PYTHON_VERSION} as python FROM python as python-build-stage ARG BUILD_ENVIRONMENT=production # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt FROM python as python-run-stage ARG BUILD_ENVIRONMENT=production ARG APP_HOME=/app ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} RUN addgroup --system django \ && adduser --system --ingroup django django RUN apt-get update && apt-get install --no-install-recommends -y \ # psycopg2 dependencies libpq-dev \ # Translations dependencies gettext \ # cleaning up unused files && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* # copy python dependency wheels from python-build-stage COPY --from=python-build-stage /usr/src/app/wheels /wheels/ # use wheels to install python dependencies RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ && rm -rf /wheels/ COPY --chown=django:django ./compose/production/django/entrypoint … -
Raw query must include the primary key from django
grade = request.GET.get('grade') year = request.GET.get('year') subject = request.GET.get('subject') marks_sheet1=Marks_sheet.objects.raw("select id,unique_id,student_name,attendance,%s FROM school_marks_sheet a, school_marks_details b WHERE term = 'Term1' and a.grade = %s and a.year=%s and a.unique_id = b.details_id_id order by student_name",[subject,grade,year]) I got this issue when I try this code. can anyone solve this. I want to take the output according to the query -
How to use Django get request value from sql query
I tried following code grade = request.GET.get('grade') year = request.GET.get('year') subject = request.GET.get('subject') marks_sheet=Marks_sheet.objects.raw("select id,unique_id,student_name,attendance,%s FROM school_marks_sheet a, school_marks_details b WHERE term = 'Term3' and a.grade = %s and a.year=%s and a.unique_id = b.details_id_id order by student_name",[subject,grade,year]) This query isn't work. How can I use subject name in select query -
Has Many Through in django?
class Post(models.Model): ... class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE) class Tag(models.Model): comment = models.ForeignKey(Comment,on_delete=models.CASCADE) How to use post object to get all tags??? Like laravel framework hasManyThrough? Except this way for comment in post.comment_set.all(): for tag in comment.tag_set.all(): print(tag) -
Elastic Beanstalk server using 97% memory warning
I just discovered that my Elastic Beanstalk server has health status with a warning "97% of memory is in use". Because of this I can not deploy updates or ssh and run the django shell. I just receive the following error: MemoryError Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/sentry_sdk/worker.py", line 70, in start self._thread.start() File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/sentry_sdk/integrations/threading.py", line 54, in sentry_start return old_start(self, *a, **kw) # type: ignore File "/usr/lib64/python3.7/threading.py", line 852, in start _start_new_thread(self._bootstrap, ()) RuntimeError: can't start new thread I received more memory errors when trying AWS documented troubleshooting suggestions which required installing a package: sudo amazon-linux-extras install epel From here I don't know what else I can do to troubleshoot this issue or how to fix it. -
Django - how to automatically create a new model instance when another model instance is created
I have an Order and Notification Model, whenever there is a new order model instance, i want to immediately create a notification for the new order, i wrote some functions in the models but when there is a new order, the notification instance does not get created. i still think there should be a better way to do this, how can i go about this? models.py class Orders(models.Model): service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_orders") seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="seller") def create_notification(self): create_notification = Notification.objects.create(provider=self.seller, service=self.service, order=self , notification_type='new_order') create_notification.save() return create_notification class Notification(models.Model): provider = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="provider_notifications") service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name="service_notifications") order = models.ForeignKey(Orders, on_delete=models.SET_NULL, null=True, related_name="service_order") notification_type = models.CharField(max_length=100, choices=NOTIFICATION_TYPE, default="none") -
Django "DATABASES is improperly configured" error after updating versions
I am trying to update a few-year old existing django project to current django and python 3. We're running into a multitude of issues, but most haven't been to hard to identify and resolve. Currently we are running into the dreaded django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. error when trying to manage.py migrate or some other commands like inspectdb. The odd thing is that we definitely are defining the database config with a default db and engine. This setup below is from our settings.py file. It's set up that way just so that we could use sqlite for testing purposes or mysql like the live servers. I've tried both, and it doesn't work with either. I have put print statements in to confirm that it does hit the appropriate sections. I also tried the dummy engine just to test and that had the same issue. #LOCALDEV_DB = 'MYSQL' LOCALDEV_DB = 'SQLITE' if LOCALDEV_DB == 'MYSQL': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'foo', 'USER': 'root', 'PASSWORD': '123456789', 'OPTIONS': { 'init_command' : 'SET default_storage_engine=MYISAM', }, #'STORAGE_ENGINE': 'MYISAM' } } elif LOCALDEV_DB == 'SQLITE': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } The … -
Django CMS page tree default language
It seems I don't understand how to set the default language for Django CMS. I want the default language to be set to Dutch. However, for an unknown reason, it always defaults to English when creating or after modifying/editing a Page. Take the following scenario. I open the Page tree. English is selected. I select Dutch. It I edit this page. I publish it. I refresh the page, I click on edit, it opens the English page which is empty. Note: All cookies were removed as suggested in the documentation. Please advise how I can set the default language to Dutch? The settings: from django.utils.translation import gettext_lazy as _ LANGUAGE_CODE = "nl" SITE_ID = 1 USE_I18N = True MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] LANGUAGES = [ ('nl', 'Dutch'), ('en', 'English'), ] CMS_LANGUAGES = { 1: [ { 'code': 'nl', 'name': _('Dutch'), 'fallbacks': ['en', ], 'public': True, 'hide_untranslated': True, 'redirect_on_fallback': False, }, { 'code': 'en', 'name': _('English'), 'public': True, }, ], 'default': { 'fallbacks': ['nl', 'en'], 'redirect_on_fallback': False, 'public': True, 'hide_untranslated': True, } } -
Django API: Updating a list of dictionaries
I am trying to pass a list of dictionaries through my django rest framework API, loop through them, update the associated records in the model, and ultimately return the serialized data to the front end. I am receiving the following error when submitting the list of dictionaries: HTTP 400 Bad Request Allow: PUT, OPTIONS Content-Type: application/json Vary: Accept [ { "non_field_errors": [ "Expected a list of items but got type \"dict\"." ] }, { "non_field_errors": [ "Expected a list of items but got type \"dict\"." ] } ] Here is the JSON I'm passing through the django rest framework API template: [ { "id": "1", "order": "5" }, { "id": "2", "order": "3" } ] Here is a view of my model: class Waitlist(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True) identification = models.CharField(max_length=50) email = models.EmailField(max_length=100, validators=[], blank=True) mobile_phone = PhoneNumberField(blank=True) store_number = models.PositiveSmallIntegerField() order = models.PositiveSmallIntegerField() status = models.PositiveSmallIntegerField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.first_name + ' ' + self.last_name Here is a stripped down view of my views.py: from django.shortcuts import render, get_object_or_404 from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from .models import Waitlist from .serializers import WaitlistOrderSerializer, WaitlistOrderListSerializer @api_view(['PUT']) def … -
Django: Is possible use _set into the filter() method?
I'm working on my ListView called IndexView on my polls app. This view currently return the last five published questions (not including those set to be published in the future). But my view also publish Questions that don't have any Choice, so I also want this view to only publish Questions that have Choices. IndexView in views.py class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] Question and Choice models in models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text My approach is to use the _set object and checking if the size of the queryset is bigger than 0 but I don't know if is possible use this object into the filter() method. -
AttributeError at / 'int' object has no attribute 'get'
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/deprecation.py", line 138, in call response = self.process_response(request, response) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/middleware/clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'int' object has no attribute 'get' Here is my code, #views.py class BookList(generic.View): model = Book def get(self, request, *args, **kwargs): books = Book.objects.all() if request.GET.get('Add') == 'Add': query = request.GET.get('hidden-book') book = Book.objects.filter(pk=query).update(moved=True) return book context = {'books': books} return render(request, 'main.html', context) #main.html <form method="GET" action=""> <input type="hidden" name="hidden-book" value="{{ book.id }}/> <input type="submit" name="Add" value="Add"/> </form> #models.py class Book(models.Model): moved = models.BooleanField(default=False) When the user presses the 'Add' input button, it should change the moved attribute in book to True. For background, I have an application that has a list of books, each with their own add button, that upon clicking an add button, the book is added to another list of books. My code works, but when I click the add button an AttributeError at / 'int' object has no attribute 'get' is raised. When I go back to 127.0.0.1:8000/, the book has been moved from the first to second list. Since I don't know what's causing the error, I … -
Trying to have django admin display all the files in a ticket
I am currently trying to have my admin item display page show all the files in the ticket, but for some reason it only shows the first file in a ticket. My model file is like so class Ticket(models.Model): OPEN = 'Open' CLOSED = 'Closed' STATUS_CHOICES = ( (OPEN, OPEN), (CLOSED, CLOSED), ) title = models.CharField(max_length=250) body = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=20, default=OPEN, choices=STATUS_CHOICES) uuid = models.CharField(max_length=250, default=Utils.generate_uuid) created_at = models.DateTimeField(default=timezone.now) email = models.CharField(max_length=200, null=True, blank=True) class TicketComment(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) body = models.TextField() user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) uuid = models.CharField(max_length=250, default=Utils.generate_uuid) created_at = models.DateTimeField(default=timezone.now) def upload_path(instance, filename): ext = filename.split('.')[-1] name = filename.split('.')[0] if not instance.pk: unique_id = Utils.generate_hex_uuid() uploaddirectory = "static/uploads/%s/" % unique_id os.mkdir(uploaddirectory) return '{}/{}.{}'.format(uploaddirectory, name, ext) class TicketFile(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, null=True, blank=True) ticket_comment = models.ForeignKey(TicketComment, on_delete=models.CASCADE, null=True, blank=True) inputfile = models.FileField(max_length=254, upload_to=upload_path, null=True, blank=True) inputfilepath = models.TextField(null=True, blank=True) name = models.TextField(null=True, blank=True) uuid = models.TextField(default=Utils.generate_hex_uuid) created_at = models.DateTimeField(default=timezone.now) Then my admin file looks like so from tickets.models.ticket import Ticket from tickets.models.ticket_comment import TicketComment from tickets.models.ticket_file import TicketFile from django.contrib import admin class TicketFileInline(admin.StackedInline): model = TicketFile extra = 0 class TicketCommentInline(admin.StackedInline): model = TicketComment extra …