Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not Found: /static/frontend/styles.css (Docker, Django, Nginx)
I am trying out docker for the first time to deploy in production environment I followed some you- tube tutorials but i was successful in containerizing my Django project. but when i run it nothing appears and i get a 404 error saying not found static/fronted/styles.CSS. Please refer to the attached snippet: error: Here is my Docker file: FROM nikolaik/python-nodejs:python3.8-nodejs14-bullseye ENV PYTHONUNBUFFERED 1 ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 RUN python3 -m pip install --upgrade pip RUN set -ex && mkdir /app WORKDIR /app # Copy the requirements file and install dependencies COPY d_requirements.txt /app/ RUN pip install -r d_requirements.txt # Copy the application code COPY . /app/ # Create the /opt/ai_sensei_data_source directory and set permissions RUN mkdir /opt/ai_sensei_data_source WORKDIR /opt RUN chmod a+x+w+r ai_sensei_data_source # Copy the .env file to /opt/ai_sensei_data_source/ COPY /.env /opt/ai_sensei_data_source/.env # Change back to the frontend directory to install frontend dependencies WORKDIR /app/frontend # Install frontend dependencies RUN npm install -f RUN npm install -g @angular/cli RUN ng build --configuration production # Copy build static files to nginx conf dir & set permissions RUN mkdir -p /home/kchavan/Desktop/dlops-portal/static RUN cp -r /app/static/* /home/kchavan/Desktop/dlops-portal/static/ # # RUN chown -R <user>:<group> /home/kchavan/Desktop/dlops-portal/ && \ # # chmod -R … -
Can not configure postgres database in GitHub actions pipeline using Docker
I am creating pipeline for my Django Project with GitHub actions and can't make it working correctly. As I use docker, when I start the Docker and start my tests with 'python manage.py test' it works correctly. But when my tests are started I get an error. The reason is probably is that it does not know how to connect to DB, as Docker works with that in my case. I tried to use github secrets, but it seems that it does not work. Here is the traceback in GitHub Actions: Creating test database for alias 'default'... /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/postgresql/base.py:405: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Found 2 test(s). File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = … -
Semantic-ui multiple How about customizing the display?
I have created a multi-selection dropdown box, but I don't want it to increase by one every time I click on it. I envisioned that it would display no more than three values, and if it did, it would display "4 for 10 selection", is there anything I can do to make this happen? I have tried this method but it gives me an error. //Customize the text that is displayed after multiple selections onLabelCreate: function(value, text) { if ($('.ui.dropdown').dropdown('get value').length > 3) { return '4 of 6 selected'; } } -
Django Form Does Not Validate With Correct Files
class RentalImageForm(forms.Form): images = forms.FileField(validators= [FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'], message='Only JPG, JPEG, PNG, and GIF files are allowed.')]) @login_required def createListing(request): if request.method == 'POST': createListingForm = RentalForm(request.POST) if request.FILES.getlist('images'): uploaded_files = request.FILES.getlist('images') print(uploaded_files) for files in uploaded_files: rental_image_form = RentalImageForm({'images':files}) if rental_image_form.is_valid(): print('VALID') else: print(rental_image_form.errors) <input type="file" name="images" accept="image/*" required multiple id="id_images" /> _____________________________________________________ I am trying to validate each file I upload to my input and then put them in a loop to verify that all files are in correct extensions. Even when my extensions are all correct my Rental Image Form gives out false when I check with .is_valid(). Overall I have checked and seen that my images files are correctly uploaded but when it comes to validating the form it fails. -
toggle table row based on unchecked checkbox
Not super familiar with frontend, but I have 4 checkboxes I'm using to filter table data. Any number of them can be selected at once. What I want to accomplish: get all unchecked boxes if no boxes are checked pass (meaning don't hide any rows) if a box is checked, for any box that is NOT checked, exclude the row associated with that unchecked box This is for a Django app and the table row id is being generated via database query. The table will have max 100 rows. Per the query I'm executing, any table row will be either: id="audio", id="video", id="writing", id="games" HTML: <div> <input type="checkbox" value="music" id="music_filter"> <input type="checkbox" value="video" id="video_filter"> <input type="checkbox" value="writing" id="writing_filter"> <input type="checkbox" value="games" id="games_filter"> </div> <table class="table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> {% for i in query_set %} <tbody> <tr id="{{i.media_type}}"> <td>{{some data}}</td> <td>{{some other data}}</td> </tr> </tbody> I have jQuery loaded via CDN in the html file and trying this: JQUERY/JS: $(document).ready(function(){ $('#music_filter', '#video_filter', '#writing_filter', '#games_filter').on('click',function(){ var notChecked = $("input:checkbox:not(:checked)"); if (notChecked.length > 0) { for (let i = 0; i < notChecked.length; i++) { $('#i').toggle(); }; }; }); }); A little help to see my mistake(s)? Thanks! -
Django: Auto populate data based on selection
I am trying to create an invoice/PO Form and need some help. I am using 4 models: Client, Shipping, Billing, and PO models. I have the OneToOne relationship between shipping and billing models to the client model and both as foreign keys (please let me know if this method is still ok) in PO model. models.py ClientBillingAddress and ShippingAddress are identical, except "billing" is replaced with "shipping" class ClientBillingAddress(models.Model): client = models.OneToOneField(Client, on_delete=models.CASCADE, related_name='billing_address') billing_location_name = models.CharField(max_length=255, unique=True) address_line_1 = models.CharField(max_length=200, blank=True, null=True) address_line_2 = models.CharField(max_length=100, blank=True, null=True) address_city = models.CharField(max_length=50, blank=True, null=True) address_province = models.CharField(max_length=50, blank=True, null=True) address_postal = models.CharField(max_length=15, blank=True, null=True) address_country = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=15, null=True, blank=True) email_to = models.CharField(max_length=150, null=True, blank=True) email_cc = models.CharField(max_length=150, null=True, blank=True) bill_contact_name = models.CharField(null=True, blank=True, max_length=50) is_default = models.BooleanField(default=False) def get_formatted_address(self): address_lines = [self.billing_location_name, self.address_line_1, self.address_line_2] address_city_info = f"{self.address_city}, {self.address_province}, {self.address_postal}" address_lines.append(address_city_info) address_lines.append(self.address_country) return "\n".join(address_lines) def __str__(self): return self.billing_location_name class ClientPO(models.Model): client_PO_number = models.CharField(max_length=50, unique=True) customer_company = models.ForeignKey(Client, on_delete=models.CASCADE, related_name="customer_name_PO") order_reserved_total = models.PositiveBigIntegerField(default=0) order_total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_line = models.PositiveBigIntegerField(default=0) order_product = models.ForeignKey(InventoryItemDetail, on_delete=models.CASCADE, related_name="order_products") order_qty = models.PositiveBigIntegerField(default=0) order_unit_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_extended_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_units = models.CharField(max_length=10, … -
Reactjst-WebSocket is already in CLOSING or CLOSED state
I created chat system using Django and Reactjs,when i want to send Message then in console give me Error of : WebSocket is already in CLOSING or CLOSED state. my code is let socket = new WebSocket(ServerUrl.WS_BASE_URL + ws/users/${CommonUtil.getUserId()}/chat/); const messageSubmitHandler = (event) =\> { event.preventDefault(); if (inputMessage) { socket.send( JSON.stringify({ action: SocketActions.MESSAGE, message: inputMessage, user: CommonUtil.getUserId(), roomId: CommonUtil.getActiveChatId(match), }) ); } setInputMessage(''); }; \<div className="flex-grow-0 py-3 px-4 border-top"\> \<form onSubmit={messageSubmitHandler}\> \<div className="input-group"\> \<input onChange={(event) =\> setInputMessage(event.target.value)} onKeyUp={chatMessageTypingHandler} value={inputMessage} id="chat-message-input" type="text" className="form-control" placeholder="Type your message" autoComplete="off" /\> \<button id="chat-message-submit" className="btn btn-outline-warning"\> Send \</button\> \</div\> \</form\> \</div\> I search in stackOverflow but there is no Such solution -
Add field in swagger ui using drf-yasg
My code is hosted here. It uses drf-yasg, jwt and the django rest framework. I am trying to set up a patch method to have the user edit his task. The code in a nutshell is as follows def get_payload(request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') return payload class TaskView(APIView): pk = openapi.Parameter('pk', openapi.IN_QUERY, description="field you want to order by to", type=openapi.TYPE_INTEGER) @swagger_auto_schema( request_body=openapi.Schema( manual_parameters=[pk], type=openapi.TYPE_OBJECT, properties={ 'taskname': openapi.Schema(type=openapi.TYPE_STRING, description='Add taskname'), 'completion': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='completion'), } ) ) def patch(self, request, pk): payload = get_payload(request=request) task = Tasks.objects.filter(id=pk, username=payload['username']).first() serializer = TaskSerializer(task, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) However, the swagger ui does not display the field for pk. I can see the sample body but the field for pk is missing. How do I add the field for pk here? -
How to change related object when creating object in DRF
I want to change is_available field in Book object when reservation is being create. I found a way which I am pasting here, but this digging in request looks messy, so as it often is with so mature frameworks as drf there are probably better ways to do that. So I have serializer.py class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BookModel fields = ["number", "title", "author", "is_available"] class ReservationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ReservationModel fields = ["reserved_by", "book", "started_at", "valid_until"] And views.py class BookViewSet(viewsets.ModelViewSet): queryset = BookModel.objects.all() serializer_class = BookSerializer permission_classess = [] class ReservationViewSet(viewsets.ModelViewSet): queryset = ReservationModel.objects.all() serializer_class = ReservationSerializer permission_classess = [] def perform_create(self, request, *args, **kwargs): super().perform_create(request, *args, **kwargs) book = BookModel.objects.get(pk=request.data.serializer.instance.book_id) book.is_available = False book.save() I posted what I did, Please teach me do it better - proper way -
How can I assert that a pdf file was returned in python?
I am working on asserting that a pdf is returned from my request. Here is what my test looks like so far. @mock.patch('path.to.class._get_file', return_value=MockResponse(status.HTTP_200_OK, 'application/pdf')) def test_get_should_successfully_return_the_requested_pdf(self, get_file_mock): response = self.client.get(f'/api/v1/path/to/file/abc123.pdf, content_type='application/vnd.api+json') self.assertEqual(response.status_code, status.HTTP_200_OK) # works great self.assertEqual(response['Content-Type'], 'application/pdf') # works great self.assertEqual(response, <abc123.pdf>) # not so great If I do a print to see whats in the response: print(response) <HttpResponse status_code=200, "application/pdf" I am pretty sure I am not setting up the @patch correctly. Specifically, this: status.HTTP_200_OK, 'application/pdf' I've seen a lot of posts about reading or opening files, but I just need to make sure it was in fact a pdf (file) that was returned. How can I set my mock up so that I can assert a pdf (file) was returned? -
How to attach HTMX parameters to a django input form
I am trying to implement an HTMX autosearch function to an input created by a django form. When I inspect the element on the page, the htmx tags are all present. However, the htmx never intializes and it never goes to the views endpoint. The code for the django input form is as follows: widget_attrs_nha_autosearch = { 'class': 'form-control', 'data-user-entry': 1, 'disabled': value.get('read_only'), 'hx-post': "{% url 'ng_django_pmp:nha-autosearch' %}", 'hx-target': '#results', 'hx-trigger': "keyup changed delay:500ms" } if value.get('label') == 'nha_override': self.fields[field] = forms.CharField( initial=value.get('default', ''), label=value.get('label'), max_length=value.get('max_length'), required=required, widget=forms.TextInput(attrs=widget_attrs_nha_autosearch), validators=value.get('validators', [])) When I attempt to create the htmx code on its own in html, it works just fine. However, I need the code to be created in this manner in order to properly trigger something on the backend. The HTMX code on its own is as follows: {% csrf_token %} <div class="d-flex justify-content-end mb-4"> <input type="input" hx-post="{% url 'ng_django_pmp:nha-autosearch' %}" hx-target='#results' hx-trigger="keyup changed delay:500ms" name="search" class="d-flex flex-grow-1 flex-column p-3 border border-secondary rounded m-2" style="overflow: auto; min-width: 0; min-height: 0" placeholder="" id='id_nha_override' /> </div> <div id="results"></div> Am I missing something? -
Deploy Django app as a DigitalOcean's Cloud function?
The Scenario is, I want to deploy my Django application as a PaaS cloud function of the Django application. I have tried to search over the internet but come up with nothing. If this is possible, what will be the complications? Do I need to write the application from scratch again in vanilla Python for deploying it to the Cloud function? -
Django test failes ModuleNotFoundError: No module named 'base' in github actions
i am trying to put down a CI/CD workflow using github action for my project. i have created some test which run fine locally. but on github actions it fails with an error. i have given it the env variables it ask for in the error but still it isn't working link to the repo https://github.com/Suryansh5545/Ticketify. This is the workflow https://github.com/Suryansh5545/Ticketify/actions/runs/5729864155. After fixing this i am gonna try to make workflow to make and export the images from my compose file and then run staging on portainer. Error given by workflow:- ModuleNotFoundError: No module named 'base' ModuleNotFoundError: No module named 'event' It also says about CELERY_BROKER_URL not being a attribute but it is set in both github environment variable and by default if not present in settings. -
How to Save the current user for the created model object in django rest framework
Sorry if I'm asking a noob question. i have this model which used to create a article and the article has a field which associated to the django user model from django.db import models from django.contrib.auth.models import User class Article(models.Model): headline = models.CharField(max_length=150) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateField(auto_now_add=True) pub_time = models.TimeField(auto_now_add=True) # fields need to be added # location # byline -> line tells who writes the article # conclusion # tags def __str__(self): return self.headline i use this django rest framework view to create the object. using postman and giving the author id i can create the article post @api_view(['POST']) def create(request): if request.method == 'POST': serializer = ArticleSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) what i need to achieve is the only the logged user need to be able to create the article and when the user create the article the author id need to be auto updated at the time the object was created. here is my serializer from rest_framework import serializers from . models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' -
youtube transcript summariser using chrome extension project
In youtube transcript summariser using chrome extension , im getting warning as " This is a development server. Do not use it in a production deployment. Use a production WSGI server instead". im not understanding what to do -
django-channels: Not Found: /ws/
Hi I have typical django app for real-time notifications using websockets Have 2 apps "core" and "notification" I need to show notification on notification page when Review is created. I added channels core and notification to installed apps INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "channels", "core", "notification", ] Added asgi configuration ASGI_APPLICATION = "reviewproject.asgi.application" Configured channel layers CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } Here is asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import notification.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reviewproject.settings") application = ProtocolTypeRouter( { "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( notification.routing.websocket_urlpattern ) ) } ) I also have routing.py from django.urls import re_path from . import consumers websocket_urlpattern = [ re_path(r'ws/notification/$', consumers.NotificationConsumer.as_asgi()), ] consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = "notification" await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def send_message(self, event): message = event['message'] await self.send(text_data=json.dumps({'message': message})) And sending notification when Review is created class ProductView(View): def send_notification(self, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("notification", {"type": "send_message", "message": message}) def get(self, request, pk): reviews = ReviewModel.objects.filter(product=pk) product = get_object_or_404(ProductModel, pk=pk) context = { "reviews": reviews, "product": product } return render(request, … -
I am Unable to Vailidate error to my UI I want the specific error as if username is same the error will be username doesn't exist
I am Unable to Vailidate error to my UI I want the specific error as if username is same the error will be username doesn't exist My Backend code My Urls.py from django.urls import path from . views import * from rest_framework_simplejwt.views import ( TokenRefreshView, ) urlpatterns = [ path('', getRoutes), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', UserRegistrationView.as_view(), name='user_registration'), ] I have simple serializer My Serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] My Views.py from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from django.contrib.auth.models import User from rest_framework import status from rest_framework.views import APIView from .serializer import UserRegistrationSerializer from django.core.exceptions import ValidationError class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username # ... return token class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer @api_view(['GET']) def getRoutes(request): routes = [ '/api/token', '/api/token/refresh', ] return Response(routes) class UserRegistrationView(APIView): def post(self, request): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] email = serializer.validated_data['email'] phone = serializer.validated_data['phone'] # Check if username already exists if User.objects.filter(username=username).exists(): return Response({'error': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) # Check if … -
I have a question about generic view in Django's tutorial example
In the “Writing your first Django app, part 4” of the tutorial of Django documentation, there is example of using generic view like blow ; File name : polls/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.""" return Question.objects.order_by("-pub_date")[:5] class DetailView(generic.DetailView): model = Question template_name = "polls/detail.html" class ResultsView(generic.DetailView): model = Question template_name = "polls/results.html"` Q1 .in “class IndexView”, where is the “latest_question_list” defined? Is it the return value of “get_queryset” function? If so, how can I find the relationship between “latest_question_list”and “get_queryset” function? There is not any clue. Q2.there is a explanation in the tutorial like so: In previous parts of the tutorial, the templates have been provided with a context that contains the question and latest_question_list context variables. For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable. However, for ListView, the automatically generated context variable is question_list. To override this we provide the context_object_name attribute, specifying that we want to use latest_question_list instead. My question is that, it said the question variable is provided automatically for DetailVIew. what does the “question” … -
Distribution of values by days from the database in the template
I'm trying to distribute the data in this form: August 1st: value 1 value 2 August 2: value 3 value 4 My model: class MyModel(models.Model): value = models.CharField('Value', max_length=150) date = models.DateTimeField('Date', auto_now_add=True) -
CS50W mail project, mark my read variable in my API as true as default but it must be false
I've been dealing with this bug for past few days and i can't fix it. So basically in this project i should make a email in a local host server using only JS, HTML and css. as you can see in the following code the read variable of the emails that get composed must remain false as default until you visit the email page : models.py : class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "read": self.read, "archived": self.archived } and it's not my JS file problem because i never even write anything for the read variable to change it : Inbox.js file : document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#submit').addEventListener('click', submit); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display … -
Passing function from DjangoListAPI to a celery task
I am having some trouble passing a function to a celery task, and i cant pass its results because it takes much time to load and it times out the api request @celery.task(name='task_name', bind=True) def celery_task(self, headers, data_function): data = data_function() # more code class DataClass(generics.ListCreateAPIView): def get(self, request, *args, **kwargs): send_excel_as_email.apply_async(args=[headers, self.get_data]) def get_data(self): queryset = self.filter_queryset(self.get_queryset()) serializer_class = self.get_serializer_class() data = serializer_class(queryset, context=self.get_serializer_context(), many=True).data # more code So basically the celery_task is a reusable task that will be used in many other Classes and each class has its own query_set and serializer, thats why i need to find a way to call the get_data function inside the celery task itself i tried using pickl but it throwed errors that it cant serialize the function -
Can't figure out why Django ORM is giving me this error with prefetch_related()
I have the following data models in my Django app: class Company(models.Model): company_name = models.CharField(max_length=255) company_url = models.URLField(max_length=2048, blank=True, null=True) ... class Meta: db_table = 'company_table' class PricingPlan(models.Model): plan_name = models.CharField(max_length=255, blank=True, null=True) ... company = models.ForeignKey(Company, related_name='pricing_plans', on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'pricing_plan_table' class Feature(models.Model): feature_name = models.TextField(blank=True, null=True) plans = models.ManyToManyField(PricingPlan, related_name='features', blank=True) class Meta: db_table = 'feature_table' class WebData(models.Model): company = models.OneToOneField(Company, related_name='web_data', on_delete=models.CASCADE) version = models.IntegerField(blank=True, null=True) ... class Meta: db_table = 'web_data_table' Now, I want to query the DB like this: queryset = queryset.select_related('web_data').prefetch_related('pricing_plans', 'pricing_plans__features') But get this error: django.db.utils.ProgrammingError: relation "feature_table_plans" does not exist LINE 1: ...e"."feature_name" FROM "feature_table" INNER JOIN "feature_t... Any ideas on how to fix this? -
Deploying a complete full stack app to Railway
I have a full containerized frontend React app, I also have a full containerized backend Django/Python app (this simply works as an API) which accesses a Postgres database, and a third project which uses a Docker image of Postgres. I also have the full project using Docker Compose. What do you suggest that I do in order to deploy it to the Railway hosting: Deploy it to Railway using the complete Docker Compose project Deploy the React frontend, also deploy the Django/Python backend and also deploy the Postgres project Deploy just the frontend and backend, and use some sort of Postgres service that Railway could have I don't know which approach to take and which is viable. -
How can I exclude a subclass (or subclasses) of pages from Wagtail's search functionality?
I'm creating a blog site for a friend and there are certain page models that I would like to be excluded from users' searches. These models are BlogIndexPage and ThankYouPage. Both of these models subclass wagtail.models.Page. I want to have control over how these pages are visited and therefore don't want links for them to show up in search results if users search—for example—thank or blog. For context, this is the search view function: def search(request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) # Search if search_query: search_results = ( Page.objects.live().order_by("-first_published_at").search(search_query) ) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() # etc... I've tried the two solutions suggested in this other thread and a third solution I found in the documentation, but they did not solve my problem. Specifically I tried the following: class ThankYouPage(Page): ... # Method One: @classmethod def get_indexed_objects(cls): return cls.objects.none() # Method Two: def get_indexed_instance(self): return None # Method Three: search_fields = [] I ran the update_index management command after each change. In the Django shell, I get the following behavior: >>> from wagtail.models import Page >>> from apps.contact.models import ThankYouPage >>> >>> Page.objects.all().search("thank") <SearchResults [<Page: Thank You Page>]> >>> >>> ThankYouPage.objects.all().search("thank") … -
How to define file path in a view method in django views.py
I need to read a CSV file in my view method. This is my view method in views.py in django project: def myfile(request): csv_fp = open('file.csv', 'r') reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'myfile.html', {'data' : out, 'headers' : headers}) This is in my urls.py: path('myfile/', views.myfile, name='myfile'), My django version is: 3.2.2 I tried many ways to open file in csv_fp = open('file.csv', 'r'). I used the below ways in my views.py and non of them worked: my file in the static directory: csv_fp = open('static/file.csv' , 'r') # not working csv_fp = open('file.csv' , 'r') # not working I added the below lines in my views.py and it didn't work as well: import csv, os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, 'static') file_path = os.path.join(STATIC_ROOT, 'file.csv') csv_fp = open(file_path , 'r') This is the error message: Exception Location: /home/djangoir/virtualenv/project/3.7/lib/python3.7/site-packages/django/template/loader.py, line 19, in get_template The point is I don't want to generate a model for the database and import CSV file into the database. I just need somehow read the file and export its data in a dictionary in the render method.