Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django changing a value of databe field using variable in view
Is there any way to update the by-hand value of a particular field in the model instance using variables? For example. models.py class ExampleModel(models.Model): name=models.CharField(max_length=10) a=models.CharField(max_length=10) b=models.CharField(max_length=10) c=models.CharField(max_length=10) views.py list=[a,b,c] fruits=[orange,apple,banana] values def ExampleView(request): model_instsnce=ExampleModel.objects.last() for i in list: instance_model.i=fruits[i] model_instance.save() In my project, I tried to use something like the above but it doesn't work. 'i' from loop doesn't behave like a variable. 'i' is treated as a new field in the model. Any idea how to use variables to designate fields from model to change? -
How to avoid data being stored in database using django rest framework
I have create a django rest framework api. For that i have created model, then create a serialize. It is working fine. I want to know is there a way that my input would not store in database. Currently, my inputs are stored in sqlite3 database. The reason why i want to do that the user input value via php form. I have to take 1 value from that form and do some modifications on it and return the value. Thats why i dont think i need a db for my django project, Here is code models.py class MyModel(models.Model): value=models.IntegerField() serializers.py class MySerializer(serializers.ModelSerializer): class Meta: model=MyModel fields='__all__' views.py class MyViews(APIView): def post(self, request): serializer = MySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) urls.py urlpatterns = [ path('api', VideoUploadViews.as_view()) ] -
Sorl-thumbnail only working with DEBUG=True
I'm using Python 3.6.9, Django 3.2.8, sorl-thumbnail 12.7.0 with memcached my thumbnails completely disappear and give a 404 when settings.py variable DEBUG is set to False. I also have to say, that I don't get any errors displayed at all from setting THUMBNAIL_DEBUG = True as I understand it depends on the aforementioned variable which I have to set to False for pictures to disappear, if it does not depend on it I'm not getting any error displayed either. I'm just loading them inside templates like this: {% load thumbnail %} {% thumbnail ann.obj.fotografia_professionista "460x310" as thumb %}<img src="{{ thumb.url }}" data-src="{{ thumb.url }}" class="img-fluid lazy">{% endthumbnail %} and it works fine as long as DEBUG = True. I restarted apache2 and memcached, I also used python manage.py thumbnail clear or cleanup but it just doesn't work at all. I'm delivering the thumbnails at SETTINGS.MEDIA_URL, which is just set to "/media" and that I'm enabling in urls.py like this: urlpatterns = [ # my paths ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I did read this thread and I set up my urlpatterns the same exact way as it was suggested, but it doesn't solve my problem -
I have a problem with making random backgorund image usign js inside my django project?
the images don't appear even though I add the correct directory but djaong post give this massage in console: GET http://127.0.0.1:8000/%7B%%20static%20bc-3.jpg%20%%7D 404 (Not Found) script.js:24 my problem is I wanna add a random background image in my project I set this in CSS property "background-image" and it's work the URL but js code doesn't work my code: index.html {% extends "kidedu/layout.html" %} {% load static %} {% block body %} <div class="random_images_container"> <div class="main_head"> <h1>Join Our Big Community, To Educate Kids.</h1> <h5>Get Start, By sing-in for a new account or log in.</h5> <a class="head_btn btn" href="{% url 'sign_up' %}">Join Us</a> </div> <div class="arrows"> <i class="fas fa-chevron-left le"></i> <i class="fas fa-chevron-right ri"></i> </div> <ul class="bullets"> <li></li> <li class="active"></li> <li></li> </ul> </div> {% endblock %} js file // Image slider const imageSlider = document.querySelector(".random_images_container") const imagesArr = ['bc-1.jpg', 'bc-2.jpg', 'bc-3.jpg'] setInterval(() => { let randomNumber = Math.floor(Math.random() * imagesArr.length) console.log(randomNumber); imageSlider.style.backgroundImage = 'url("{% static '+imagesArr[randomNumber]+' %}")' }, 1000) url.py from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path("", views.index, name="index"), # User path("log_in/", views.log_in, name="log_in"), path("sign_up/", views.register, name="sign_up"), path("log_out/", views.log_out, name="log_out"), ] style.css .random_images_container { height: 515px; background-size: cover; background-image: url("{% static 'images/bc-1.jpg' %}"); width: … -
How to send Django GraphQL Auth mails with Celery?
I am using Django GraphQL Auth for authentication purposes. It has this feature to automatically send emails after creating an account or during a password reset etc. I want to use this feature with Celery and thankfully it provides that too here. It's just that I am not sure how to use that feature. Can you tell me how? -
Django - Pass PK as initial value in Form(CreateForm)
-Objective- I want to set an object PK as initial value in the Create Form. Version Python 3.9.2 - Django 3.2 - (Crispy-Forms) Context: I created a list from where I create objects(each with pk). Once I select one I can add several lines from a Detail page(Detailview)that redirects to create/update forms (like add/edit informations related to that specific object). I need to have it related (1 to many). -Issue and Error- I'm unable to get the object PK -as initial value- in the 1st field of the Creation form(based on Createview+ Forms.py + Class in Models.py). Errors such as: "object can't be null" - value does not appear in the form, but the space/widget does - many, many others. I tried plenty of variations of code(get pk from url, from cache, dict., def in forms.py)...but haven't found one way to make it work. Please, any help on the matter would be kindly appreciated. Thanks in advance, Below my code: Forms.py ----------------------------CREATION FORM IN THE ENDPAGE-------------------------- from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.db.models.fields import BooleanField, CharField, DateField from django.forms import ModelForm, widgets from django.forms.fields import ChoiceField from django.forms.models import ModelChoiceField from django.http.response import … -
Example of usage Subquery in django orm
What is the difference between two queries? Because I see identical queries through queryset.query. categories = Category.objects.filter(is_active=True).values_list("pk", flat=True) Post.objects.filter(category_id__in=Subquery(categories)) vs Post.objects.filter(category_id__in=Category.objects.filter(is_active=True).values_list("pk", flat=True)) And how to use Subquery properly? In what cases? Can anyone explain with examples Subquery, Outref etc? -
I am creating a blog site. I want to create a list field in the user model , or the profile model to store all the posts created by the user
** Help me to create a list field in the models or extend the user model to have the lists of posts created by the user. ** from django.db import models from django.contrib.auth.models import User from PIL import Image from blog.models import Post # This is my Profile Model class Profile(models.Model) : user = models.OneToOneField(User , on_delete = models.CASCADE) image = models.ImageField(default= 'default.png' , upload_to = "profile_pics") """ i want to create list field to store the posts user create . This is the Profile model . whenever a post is created by the user. the list in here saves the post created by the user. """ def __str__(self): return "{} Profile".format(self.user.username) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 125 or img.width >125 : output_size = (150 , 150) img.thumbnail(output_size) img.save(self.image.path) This is my Post model . How and where should i create the list so that i can have the track of the posts created by the user. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model) : title = models.CharField(max_length = 100) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete … -
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?