Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python split() list as string not number . in Django and chart.js
I take values from device and split like bellow and append array. After that i send the chart.js and visualize data with line chart. But values comes string not number. When i write the value its correct(etc: 17.53 17.70 18.40) but in the chart its take one by one and draws 1 7 5 3 not 17.53 . Draws by one by one. Probally my split method is wrong. Its take as string like a b c and draws a b. What should i do ? temp = client.query('select * from device_frmpayload_data_Temperature order by time desc limit 10') temp_V= temp.get_points(tags={'dev_eui':'000950df9be2733e'}) temp_data = [] for x in temp_V: y = float(str(x).split("'value': ", 1)[1].split("}")[0]) temp_data.append(y) return render(request, 'Events/charts.html', { 'temp_data' : temp_data, }) #chart data part datasets: [{ label: 'temp values', data:'{{temp_data|safe}}', -
Problem to deploy Django app on Apache it load only the default pagina
I'm trying to deploy this Django app on Apache2 server using the WSGI mod. I set up everything and seems that everything works but instead to load my index, Apache load the default Apache pagina. I checked the WSGI configuration to see if I made some mistake serving the static but seems everything is in order. I also checked the error.log from Apache but I couldn't find anything useful. This is the error.log of Apache: [Thu Sep 30 22:28:57.072809 2021] [authz_core:debug] [pid 34291:tid 140219030382336] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of Require all granted: granted [Thu Sep 30 22:28:57.073467 2021] [authz_core:debug] [pid 34291:tid 140219030382336] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of <RequireAny>: granted [Thu Sep 30 22:28:57.076377 2021] [deflate:debug] [pid 34291:tid 140219030382336] mod_deflate.c(854): [client 77.171.127.237:46746] AH01384: Zlib: Compressed 10918 to 3120 : URL /index.html [Thu Sep 30 22:28:57.182998 2021] [authz_core:debug] [pid 34291:tid 140219047167744] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of Require all granted: granted, referer: http:> [Thu Sep 30 22:28:57.183125 2021] [authz_core:debug] [pid 34291:tid 140219047167744] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of <RequireAny>: granted, referer: http://www.w> [Thu Sep 30 22:28:57.227778 2021] [authz_core:debug] [pid 34291:tid 140219021989632] mod_authz_core.c(817): [client 77.171.127.237:46746] AH01626: authorization result of Require all granted: granted, referer: http:> [Thu Sep … -
Passing Audio Files To Celery Task
I have a music uploading app and believe that it would be smart to pass the files to a celery task to handle uploading. However, when attempting to pass the files, as I will show in my code below, I get a message stating that they are not JSON serializable. What would be the correct way to handle this operation? Everything below uploaded_songs in .views.py is my current code that successfully uploads the audio tracks. It doesn't, however, utilize celery yet. .task.py from django.contrib.auth import get_user_model from Beyond_April_Base_Backend.celery import app from django.contrib.auth.models import User @app.task def upload_songs(songs, user_id): try: user = User.objects.get(pk=user_id) print('user and songs') print(user) print(songs) except User.DoesNotExist: logging.warning("Tried to find non-exisiting user '%s'" % user_id) .views.py class ConcertUploadView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request): track_files = request.FILES.getlist('files') current_user = self.request.user upload_songs.delay(track_files, current_user.pk) try: selected_band = Band.objects.get(name=request.data['band']) except ObjectDoesNotExist: print('band not received from form') selected_band = Band.objects.get(name='Band') venue_name = request.data['venue'] concert_date_str = request.data['concertDate'] concert_date_split = concert_date_str.split('(')[0] concert_date = datetime.strptime(concert_date_split, '%a %b %d %Y %H:%M:%S %Z%z ') concert_city = request.data['city'] concert_state = request.data['state'] concert_country = request.data['country'] new_concert = Concert( venue=venue_name, date=concert_date, city=concert_city, state=concert_state, country=concert_country, band=selected_band, user=current_user, ) new_concert.save() i = 0 for song in track_files: audio_metadata = music_tag.load_file(track_files[i].temporary_file_path()) temp_path = … -
how can we fix send_messasge() missing 1 required positional argument: 'message'
Currently, I am working on a notification feature in Django. I am able to run my created code on localhost, development servers but when I deployed the same code production server then It's throwing the below error send_messasge() missing 1 required positional argument: 'message' below is my model.py code. class All_Device_Notification(models.Model): title = models.TextField(default="") description = models.TextField(default="") link = models.TextField(default="") def __str__(self): return self.title def save(self, *args, **kwargs): filtered_users = User.objects.all() devices = FCMDevice.objects.filter(user__in=list(filtered_users)) devices.send_message(title=self.title, body=self.description, click_action=self.link) super(All_Device_Notification, self).save(*args, **kwargs) Here I am not able to understand that if I am compiling the code on the localhost or development server then it was working well but Why am facing the error in the production server? below is my urls.py file url(r'^devices?$', FCMDeviceAuthorizedViewSet.as_view({'post': 'create'}),name='create_fcm_device'), -
Django - how to create proper categories and subcategories
I am currently working on a store made in Django and I have a problem because I have a model for Category as well as Subcategory. The problem is that I don't really know what I did wrong, because in the html file I try to call both categories and subcategories, but in each category all subcategories are displayed, instead of belonging to a specific category. I would like to ask for your help, and check, if files below are correctly written. Thanks in advance models.py from django.db import models from django.urls import reverse # Class model for category class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('selcorshop:product_list_by_category', args=[self.slug]) # Class model for subcategory class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name def get_absolute_url(self): return reverse('selcorshop:product_list_by_subcategory', args=[self.slug]) # Class model for product class Product(models.Model): subcategory = models.ForeignKey(Subcategory, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) … -
Dropdown menu button transparent for mobile version
Somehow I made transparent drop-down button at my django website. I got reported an errors below. I'll provide code at the end of that error. {% load static %} <!DOCTYPE html> <html lang="en"> <head> {% block bootsrap %} {% load bootstrap4 %} {# CSS Bootstrap #} {% bootstrap_css %} {% endblock bootsrap %} <meta charset="UTF-8"> <meta name="description" content=""> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- The above 4 meta tags *must* come first in the head; any other head content must come *after* these tags --> <!-- Title --> <title>Competitiveness index</title> <!-- <title>Competitiveness index | Base</title> --> <!-- Favicon --> <link rel="icon" href= "{% static 'img/core-img/logo_ci.svg' %}" <!-- Core Stylesheet --> <link href= "{% static 'style.css' %}" rel="stylesheet"> <!-- Responsive CSS --> <link href= "{% static 'css/responsive.css' %}" rel="stylesheet"> <!-- Bootstrap CSS --> <link href= "{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <style type="text/css"> .flex-container { display: flex; } </style> </head> <body> <!-- ***** Preloader Start ***** --> <div id="preloader"> <div class="mosh-preloader"></div> </div> <!-- ***** Header Area Start ***** --> <header class="header_area"> <div class="container-fluid h-100"> <div class="row h-100"> <!-- Menu Area Start --> <div class="col-12 h-100"> <div class="menu_area h-100"> <nav class="navbar h-100 navbar-expand-lg align-items-center"> <!-- Logo --> <a class="navbar-brand" href="{% … -
Why i'm getting this error when I try to import mt csv file into a dbsqlite file with python manage.py?
I'm having some problems to import my csv file to the database of my django project. i'm working on windows prompt. Everything was going great until i try to import the csv with the command(python manage.py load_cursos). I'm getting the follow error: UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 958: character maps to undefined Can someone help me, please? this is my models.py (its all in charfield because first i want to learn how to import correctly, it's a test) from django.db import models class Curso(models.Model): idCurso = models.CharField(max_length=100, blank=True) descricao = models.CharField(max_length=100, blank=True) ordemRelatorio = models.CharField(max_length=100, blank=True) tipoCurso = models.CharField(max_length=100, blank=True) idTipoCurso = models.CharField(max_length=100, blank=True) grupoFiltro = models.CharField(max_length=100, blank=True) valorCurso = models.CharField(max_length=100, blank=True) valorCursoUnidade = models.CharField(max_length=100, blank=True) ordemAprendizado = models.CharField(max_length=100, blank=True) qtdParcelas = models.CharField(max_length=100, blank=True) nivelCertificado = models.CharField(max_length=100, blank=True) reprovaPorNota = models.CharField(max_length=100, blank=True) reprovaPorFalta = models.CharField(max_length=100, blank=True) notaOral = models.CharField(max_length=100, blank=True) notaEscrita = models.CharField(max_length=100, blank=True) paginaMapa = models.CharField(max_length=100, blank=True) idCondicaoPagamento = models.CharField(max_length=100, blank=True) dataAlt = models.CharField(max_length=100, blank=True) horaAlt = models.CharField(max_length=100, blank=True) dataInc = models.CharField(max_length=100, blank=True) horaInc = models.CharField(max_length=100, blank=True) usuarioAlt = models.CharField(max_length=100, blank=True) usuarioInc = models.CharField(max_length=100, blank=True) cursoSemestral = models.CharField(max_length=100, blank=True) contratoWebMostra = models.CharField(max_length=100, blank=True) contratoWebNiveis = models.CharField(max_length=100, blank=True) contratoWebDuracao = models.CharField(max_length=100, blank=True) contratoWebOrdem = models.CharField(max_length=100, blank=True) … -
Django, why doesn't it post to db?
So I made dependent dropdown menu but it won't post to database. What am I doing wrong? Also, is it possible to post this to different table? The thing is, I have 5 of same form on same page each with their on OrderForm, Model Like this named 1 through 5. But it wouldn't post whether I use 1 form per page or 5 forms on same page. I would prefer if there is a way to use raw sql and insert these form data into different table mapping fields to specific fields. models.py class OrderItem(models.Model): vendor_name = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) menu_name = models.ForeignKey(Menu, on_delete=models.SET_NULL, null=True) date_created = models.DateTimeField('date created', auto_now_add=True) note = models.CharField('note', max_length=255, null=True, blank=True) forms.py class OrderForm(forms.ModelForm): note= forms.CharField(widget=forms.Textarea) class Meta: model = OrderItem fields = ('vendor_name', 'menu_name', 'note') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['menu_name'].queryset = Menu.objects.none() self.fields['vendor_name'].widget.attrs['style'] = 'width:250px; height:25px;' self.fields['menu_name'].widget.attrs['style'] = 'width:250px; height:25px;' self.fields['note'].widget.attrs['style'] = 'width:250px; height:100px; resize:none;' views.py def save_order(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') return render(request, '/order_info.html', {'form': form}) order_info.html <div class=""> <form method="post" id="order_Form2" class="form2" menus-url="{% url 'ajax_load_menus' %}"> {% csrf_token %} {{ form.as_p }} {% bootstrap_button 'Pick' button_type='submit' button_class='btn-primary btn-sm … -
django drf model viewset self documenting
Was hoping to create a custom ModelViewSet to inherit from, that creates generalized information on the different CRUD routes. Right now we have to overwrite methods that don't need change. Some views require almost every method to be overwritten or writing functions views etc, but others maybe have 1 or 0 changes from just a ModelViewSet. Using django spectacular this makes models way to huge, and hides relevant logic between a clutter of text. I'm hoping there is a smarter/better way to do this? Example Given the simple model NameTag that is beeing delivered in a test api: models.py from django.db import models class NameTag(models.Model): name = models.CharField(max_length=50) serializers.py from rest_framework import serializers from .models import NameTag class NameTagSerializer(serializers.Serializer): class Meta: model = NameTag api.py from rest_framework import viewsets from .models import NameTag from .serializers import NameTagSerializer class NameTagViewset(viewsets.ModelViewSet): serializer_class = NameTagSerializer model = NameTag using extend_schema the viewset becomes huge. documented_api.py from drf_spectacular.utils import extend_schema from rest_framework import serializers, viewsets class NameTagViewset(viewsets.ModelViewSet): serializer_class = NameTagSerializer model = NameTag @extend_schema( operation_id='New NameTag', description='Create a new NameTag', tags=['NameTags'] ) def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) @extend_schema( operation_id='List of NameTags', description='All NameTags', tags=['NameTags'], ) def list(self, request, *args, **kwargs): … -
Problem with creating tables in sql python file
i got an Error when i'm trying to crate table and my sql server mycursor = mydb.cursor() mycursor.execute("CREATE TABLE countries (name VARCHAR(300), population size INTEGER(10), \ capital city VARCHAR(300))") mycursor.execute("SHOW TABLES") for tb in mycursor: print(tb) can anyone knows what is the problem with the syntax? -
Django Admin | Filter dropdown on Many to Many based on a foreign key relationship selection
I'm trying to figure out the best way to filter horizontally in Django Admin on a model that has a Many to Many relationship. The goal is in the Inline section when one dropdown is populated the dropdown next to it which has a foreign key relationship to the first dropdown will be filtered. There are TypeSets and TypeValues, a TypeSet has many TypeValues ex. if a TypeSet's type is "wood", the TypeValue types would be ["oak", "cherry", "walnut"] These TypeValues then form a ManyToMany Relationship with "Thing" ( along with the included TypeSet_id ) The goal is in the ThingTypeInline within Django Admin when creating a new Thing I can select the TypeSet from the dropdown which would then filter the TypeValue dropdown next to it. Would this be a custom Form? Models: class TypeSet(models.Model): """TypeSet to be used to describe data type""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(max_length=255, unique=True) ..... class TypeValue(models.Model): """TypeValue to be used to describe value in the TypeSet""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(max_length=255) type_set = models.ForeignKey( TypeSet, on_delete=models.CASCADE ) ....... class Thing(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) types = models.ManyToManyField( TypeValue, through='ThingType') .......... class ThingType(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, … -
Django ModelForm: search filter many to many field widget
I'm working with this model: class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools") pools is a m2m field from this model: class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres") I created this ModelForm: class FormulariMostra(ModelForm): class Meta: model = Sample fields = ("name", "sample_id_sex", "pools",) It works fine but the problem is that the pools field can contain thousands of values. A similar question was asked here: Django: Search many to many field while creating object I tried this widget recommended there https://github.com/ExoticObjects/django-better-filter-widget but it seems outdated... Is there any alternative? I know this can be done in the admin but I want to do it in the ModelForm. -
Images aren't loading from AWS S3 in Django
Answer in comments. My images and static files weren't loading from AWS S3 Buckets. And here is How I solved my issue, Check the comments -
django cassandra engine get last item
from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel from django.db import connections def get_tag(car_name, car_type): class Tag(DjangoCassandraModel): __table_name__ = car_name + "_" + car_type time = columns.Integer(primary_key=True, required=True) # unix time in seconds # noqa value = columns.Float(required=True) with connections['cassandra'].cursor() as cursor: cursor.execute("CREATE TABLE IF NOT EXISTS mydatabase." + __table_name__ + " (time INT PRIMARY KEY, value FLOAT);") # noqa def last(): with connections['cassandra'].cursor() as cursor: elem = cursor.execute("SELECT * FROM " + Tag.__table_name__ + " ORDER BY time DESC LIMIT 1;") # noqa return elem def __str__(self) -> str: return str(self.time) + "," + str(self.value) return Tag Usage in code: tag = get_tag(car_name, car_type) last_elem = tag.last() Produced error when calling tag.last(): cassandra.InvalidRequest: Error from server: code=2200 [Invalid query] message="ORDER BY is only supported when the partition key is restricted by an EQ or an IN." Hello. I have a dynamic Django model creation in Cassandra. (time, value) measurements. How to get the last element in the table based on time (primary key)? My implementation has an error. -
Get list of values from grandchildren records
I'm trying to access the grandchildren records in a list to avoid duplicate records. In this example, a tag can only be used once across articles for a given author. I will use the resulting list of grandchildren records in my clean function to return validation errors. class Article(models.Model): tag = models.ManyToManyField(Tag) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Tag(models.Model): class Author(models.Model): Right now I can do this: print(author.articles.first().tag.first()) Travel I'd like to be able to use something like author.articles.tags.all() to return the list and check the submitted form against it to raise a ValidationError message to the user. How can this be done efficiently with the basic Many-to-Many setup without creating an intermediate table for the tag relationships? This is solely in the Admin interface, in case that matters at all. -
pymongo.errors.ServerSelectionTimeoutError [SSL: CERTIFICATE_VERIFY_FAILED]
I am using MongoDB(Mongo Atlas) in my Django app. All was working fine till yesterday. But today, when I ran the server, it is showing me the following error on console Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\admin\appdata\local\programs\python\python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "c:\users\admin\appdata\local\programs\python\python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\core\management\base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py", line 52, in table_names return get_names(cursor) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\django\db\backends\base\introspection.py", line 47, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\djongo\introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py", line 880, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\database.py", line 842, in list_collections return self.__client._retryable_read( File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py", line 1514, in _retryable_read server = self._select_server( File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\mongo_client.py", line 1346, in _select_server server = topology.select_server(server_selector) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py", line 244, in select_server return random.choice(self.select_servers(selector, File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\Lib\site-packages\pymongo\topology.py", line 202, … -
Execute multiple celery tasks inside a celery task
im looking to execute multiple related celery tasks within another celery task. Is this even possible? Code below will give a better idea of what i am trying to accomplish @shared_task(ignore_result=True) def test_job(): try: another_test_job.delay() yet_another_test_job.delay() except Exception as e: logger.error(f'Something happened when collecting edr data ===> {e}') raise @shared_task(ignore_result=True) def another_test_job(): try: print('this is another test') except Exception as e: logger.error(f'Something happened when collecting edr data ===> {e}') raise @shared_task(ignore_result=True) def yet_another_test_job(): try: print('this is yet another test') except Exception as e: logger.error(f'Something happened when collecting edr data ===> {e}') raise My goal is to try to consolidate the amount of tasks i schedule essentially assigning my tasks under one task. I have tried executing my task manually using test_job.apply() results in In [2]: test_job.apply() 2021-09-30 13:57:49,196 amqp DEBUG Start from server, version: 0.9, properties: {'capabilities': {'publisher_confirms': True, 'exchange_exchange_bindings': True, 'basic.nack': True, 'consumer_cancel_notify': True, 'connection.blocked': True, 'consumer_priorities': True, 'authentication_failure_close': True, 'per_consumer_qos': True, 'direct_reply_to': True}, 'cluster_name': 'someclustername', 'copyright': 'Copyright (c) 2007-2020 VMware, Inc. or its affiliates.', 'information': 'Licensed under the MPL 2.0. Website: https://rabbitmq.com', 'platform': 'Erlang/OTP 22.3.4.11', 'product': 'RabbitMQ', 'version': '3.8.9'}, mechanisms: [b'PLAIN'], locales: ['en_US'] 2021-09-30 13:57:49,259 amqp DEBUG using channel_id: 1 2021-09-30 13:57:49,307 amqp DEBUG Channel open 2021-09-30 13:57:49,431 … -
Django merge QuerySet while keeping the order
i'm trying to join together 2 QuerySets. Right now, I'm using the | operator, but doing it this way won't function as an "append". My current code is: df = RegForm((querysetA.all() | querysetB.all()).distinct()) I need the elements from querysetA to be before querysetB. Is it even possible to accomplish while keeping them just queries? -
How can I replace a button with a message after once click on it in Django
I am trying to add a button('Add to your watchlist'), when user click on that the button will replaced with a text which will say 'Item is added to your watchlist'. How can I emplement this on my code? Is there no way (without JavaScript) adding this feature in my web application ? In urls.py: path('listing/<int:auction_id>', views.auction, name='auction'), path('listing/<int:auction_id>/wachlist', views.add_to_watchlist, name="add_to_watchlist") In views.py: def add_to_watchlist(request, auction_id): auction = AuctionListing.objects.get(pk=auction_id) user = User.objects.get(username=request.POST['username']) try: watch_key = Watchlist.objects.get(owner=user) except: watch_key = Watchlist.objects.create(owner=user) auction.watch_item.add(watch_key) return redirect('auction',auction_id=auction.id) In auction.html: <form action="{% url 'add_to_watchlist' auction.id %}" method="POST"> {% csrf_token %} <input type="hidden" name="username" value="{{ user.username }}"/> <input type="submit" class="btn btn-success" value="Add to your watchlist" style="float:right" /> </form> -
Sum of Integers error django.db.utils.ProgrammingError: function sum(jsonb) does not exist
I'm trying to aggregate Sum() to a queryset, the fields are simple IntegerField() but this error appears. Error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/opt/companies/api/v2/views.py", line 86, in get ticket_closed_time=Avg(F("ticket_closed_time")), File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 379, in aggregate return query.get_aggregation(self.db, kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 489, in get_aggregation result = compiler.execute_sql(SINGLE) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return … -
How do I schedule objects to created for a model in django?
I have a notice model that creates s notice (it contains title, description and date). I would like to schedule notices to be created at certain dates. Basically, I mean using another model I want to schedule and create the notices at that date specified. How would I do this? What's the easier road to achieve this? All I can think of is rabbitmq and celery. And i don't even know how it would create s notice at a dynamic date. -
How to create a form with foreign key django
I'm working on a Django project and getting the Value error below. I think the problem is in the category field because if I will comment it in new.html, it adding a listing without the problem. However, I can't find where is the error. ValueError at /new The view auctions.views.add_listing didn't return an HttpResponse object. It returned None instead. This is my models.py: class Category(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class Listing(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=256) price = models.DecimalField(max_digits=24, decimal_places=2) photo = models.ImageField() bid = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) category = models.ManyToManyField(Category, default=None, blank=True) def __str__(self): return self.title views.py: def add_listing(request): if request.method == "POST": form = ListingForm(request.POST, request.FILES) print('FORM CREATED') print(form.is_valid()) if form.is_valid(): print('FORM IS VALID') print(form.cleaned_data) new_listing = form.save(commit=False) return HttpResponseRedirect(reverse(listing, args={new_listing.pk,})) else: pass else: return render(request, "auctions/new.html",{ 'category':Category.objects.all() }) new.html: <form action="" method="POST" name="listing" enctype="multipart/form-data"> {% csrf_token %} <h4>Title</h4> <input type="text" name="title"> <h4>Choose category</h4> <select name="category" id=""> {% for type in category %} <option value="{{ type }}" name="category">{{ type }}</option> {% endfor %} </select> <h4>Description</h4> <input type="text" name="description"> <h4>Price</h4> <input type="number" name="price"> <h4>Photo</h4> <input type="file" accept="image/*" name="photo" id="file"> <!-- <p>Or provide URL of image</p> <input type="text" name="image_url"/> --> … -
Why use get_absolute_url function not work?
I am trying to use get_absolute_url to get an object (post_detail) from (post_list), but returns with no object and still in the same page (post_list) with no error. in views.py : # Object list using Function-based-views def post_list(request): post_list=Post.objects.all().order_by('-created_at') lastest=post_list.order_by('-created_at')[:4] last_post= post_list.order_by('-created_at')[0] context={ 'allpost':post_list, 'latest':lastest, 'lastpost':last_post } return render(request,'post/post_list.html',context) # Post_singl_object using DetailView class PostDetail(DetailView): model=Post context_object_name='post_detail' def get_context_data(self, **kwargs): context= super().get_context_data(**kwargs) context['slug']=super().get_context_data(**kwargs) return context urls.py : from django.urls import path from . import views app_name="allpost" urlpatterns = [ path('', views.post_list), path('<slug:slug>',views.PostDetail.as_view(),name='post_detail'), ] in my templates in page (post_list.html) i loop for list objects to get (title,headline, image, and author), but in a link i use ( def get_absolute_url(self): return reverse("post_detail", kwargs={'slug': self.slug} ) to redirect to post page, but that's not work and still in same page (post_list). in post_list.html : {% for post in allpost %} <a href="{{ post_detail.get_absolute_url }}" class="stretched-link">Continue reading</a> {% endfor %} any idea ? -
Django foreign key as primary key?
The question In Django, is it possible to use a foreign key as the primary key for a model? For example: Context Let's say that we have class Reporter that has many Articles, but if we remove our reporter from our database, we also want the articles that belonged to them to be deleted. The schema is a one-to-many relationship, where one reporter has many articles, and the existence of the article instances in the database relies on the reporter instance. What I am confused about specifically What kind of Django relationship would I need to achieve this business requirement? Unfortunately, I have read all of the Django documentation. Therefore, I cannot find which database relationship makes the most sense, and I hope someone with more experience than me in Django and PostgreSQL can help out. Bonus points Imagine that each article needs to be in a specific arbitrary order and that this is also a constraint of the database relationship. -
AWS S3 Lambda Trigger Not Working When Uploaded to Bucket Subfolder
I have a Lambda Python function that will resize images on upload. Everything is working correctly, but only when I upload directly to the bucket. When I upload files to the bucket/uploads/ folder, it would no longer trigger the resize function. I have tried the filtering options in the trigger settings uploads/ to no avail. Assuming it is related to my Lamda function and the folder should/must also be included? Here is my Lambda function: def lambda_handler(event, context): for record in event["Records"]: bucket = record["s3"]["bucket"]["name"] key = record["s3"]["object"]["key"] download_path = "/tmp/{}{}".format(uuid.uuid4(), key) upload_path = "/tmp/resized-{}".format(key) s3_client.download_file(bucket, key, download_path)