Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Sessions not Working on remote server
I am trying to use a session variable in my django app view.py def get(self, request): room_name = request.session.get('room_name', str(uuid.uuid4().hex)) context = app.get_context(room_name) context['room_name_create'] = room_name context['room_name_check'] = request.session.get('room_name') return render(request, self.template, context) js console.log('a', context.room_name_create) console.log('b', context.room_name_check) This works perfectly on my local server. On the remote server context.room_name_create shows a value, but context.room_name_check shows as null in the browser. This is only a small app and I have copied all of the source files to the remote server and so all of the source is identical. I have tested this on different browsers Can anyone suggest what I can check to resolve this? -
What is the entry point of a Django app similar to main.py? Where do I set up parameters?
I want to set up some parameters and initialize the Injector object, because I want to use a dependency injection and singletons in my Django app. Usually I do that in the main.py of my app but with Django I don't see where the first entry point of the application is when it runs. Where shoud I initialize the injector and pass it my views and services? I have a view like this: from uuid import UUID from django.shortcuts import render from django.http.response import JsonResponse from django.http.request import HttpRequest from rest_framework import viewsets, status from rest_framework.parsers import JSONParser from rest_framework.response import Response from Instruments.services import InstrumentsService from rest_framework.decorators import api_view from Instruments.services import InstrumentsService from injector import singleton, inject # Application views live here @singleton class InstrumentViewSet(viewsets.ModelViewSet): @inject def __init__(self, instrument_service: InstrumentsService, **kwargs): self.instrument_service = instrument_service super().__init__(**kwargs) def list(self, request: HttpRequest): data = {} try: data = self.instrument_service.get_instruments() return JsonResponse(data, status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse( {"Status": f"Error: {exc}"}, status=status.HTTP_400_BAD_REQUEST, safe=False, ) def create(self, request): instrument_data = JSONParser().parse(request) data = {} try: data = self.instrument_service.add_instrument(instrument_data) return JsonResponse(data, status=status.HTTP_201_CREATED, safe=False) except Exception as exc: return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST, safe=False) def retrieve(self, request, pk: UUID = None): data = {} try: … -
Why isn't assertContains working properly in django tests?
I wrote a test that is supposed to create a flight, then pass appropriate arguments to the client.get function and receive a response that will contain results of 'search' - in this case it should be only the flight created before as a direct flight from Airport to AirportSeceond(names or airport and airport2). However, it seems that there are no results in the response (the first assertion works properly). My test (TestCase): def test_no_errors_html_direct_flights(self): country, city, airport, city2, airport2, airport3 = create_set() flight = SingleFlight.objects.create(departure_airport=airport, arrival_airport=airport2, departure_time_utc=(tz.now()+datetime.timedelta(days=5)), duration_in_hours=2, duration_in_minutes=10, price=200) print("\n\n\n") print(flight) date = (tz.now() + datetime.timedelta(days=5)).date().strftime("%Y-%m-%d") print(date) kwargs = {'dep': 'Airport', 'arr': 'AirportSecond', 'date': date} response = self.client.get(reverse('app1:flight-search-result'), kwargs) self.assertContains(response, 'No options for your search') self.assertContains(response, 'Direct connection') My template: {% block content2 %} {% if not direct_flights %} {% if not indirect_flights %} <p><strong>No options for your search</strong></p> {% endif %} {% endif %} {% for flight in direct_flights %} <p>{{ flight.departure_airport }}</p> <p>{{ flight.departure_time_local }}</p> <p> </p> <p>{{ flight.arrival_airport }}</p> <p>{{ flight.arrival_time_local }}</p> <p>Direct connection</p> <---- this should be in the response <a href="{% url 'app1:flight-search-detail-passenger-form' flight.id_flight %}">Here! ;)</a> {% endfor %} {% for connection in indirect_flights %} {{ connection.price }} {% for flight in connection.all_info %} … -
Access to ForeingKey's model data in Django
I need to access to a ForeignKey's model data, but I don't know how. I wrote this as a simple example of what I want to do: class Model1(models.Model): name = models.CharField(max_length=100) phone_number = models.BigIntegerField() class Model2(models.Model): model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) name = model1.name phone_number = model1.phone_number It gives me the following error message: AttributeError: 'ForeignKey' object has no attribute 'name' -
How to customize a look of crispy forms?
I have to edit an upload form created with crispy forms. I have provided a code that I have been used, and how it looks right now and how I would like to look. I tried to do it with helper attributes, but I failed, can you help me to get wanted outcome? This is how it looks now! I'm looking for something like this! This is upload_document.html {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <h1>Upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Upload</button> </form> {% endblock content %} models.py from django.db import models class UploadFile(models.Model): excel = models.FileField(upload_to="excel/", max_length=250) def __str__(self): return self.title forms.py from .models import UploadFile class GlForm(forms.ModelForm): class Meta: model = UploadFile fields = ('excel',) settings.py CRISPY_TEMPLATE_PACK = 'bootstrap4' INSTALLED_APPS = [ 'bootstrap4', 'crispy_forms', '...', ] Thanks in advance! -
Django Swagger won't allow me to use POST method (no parameters shown)
I'm using djangorestframework together with drf-spectacular modules for a Django project, and I'm trying to build some basic API methods for my Project model. Its structure looks like this: from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length = 128) description = models.TextField() image = models.URLField() date = models.DateTimeField(auto_now_add=True) I also have a serializer for the model, looking like this: from rest_framework import serializers from api.models.Project import Project class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ['title', 'description', 'image', 'date'] Then, in views.py, I created two functions: project_list_view, which either lets you to GET all the Project objects from the database, or lets you POST a new object. And finally, project_detail_view, which lets you GET a Project object by typing in its pk (integer id). These are my two functions: @api_view(['GET', 'POST']) def project_list_view(request): if request.method == 'GET': projects = Project.objects.all() serializer = ProjectSerializer(projects, many=True) return Response(serializer.data) elif request.method == "POST": serializer = ProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def project_detail_view(request, pk): if request.method == "GET": try: project = Project.objects.get(pk = pk) serializer = ProjectSerializer(project, many = False) return Response(serializer.data, status = status.HTTP_200_OK) except: return Response(status=status.HTTP_404_NOT_FOUND) The GET from … -
Relation doesn't exist in django restframework
I am creating one crud operation in django restframework and I have created project name "portfolio" and app "stock" and store in postgres database Here is my code. stock.models.py from django.db import models class Stocks(models.Model): Name = models.CharField(max_length=50) Number_of_Share = models.IntegerField() Unit_Price = models.IntegerField() ShareValue=models.IntegerField() Total_Share_Value= models.IntegerField() stock.serializers.py from rest_framework import serializers from .models import Stocks class StocksSerializer(serializers.ModelSerializer): class Meta: model =Stocks fields = '__all__' stock.viewset.py from rest_framework import viewsets from .models import Stocks from . import serializers class StockViewset(viewsets.ModelViewSet): queryset = Stocks.objects.all() serializer_class = serializers.StocksSerializer portfolio.router.py from stock.viewsets import StockViewset from rest_framework import routers router = routers.DefaultRouter() router.register('Stocks',StockViewset) portfolio.urls.py from django.urls import path, include from .router import router urlpatterns = [ # path('admin/', admin.site.urls), path('portfolio/',include(router.urls)) ] But I am facing this error. Exception Type: ProgrammingError Exception Value: relation "stock_stocks" does not exist LINE 1: ...reValue", "stock_stocks"."Total_Share_Value" FROM "stock_sto... Please help me solve this error. -
How to connect to ElastiCache instance (Redis) from Django App running on local machine
I'm struggling to find a solution to properly set connexion between my Django app running on my local machine and my ElastiCache instance Let me resume the situation. CONFIG: I have a Django App deployed on an AWS EC2 instance and running using a docker-compose-yml file. I'm using ElastiCache & Redis for my cache. MY ISSUE: I can successfully connect to my ElastiCache Instance from my EC2 instance. I can use Redis and create key etc.. Everything working perfectly. I am able to connect to ElastiCache from my Django App when I run it with my docker-compose.yml file within my EC2 Instance. I can also use Redis on my ElastiCache from my local machine by creating a sort of bridge with my EC2 instance using this command: ssh -f -N -L 6379:{my_elasticache_amazon_url}:6379 ec2-user@{my_ec2_instance_url} Then I run the following command and have access to redis: redis-cli -h 127.0.0.1 -p 6379 127.0.0.1:6379> But I can't access to ElastiCache from my Django App running on my local machine! I need to set this connexion for dev and test purpose, before deploying it on the EC2 instance. WHERE I AM: I tried to directly connect to ElastiCache using the URL in the Django App … -
How can i add Viusal studio build tools in dependencies in heroku requirements?
i'm tryng to build a web app for my master thesis. I'm using django. I used the package cvxpy (cvxpy) of python that need the visual studio build tools for python 3 to be installed. I have two problem: 1) how can i install this tools on a python venv? 2) how can i declare in requirements.txt for heroku the need of visual studio build tools ? Thanks PS i had not problem to install and use visul studio build tools in my local machine without venv. -
heroku run python manage.py makemigrations -a myapp takes forever
I have added this to my setting.py DATABASE_URL = os.environ.get('DATABASE_URL') db_from_env = dj_database_url.config(default=DATABASE_URL) DATABASES['default'].update(db_from_env) and yet when I run heroku run python manage.py makemigrations -a myapp it stucks in connecting process. Does anyone know how to solve this? -
401 "Unauthorized" error in Django File Upload
I have created a Django and Angular application to upload files. It was working without errors until I integrated a login page. I have not been able to upload files since integration. I get 401 - "Unauthorized" error. What could have possibly gone wrong? Thank you -
Django Raw SQL query outputting me objects instead of actual data
I'm trying to run raw SQL because i'm fed up with Django's QuerySet. So i thought it would be easy to run raw sql, but apparently not. Here is what i'm trying to run: test_raw = CsmSecurityPrice.objects.raw("SELECT SEC_ID, PRICE, PRICE_DATE FROM dbo.CSM_SECURITY_PRICE WHERE SEC_ID = 1093772 ORDER BY PRICE_DATE DESC")[:] for p in test_raw: print(p) Here is the horrendous output i get: CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772) CsmSecurityPrice object (1093772)..... The query works wonder in SQL SERVER MANAGEMENT STUDIO. -
Passing a placeholder text using django-filter and different views
I have a model: class Movie (models.Model): category = models.CharField(max_length=50, verbose_name='Kategoria filmu', default= 'unassigned', null=False, choices=category_choices) source = models.CharField(max_length=50, verbose_name='Źródło filmu', default= 'unassigned', null=False, choices=source_choices) promotion = models.BooleanField(default=False, verbose_name='PROMOCJA FILMU') author = models.CharField(max_length=50, verbose_name='Nazwa influencera') title = models.CharField(max_length=50, verbose_name='Nazwa filmu') content = models.TextField(max_length=10000, verbose_name='HTML EMBEDED do filmu') date_posted = models.DateTimeField(default=timezone.now) youtube_url = models.URLField(blank=True, max_length=300) tiktok_url = models.URLField(blank=True, max_length=300) insta_url = models.URLField(blank=True, max_length=300) I am passing it to the view with djnago-filter with different category choice: views.py: #HotTop View class HotTopView (FilterView): model = Movie template_name = 'pages/hot_top.html' filterset_class = MovieFilter paginate_by = 6 def get_queryset(self): category_qs = self.model.objects.filter(category="HOT-TOP") return category_qs.order_by('-date_posted') #Odkrycia View class OdkryciaView (FilterView): model = Movie template_name = 'pages/odkrycia.html' filterset_class = MovieFilter paginate_by = 6 def get_queryset(self): category_qs = self.model.objects.filter(category="ODKRYCIA") return category_qs.order_by('-date_posted') and my filters.py: class MovieFilter(django_filters.FilterSet): author = django_filters.CharFilter(label='', lookup_expr='contains', widget=TextInput(attrs={'placeholder': 'Search'})) class Meta: model = Movie fields = ['author'] The question is how can i change placeholder of my serach form depending on the view (HotTop or Odkrycia). I want it to be - when i am in HotTop View -> Search in Hot Top and when i am in Odkrycia - > Search in Odkrycia -
Django back end to serve a react front end images
I am working in a project with a django back and a react front. I am stuck on displaying images on react front. The url served in my react console is : http://localhost:8000/media/media/images/cards/card1.jpg When I load this url in a new chrome the page the image is displayed however in my react page the image is blank. Here are my django settings.py : # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent #Directories PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR) MEDIA_URL = '/media/' Here is my serializer : class StartupSerializer(serializers.ModelSerializer): class Meta: model = Startup fields = ('id', 'header', 'title', 'category', 'description', 'tags' , 'card_image' , 'logo_image') And here is my model : class Startup(models.Model): header = models.CharField("Header", max_length=255, null=False) title = models.CharField("Title", max_length=255, null=False) category = models.CharField("category", max_length=255, null=False) description = models.CharField("description", max_length=255, null=False) # TODO Change this to options instead of array tags = ArrayField(models.CharField(max_length=10, blank=True), size=5,) # TODO Images to be stored in aws only url will be in DB card_image = models.ImageField(upload_to='media/images/cards', null=False) logo_image = models.ImageField(upload_to='media/images/logos', null=False) createdAt = models.DateTimeField("Created At", auto_now_add=True) def __str__(self): return self.title Please not on recat side the axios works fine and I can get all other fields … -
How can I find out the type by accessing the column of the index of the models.all() result?
How can I find out the type by accessing the column of the index of the models.all() result?? My code is like this: def qtj(result_model): for index in result_model: print('index : ', index) for column in index: print(f'column : {column} type:{type(column)}') but this at index : index : {'board_seq': Decimal('15'), 'board_title': '제목', 'board_content': '내용', 'board_writer': '무명', 'board_password': '1234', 'create_date': datetime.datetime(2021, 11, 27, 18, 6, 8, 586137)} and in the column : column : board_seq type:<class 'str'> What I want to do is find the datetime.datetime, not the str. -
How to avoid Django shows multiple logs in shell
I have a part of codes like below in Django project. This code gives the same multiple logs in the shell. si_ids = Blank_Form.objects.get(blank_form_id__exact=blank_form_id).core_service_id.split('s')[1::] logger.log(20, '[si_ids] {}'.format(si_ids)) [si_ids] ['49', '69', '50', '56'] [si_ids] ['49', '69', '50', '56'] ... about 10 same line continues Every line that has logger.log gives the same 10 more lines. How to get just a single line of log? -
ValidationError with Custom pagination in ListAPIView
I am trying to set error message in my ListAPiview where if a user tries to access data other than Pool Operator he should get a permisiion denied error Views.py class ProductListAPIView(generics.ListAPIView): serializer_class = ProductSerializer pagination_class = StandardResultsSetPagination permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): company = self.request.GET['company'] view = self.request.GET['view'] if view=='Pool Operator': emp = list(Employee.objects.filter(company=company).values_list('pk', flat=True)) queryset = Product.objects.filter(owner__in=emp).order_by('-pk') return queryset else: return ValidationError( {'permission denied': "Can't see user's Products"} ) But when I run this I get the following error: object of type 'ValidationError' has no len() What needs to be changed to show a successful error message? -
Use variable as form fields in Django form template
<here all loading of static , template_filters, crispy_forms > <form> {% for i in artifact_length %} {% with artifact_name="artifact_"|artifact_name:forloop.counter0 %} {{form.artifact_name|as_crispy_field}} {% endwith %} {%endfor%} </form> This is related template code. Here i want to render form fields with names artifact_0, artifact_1 as coming from form. The variable artifact_name inside with is working fine and returning expected identifiers artifact_0 , artifact_1, but i want to use these variables as form fields to render as as_crispy_field. The code {{form.artifact_name|as_crispy_field}} does not print anything because it is assuming form as field with name artifact_name which is not. Instead i want to use the value of variable here. forms.py class Someform(forms.form): def __init__(self, artifact_obj): super().__init__() count = 0 for artifact in artifact_obj: self.fields[f'artifact_{count}'] = forms.CharField(widget=forms.NumberInput()) count += 1 tags.py @register.filter('artifact_name') def get_artifact_name(artifact_prefix: str, counter: int): print('method', 'prefix', artifact_prefix, 'counter', counter) return f'{artifact_prefix}_{counter}' There is variable length form being created. As informs.py form fields are being created with artifact_count where count can range from 0 to len of obj. -
How to apply filter based on dates of an already existing database with Django Queryset
So i have the below's QuerySet output : <QuerySet [{'price': 12.515, 'price_date': datetime.datetime(2017, 3, 13, 0, 0, tzinfo=)}, {'price': 12.335, 'price_date': datetime.datetime(2017, 3, 14, 0, 0, tzinfo=)}, {'price': 12.37, 'price_date': datetime.datetime(2017, 3, 15, 0, 0, tzinfo=)}, {'price': 12.35, 'price_date': datetime.datetime(2017, 3, 16, 0, 0, tzinfo=)}, {'price': 12.305, 'price_date': datetime.datetime(2017, 3, 17, 0, 0, tzinfo=)}... How can i get say the price with price_date = 11-26-21 (November 26th 2021) ? Or if i want to filter by latest 30 prices? Thanks -
VS Code suggestion attribute of Django class based view
vscode django classbased view suggestion Hello Experts, I have been creating djagno project on vscode as per front screen(windows 10) in the picture and vscode helped me to write correct attribute of the class based view with suggesoin (Ex. context_object_name) I have shifted to windows 11 as per the second screen in the back. I am not getting suggesion of the attribute of Djanngo's class based view and I would like to see it there same as front screen in the picture. Can anyone help me with the query? Thanks in advance for ones time and efforts to answer my query. -
Timetable in django
In my django app i would like to create a timetable showing all appointments per day. For example: Time | Seat 1 | Seat 2 | etc 9:00am John Doe Jim Doe 10:00am John Doe Jim Doe Currently i have models for appoint and seat: class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) name = models.CharField(max_length=255) date_created = models.DateTimeField(_('Date Created'), auto_now_add=True) date_updated = models.DateTimeField(_('Date Updated'), auto_now=True) class Seat(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) created_at = models.DateField(auto_now_add=True) Could you please propose a way or steps of how to achieve that? -
How to make a left join query in Django ORM
My models: class Post(models.Model): user = models.ForeignKey(BucketUser, on_delete=models.CASCADE) content = models.ForeignKey(Content, on_delete=models.CASCADE, blank=True, null=True) resource_type = models.CharField(max_length=150) url = models.URLField() text = models.TextField() class Rating(models.Model): user = models.ForeignKey(BucketUser, on_delete=models.CASCADE) content = models.ForeignKey(Content, on_delete=models.CASCADE) rating = models.IntegerField(choices=rating_choices, default='1') The PostgreSQL Tables: posts_post : | id | url | resource_type | text | content_id | user_id | ratings_rating : | id | rating | content_id | user_id | I want to get the contents of posts_post table along with the respective rating values from ratings_rating for the same content_id and a user_id which I'll receive from the GET request. I can get that easily by SQL query like: SELECT p.*, r.rating FROM posts_post p LEFT JOIN ratings_rating r ON p.content_id = r.content_id AND r.user_id = 100; /* Assuming user_id received was 100 */ or i can even do this: SELECT p.*, (SELECT r.rating FROM ratings_rating r WHERE r.content_id = p.content_id AND r.user_id = 100) AS rating FROM posts_post p; But, I'm troubled about how to do the same through Django ORM queries based on the models. Or, if I need to create new models for this? What would be the Django way of doing it? I'm still new with Django models, and … -
Django data is not rendering as saved in model
I'm uploading data to one of the models using CSV file. There is no issue in saving the data. It is getting saved as needed. But just after uploading the data all the foregin key value rendering same. In the above image all data is same. But on restarting the server using python manager.py runserver. The value are rendering as expected. Function used in rendering the data. There is no effect of refreshing it. It starts rendering the correct data on performing python manage.py runserver -
how to model formset in modal form - django
i'm trying to implement two formset in one view , one of the formsets should be pop up modal form : here is the models class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}' if quantity = 10 then we have 10 unique imei , for each mobile item we have multiple imei , the im ei should be inserted in a pop up modal @login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none()) if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST) if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context) but it only saves the last item entry and doesnt save imei , only its instance(from the item) will be saved and here is my formsets mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True) and here is my html and jquery const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = … -
Django Rest Framework Handle a lot of Request & Responses with put method for text editor
I Have a Text Editor in FrontEnd And I want to save text changes as soon as I stop typing but requests and responses are a lot I want to handle this problem with best way Do you know a solotion or package for handling this? thank you