Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading to MEDIA_URL instead of referencing static image
I have some default images stored in my static folder that we use for migrations. I reference these when deploying new features in order to batch create a large number of icons: # Set Icon icon_path = finders.find(my_path) if icon_path: icon_file = open(icon_path, "rb") icon = File(icon_file) else: raise Exception("Icon file not found.") obj.icon = icon One thing I've noticed with this method is that the saved icon references the static folder URL instead of referencing my S3 MEDIA_URL (configured with django-storages). I'm wondering if there's something I'm missing that could be causing this to happen, because when I upload an image and set it the same way from a DRF serializer it goes to S3 instead. -
Using TailwindCSS in a Django project hosted on Github
I want to use Django together with TailwindCSS in a personal web project and followed two instructions for setting it all up: on the one hand the installation instructions on https://tailwindcss.com/docs/installation on the other hand this Youtube tutorial (because the installation guide was too short for my limited understanding of the topic). https://www.youtube.com/watch?v=lsQVukhwpqQ Since I am not familiar with node.js and npm, i am unsure how to store the resulting project in Github and reproduce it on other computers. The structure of the Django project is no problem, I am familiar with it. I am unsure about the files and folders related to Tailwind and Node. After the tutorial I had a "node_modules" and a "local-cdn" folder as well as "package.json" and "package-lock.json" and a "tailwind.config.js". My question would be: which files present at the end of the two tutorials above should be synced with Github, which should not be synced and what to set up on a second machine (beyond installing node and django obvsly) to continue working on this already existing project there (in contrast to the tutorials above describing how to start a new project)? -
Django 404 I cannot get Django to redirect 404s to my homepage
I'm having a problem getting handler 404 to redirect to my homepage. Here's what I have and tried... In settings.py DEBUG=False In views.py class view_404(request, exception=None): return render(request, "mysite/index.html") In urls.py From django.conf.urls import handler404 urlpatterns = [ path('', views.index, name='index') ] handler404 = "mysite.views.index" I've tried putting the view_404 function directly in the urls.py file, I've tried handler404 = views.index. I've tried handling 404s in my nginx.conf file error_page 404 =200 /index.html; and error_page 404 /index.html; location /index.html { root path/to/template; internal; } I have not been able to get any of these to work... -
Django : best place to store constants used in view and Celery tasks
I'm looking for advice regarding project structure in my Django app. I want to define a constant that is used both in a view and in a background task (Celery to be specific), but I am not sure where this should be placed. The constant defines the number of records to be shown to the user. My model represents an image, and only the recent 100 records need to be displayed on the page. Older records can be deleted, and there is a separate Celery task that cleans up such records on a weekly basis. I have defined this 100 as NUM_RECORDS_TO_SHOW in my model class, but I am not sure if this is the best place, since I am exposing my model to the business logic. Defining this constant in my view seems also a bad idea, as this could lead to circular imports. -
Why my views.py doesn't save submitted csv file in data folder in my app directory in Django project?
Hello I am working on a project Django. I am trying to save a file after users submits it from webpage. I created views and HTML.. part of the views.py, html and urls.py are provided below. Can i get some help why my code is not saving file in data folder in my app directory? views.py class CsvPlot(View): def save_uploaded_file(self, request, file): if request.method == 'POST' and request.FILES[file]: uploaded_file = request.FILES['document'] # attribute = request.Post.get("attribute") # print(attribute) # check if the file ends with csv if uploaded_file.name.endswith('.csv'): save_file = FileSystemStorage() name = save_file.save(uploaded_file.name, uploaded_file) print(name) # Let's save the file in the data folder current_dir = settings.BASE_DIR / 'ml_in_geotech' file_directory = os.path.join(current_dir, 'data') if not os.path.exists(file_directory): os.makedirs(file_directory) self.file_path = os.path.join(file_directory, name) self.readfile(request, self.file_path) request.session['file_path'] = self.file_path else: return HttpResponse('Invalid file type. Only CSV files are allowed.') My HTML <div class="upload_file"> <h2>Train Your Data</h2> <form method="POST" enctype="multipart/form-data" action="/"> {% csrf_token %} <input type="file" name="document" id="document" required="required"> <button type="submit">Submit</button> </form> {% block messages %} {% if messages %} <div class="container" style="color: firebrick; margin-top: 20px" > {% for message in messages %} {{ message }} {% endfor %} </div> {% endif %} {% endblock %} </div> My urls.py path('csv-plot/', views.CsvPlot.as_view(), name='csv_plot'), ] -
Overriding the default validation for a Django admin Foreign Key field
I have Django models that inherit from an Archive class in which the default manager (objects) is replaced with a query that does not return archived records. This works well throughout the system. However, in admin, when a record with a foreign key attempts to validate and that foreign key instance is an archived record, the validation attempts to use the new default manager, objects which filters out archived records as opposed to the objects_all manager which returns all records - and since an archived record is not returned using objects, the save fails with "instance does not exist". Here is a simplified example: class Inv(AbstractArchive): item_code = models.CharField(max_length=20, primary_key=True) qty = models.IntegerField() def __str__(self): return f"{self.item_code}" class Txn(AbstractArchive): inv = models.ForeignKey(Inv) date = models.DateField() added = models.IntegerField My admin for Txn looks like this (I defined a form in admin with a queryset that gets all the records, even those marked as archived - I also included a clean method hoping this would override the form's default validation that uses the objects manager) class TxnForm(forms.ModelForm): class Meta: model=Txn def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['inv'].queryset = Inv.objects_all.all() def clean_inv(self): inv= self.cleaned_data['inv'] if not Inv.objects_all.filter(inv=inv).exists(): raise forms.ValidationError("Invalid inventory record selected.") … -
How to update m2m objects with django formsets?
I'm starting this project in which I have an Order class with an m2m relationship with an Item class using the throug argument with an ItemTimes class. The idea is to add several items to an order registering also it times. For that I use a model formset. The creation of the order goes well but to update items I can't even get to the point in which the formset is valid. Printing the formset errors throws this: [{'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {'id': ['This field is required.']}, {}, {}, {}, {}, {}] but in the indexes where says "This Field is required" is where ItemTimes objects are selected. Help please. Here models.py """orders models""" # django from django.db import models # local from ..customers.models import Customer from ..kits.models import Kit from ..items.models import Item from ..executors.models import Executor class Order(models.Model): """Pre Bill document to register job details performed""" customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, verbose_name="Cliente") symptom = models.CharField('Síntoma', max_length=100) flaw = models.CharField('Defecto', max_length=100) repair_description = models.CharField('Reparación', max_length=100) folio = models.CharField('No. folio', max_length=10) # next four attributes are related to the modality of the order check_diagnosis = models.BooleanField('Revisión/Diagnóstico') repair = models.BooleanField('Reparacón') … -
Django: Update all records in a table when I insert a new record
hello friends i need help! It turns out that I have a model which has several properties, I use it to obtain the consumption of the readings of a meter. The consumption is obtained through some property and then I obtain the total consumption in another property. class ConsumoElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='consumoelect') fecha = models.DateField(default=datetime.now) fecha_AM = models.CharField(max_length=20) lec_madrugada = models.IntegerField(default=0) lec_dia = models.IntegerField(default=0) lec_pico = models.IntegerField(default=0) reactivo = models.IntegerField(default=0) dato = models.IntegerField(default=0) total = models.IntegerField(default=0) def __str__(self): return '%s' % (self.pgd) def get_cm(self): c_m = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_madrugada', 'fecha')) if not c_m: return 0 else: if not c_m[0]['lec_madrugada']: return 0 else: return ((c_m[0]['lec_madrugada'] - self.lec_madrugada)) consumo_m= property(get_cm) def get_cd(self): c_d = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_dia')[0:1]) if not c_d: return 0 else: if not c_d[0]['lec_dia']: return 0 else: return ((c_d[0]['lec_dia'] - self.lec_dia)) consumo_d= property(get_cd) def get_cp(self): c_p = list(ConsumoElect.objects.filter(pgd=self.pgd).filter(fecha__gt=self.fecha).order_by('fecha').values('lec_pico')[0:1]) if not c_p: return 0 else: if not c_p[0]['lec_pico']: return 0 else: return ((c_p[0]['lec_pico'] - self.lec_pico)) consumo_p= property(get_cp) def get_total(self): return (self.consumo_d + self.consumo_m + self.consumo_p) consumo_total= property(get_total) def save(self, *args, **kwargs): fe=date.strftime(self.fecha, "%Y-%m") self.fecha_AM = fe self.total = self.consumo_d + self.consumo_m + self.consumo_p return super().save(*args, **kwargs) class Meta: unique_together=['pgd', 'fecha'] verbose_name = 'Consumo Electrico' verbose_name_plural = 'Consumo Electrico' ordering = ['pgd', 'fecha'] db_table … -
Django unable to submit form, getting error 'Select a valid choice. That choice is not one of the available choices'
I have a django form in which, 'Select_Category' will be filtered based on the value selected in 'Select_Type'. I am using an Ajax query to achieve this. When executing, I can see the filter is working properly as expected. But when I click submit, I get error on page 'Select a valid choice. That choice is not one of the available choices' and the 'Select_Category' filed is getting emptied. forms.py class Test_Form(forms.Form): Select_Type = forms.ChoiceField(choices=[('Incoming', 'IN'), ('Outgoing', 'OUT')], initial='Outgoing') Select_Category = forms.ModelChoiceField(queryset=Categories.objects.all()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['Select_Category'].queryset=Categories.objects.none() Since the form is not being submitted, I suspect some issue with my forms.py. Can someone help? -
Django Serializer to group fields
I want to build a simple endpoint /users/ that returns output like the following: { ids: [ "e3fa5cbe-e89e-4017-bbd3-546019247932", "94c1f979-f122-471b-a694-e748f5d95c25", "30f20792-18d9-4db0-8dde-9ad62d239928", "2ee0399d-881a-43b5-ad53-a741507e12c1", "359b6550-bcfd-4c41-99be-3422cbba3da5" ] } The id's belong to the user objects themselves. I have a model viewset defined as such: class UserIdViewSet( viewsets.ModelViewSet, mixins.ListModelMixin, ): queryset = User.objects.all() permission_classes = [IsAdmin] serializer_class = IdListSerializer filterset_class = UserFilter def get_queryset(self): return User.objects.filter( company=self.request.user.get_company() ) But I am having difficulty writing IdListSerializer. ChatGPT and Copilot suggest variations of the following: class IdListSerializer(serializers.Serializer): ids = serializers.ListField(child=serializers.UUIDField()) def to_representation(self, instance): return {"ids": [str(user.id) for user in self.objects.all()]} But instance is not itterable. We really want the collection not the instance. Is this possible using DRF without resorting to an APIView? -
OpenSlide for django can't open tif format (and also other formats)
I'm trying to write adjust zoomable image app viewer for digital pathology and using django with python and OpenSlide. and the last one can't open tif (and also other formats) image that i upload. here is the error after uploading: OpenSlideUnsupportedFormatError at /upload_image/ Unsupported or missing image file how i can fix it? i'm sure that's images is saved in a supported format with openslide. -
Django Custom API Endpoint with two parameters
I want to build a fairly simple API endpoint in a Django app I inherited. I'm new to python and Django The app uses views.py with classes that extend ModelViewSet. It also uses a urls.py with entries like this: router.register('agent_licenses', views.AgentLicenseViewSet) and this one I came up with: router.register(r'agent_licenses/(?P<agent_id>\d+)/<state_id>\d+/', views.AgentLicenseViewSet) I need to build the fastest-responding endpoint possible and so I plan to use a custom SQL query that returns a True/False. Is there some straightforward way to build an endpoint (hopefully in views.py, although if that's not possible, that's ok.) that will show up in Swagger without having to wrestle with Models, ModelViewSet, urls.py, Serializers, etc? I have managed to get close, using the AgentLicenseViewSet, like this: (Ignore the actual code in the endpoint method - it's just test code at this point) class AgentLicenseViewSet(viewsets.ModelViewSet): """Agent license REST view """ queryset = models.AgentLicense.objects.all() serializer_class = serializers.AgentLicenseSerializer filter_backends = (django_filters.DjangoFilterBackend,) filterset_class = filters.AgentLicenseFilter @action(methods=["GET"], detail=True) # def has_license_in_state(self, agent_id: int, state_id: int) -> Response: def has_license_in_state(self, *_args, **_kwargs ) -> Response: #print(state_id) #print(pk) # return Response(data={'message': False}) return Response(data=False) # return False But - when I run this, I get an endpoint that appears to be ignoring the \d+ in … -
(Django) How can I enable cross site verification to my website?
I am building a third party comment section. How can I allow users to sign into my website and make comments on others sites? I already have the scripts for users to import but I can’t seem to allow users to sign in and pass a “request” to my website. I’m using django by the way. -
Vue Static files are not loading
So I am developing a django application and using vue for frontend. I have connected the vue app and the django app using views.py. But when I am trying to run the application for some reason django is not loading the static files properly. Here is my settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-^**********************************' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'store_closure.apps.StoreClosureConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'corsheaders', 'CapstoneProject', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware' ] ROOT_URLCONF = 'CapstoneProject.urls' CORS_ORIGIN_ALLOW_ALL = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CapstoneProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'postgres', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432', } } 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True ROOT_PATH = os.path.dirname(__file__) STATIC_URL = '/static/' # STATIC_ROOT = 'var/static_root/' STATICFILES_DIRS = … -
Allow locally hosted Django App Access over WAN
I am currently working on developing a webapp and working with a partner on the other side of the state. I would like to allow them to access the webapp for testing and development purposes but cant seem to be able to figure out how to get the connection working. I have enabled port forwarding for port 8000 and have already attempted to run the server using my local IPv4 address. I can connect via LAN, but my partner cannot connect through their browser. We already have an established MySQL connection and all we had to do was forward port 3306 and use my router IP for WAN but that does not seem to be working for Django. Any suggestions on getting this working? -
Iterate over Django Model object to translate (translate 3.6.1) specific fields (all TextFields and all JSONFields)
How does one iterate over a Django Model object to translate all TextFields and all JSONFields before sending to template. Let me elaborate. I have a Django model models.py like the following: SOME_TEXT_CHOICES = ( ('choice_one', _('Choice One')), ('choice_two', _('Choice Two')), ('choice_three', _('Choice Three')) ) from django.db import models class SomeModel(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) some_title = models.CharField(max_length=100, null=False, blank=False) some_address = models.CharField(max_length=100, blank=True) sometime = models.TimeField(default=datetime.time(15, 00)) some_choices = models.CharField(max_length=15, choices=SOME_TEXT_CHOICES, null=False, blank=False) some_text_one = models.TextField(max_length=1000, null=False, blank=False) some_text_two = models.TextField(max_length=1000) some_json_field = models.JSONField(help_text=_('JSON field: {"key_text1":"value_text1","key_text2":"value_text2"}'), null=True, blank=True) And I have a views.py: from django.shortcuts import render, get_object_or_404 from translate import Translator from .models import SomeModel def detail_view(request, slug): context = {} context_somemodel = get_object_or_404(SomeModel, slug=slug) translator = Translator(from_lang='en', to_lang='es') # How to iterate through the context_somemodel to update all # TextField(s) and JSONField(s) with the translator.translate() method # before sending to the template? context['somemodel'] = context_somemodel return render(request, 'templates/detail_template.html', context) The original content of the model is in English and it should be translated into Spanish. I tried to update/translate a single field with SomeModel.objects.filter(slug=slug).update(some_text_one=translator.translate(F('some_text_one'))) but I get an error message: name 'F' is not defined. -
How to find this function
See code below. It is crashing at the line import_recording(info, recording_path) The problem is, I can't debug this function because I cannot find where import_recording() is defined. I do not see it in any of our files, and I can't find any helpful info from Callable, typing, or @logme.log. I believe it is calling on info from a db, and we have the correct info in the db, but it is not possible to verify this without access to this function. How can I find where this function is defined? #!/usr/bin/env python3 # -*- coding: UTF-8 -*- import os from pathlib import Path from typing import Callable import logme # type: ignore from typing_extensions import Literal from librecval.extract_phrases import AudioSegment, RecordingExtractor, Segment from librecval.recording_session import parse_metadata from librecval.transcode_recording import transcode_to_aac ImportRecording = Callable[[Segment, Path], None] class RecordingError(Exception): """ The error that gets raised if something bad happens with the recording. """ Format = Literal["wav", "m4a"] @logme.log def initialize( directory: Path, transcoded_recordings_path: str, metadata_filename: Path, import_recording: ImportRecording, recording_format: Format = "m4a", logger=None, ) -> None: """ Creates the database from scratch. """ dest = Path(transcoded_recordings_path) assert directory.resolve().is_dir(), directory assert ( dest.resolve().is_dir() ), f"audio destination is not a folder: {dest.resolve()}" assert metadata_filename.resolve().is_file(), … -
django redirect url Not Found 404 during working with dynamic forms HTMX
In the view function, I redirect when making a post-request to refer-urk, to which I pass the id of the saved class instance, however, this id is lost and I get 404 Not Found. models.py: class Position(models.Model): position_name = models.CharField(max_length=255, blank=True, verbose_name='Position') created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user by', blank=True, null=True) date_create = models.DateTimeField(auto_now_add=True) date_update = models.DateTimeField(auto_now=True) class Meta: ordering = ['date_create'] def __str__(self): return self.position_name class Contacts(models.Model): pos = models.ForeignKey('Position', blank=True, null=True, on_delete=models.SET_NULL, verbose_name='Position') contact_label = models.CharField(max_length=100, blank=True, verbose_name='Contact label') contact_value = models.CharField(max_length=255, blank=True, verbose_name='Contact value') def __str__(self): return self.contact_label forms.py: class CreateCVContactForm(forms.ModelForm): class Meta: model = resume.models.Contacts fields = ( 'contact_label', 'contact_value' ) In views.py usnig def createcvcontacts i do redirect for POST-request and pas id of saved object instance to url and then with HTMX i get this id in def ditailcontact which renders detail info abot object instance and pass context to contact_detail.html template: views.py: @login_required(login_url='/users/login/') def create_cv_contacts(request, pk): ''' functions for working with models.Contacts ''' position = Position.objects.get(id=pk) contacts = Contacts.objects.filter(pos=position) form = CreateCVContactForm(request.POST or None) if request.method == "POST": if form.is_valid(): contact = form.save(commit=False) contact.pos = position contact.save() return redirect("resume:detail-contact", pk=contact.id) # here this redirect else: return render(request, "resume/partials/contact_form.html", context={ "form": form }) context = … -
Django and MongoDB Error - REALLY WANT TO KNOW
This is a problem with Django connecting to MongoDB I'm building a Django project. And I want to connect my project to MongoDB. But I have some problem. It is really stressful. I set my code in settings.py like below. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'portfolio', 'CLIENT': { 'host': 'mongodb+srv://mmastrangelo1120:Bluecomet20040117@bluecomet.wxi3uwk.mongodb.net', 'username': 'mmastrangelo1120', 'password': 'Bluecomet20040117', 'authMechanism': 'SCRAM-SHA-1', 'authSource': 'admin' } } } Of course I installed djongo successfully. Every packages were installed, but it shows only error like this when I run any command like py manage.py migrate or py manage.py runserver: django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How to get specific details from a tag web scraping
I'm trying to scrape a specific details as a list from a page Using Beautifulsoup in python. <p class="collapse text in" id="list_2"> <big>•</big> &nbsp;car <br> <big>•</big> &nbsp;bike&nbsp; <br> <span id="list_hidden_2" class="inline_hidden collapse in" aria-expanded="true"> <big>•</big> &nbsp;bus <br> <big>•</big> &nbsp;train <br><br> </span> <span>...</span> <a data-id="list" href="#list_hidden_2" class="link_sm link_toggle" data-toggle="collapse" aria-expanded="true"></a> </p> I need a list with every text contained in the p tag like this, list = ['car', 'bike', 'bus', 'train'] from bs4 import BeautifulSoup import requests response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') p_tag = soup.find("p", {"id":"list_2"}) list = p_tag.text.strip() print(list) output: • car• bike • bus• train how to convert this as a list like, list = ['car', 'bike', 'bus', 'train'] -
How to fetch data at the moment the database updates, without refreshing the page, in Django?
In a web application that I'm building using Django, there is a filed in the main page that fetches a price float from the database and shows it, and I need it to be updated every time that the source price (in the database) gets updated, or within some seconds. And I need that to be without refreshing the page, kind of live you can say. Is there any possible way to reach this without using Django channels, e.g. by using JavaScript or anything else? -
after user logged in... its not redirecting to comments page .when i added ID..to comments in urls.py..then sudden its not redirecting
reverse for 'comments' with no arguments not found. 2 pattern(s) tried: ['comments/(?p[0-9]+)\z', '\ comments/(?p[0-9]+)/\z'] enter image description here [enter image description here] (https://i.stack.imgur.com/av1iG.png) enter image description here -
How to join 2 Models in Django using 2 common columns?
I have 2 tables in Django, one for stock data and another for stock metadata. The date and ticker together are unique in each model, class BulkData(models.Model): date = models.DateField() ticker = models.CharField(max_length=10) name = models.CharField(max_length=400) type = models.CharField(max_length= 20) exchange_short_name = models.CharField(max_length=5) MarketCapitalization = models.DecimalField(max_digits=40, decimal_places=2) request_exchange = models.CharField(max_length=20) class ohlcdata(models.Model): date = models.DateField() ticker = models.CharField(max_length=10, null=False) open = models.DecimalField(max_digits=15, decimal_places=5, null = True) high = models.DecimalField(max_digits=15, decimal_places=5, null = True) low = models.DecimalField(max_digits=15, decimal_places=5, null = True) close = models.DecimalField(max_digits=15, decimal_places=5, null = True) volume = models.DecimalField(max_digits=40, decimal_places=0, null = True) I need todo a join operation on date and ticker and right now I'm using a raw SQL query. query3 = "SELECT * FROM stocklist_bulkdata LEFT JOIN stocklist_ohlcdata ON `stocklist_bulkdata`.`date` = `stocklist_ohlcdata`.`date` AND `stocklist_bulkdata`.`ticker` = `stocklist_ohlcdata`.`ticker` WHERE `stocklist_bulkdata`.`date` = '2023-03-30'" qs3 = BulkData.objects.raw(query3) How can I do this using Django QuerySet instead of raw SQL query? Tried using raw SQL query, looking to do this using Django QuerySet -
Django error: Exception Value: Cannot resolve keyword 'tags' into field. Choices are: date, id, rp_tags, rp_title, slug, tagged_items, url
Currently, I am learning Django and with it, I am building a non profit organization's website. It is almost like a blog website except for like, comment features. Anyways, there's a page where all the reports are listed and these have tags. I used Django-taggit. I followed through a tutorial to show the tags and making it clickable and filter by tags - but I am running into the following error: error1 error2 Here are my relevent model, view, app/url and template files: from django.utils import timezone from django.utils.translation import gettext_lazy as _ from taggit.managers import TaggableManager class Report(models.Model): rp_title = models.CharField(max_length=500) slug = models.SlugField(max_length=300, unique_for_date='date') url = models.URLField(max_length=500) date = models.DateTimeField(default=timezone.now) rp_tags = TaggableManager() # rp_body = models.TextField() def __str__(self): return self.rp_title class Meta: ordering = ('rp_title',) def get_absolute_url(self): return reverse('report:report_detail', args=[self.slug]) class ReportListView(ListView): model = Report queryset = Report.objects.all() context_object_name = 'reports' template_name = 'blog/report_list.html' class ReportTagView(ListView): model = Report context_object_name = 'reports' template_name = 'blog/report_list.html' def get_queryset(self): return Report.objects.filter(tags__slug=self.kwargs.get('tag_slug')) <div class="sidebar__single sidebar__tags"> <h3 class="sidebar__title">Tags</h3> <div class="sidebar__tags-list"> {% for tag in report.rp_tags.all %} <a href="{% url 'blog:report_tag' tag.slug %}" class="link-light text-decoration-none badge bg-secondary"> {{ tag.name }} </a> {% endfor %} </div> </div> app_name = 'blog' urlpatterns = [ … -
Why changes made in Wagtail's Editor only appear with a delay in the backend (although can be seen in front tend)?
For several months now, when I edit a Page in the Editor of Wagtail and the click "Save", these changes sometimes (often at certain times) disappear fron the Editor. I can see it because when I edit content, I immediately go check the result in frontend and go back to the Editor to edit mistakes for example. In thoses situations, I can see the right content in front end, but not in the back end. I eventually discovered that I need to wait, and after a few minutes at most, the changes appear back in the Editor. Sometimes, if I make successive editions, some of them will appear first, and then the other. Simple example : I add a picture in a blog post, click Save or Publish. I can see the picture in front end, but when I come back to edit this page in back end, the picture is not there anymore. If I wait a little (either come back or just wait and refreh the page in the Editor), the picture will (re)appear in the Editor. Note that the CMS seems to really save the changes because I can see them in front end and in the …