Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multiple images upload working but how to return all images related to that instance in Django rest framework
I have successfully implemented the multiple images upload , but how to return all images related to that instance in response. class ContactTransactionsViewSet(ViewSet, ListAPIView): permission_classes = [IsAuthenticated] serializer_class = ContactTransactionsSerializer filter_backends = (DjangoFilterBackend,) filter_class = ContactTransactionsFilter parser_classes = (MultiPartParser,FormParser) def get_queryset(self): user = self.request.user return ContactTransactions.objects.filter(contact__user=user, cashbook__user=user).order_by('-txn_date') def create(self, request): flag=1 data = request.data.copy() data["user"] = request.user.id if 'transaction_images' in data: images = dict((request.data).lists())['transaction_images'] else: flag=2 serializer = self.get_serializer(data=data) if not serializer.is_valid(): response_json = { "Status": "Failure", "Response": { "data": { "message": "" } }, "Error": { "code": 400, "message": "invalid request", "error_message": {} } } return Response(response_json) else: obj= serializer.save() print(obj.id) arr=[] if flag==1 and flag != 2: for img_name in images: modified_data = modify_input_for_multiple_files(obj.id, img_name) file_serializer = ContactTransactionsImagesSerializer(data=modified_data, context={"request": request}) if file_serializer.is_valid(): file_serializer.save() arr.append(file_serializer.data) else: flag = 0 if flag==0: response_json={ "Status": "Failure", "Response": { "data": { "message": "" } }, "Error": { "code": 400, "message": "invalid request", "error_message": {} } } else: dict1={"transaction_images": arr, "view_type": "body", "receive_amount": ""} dict1.update(serializer.data) response_json={ "Status": "Success", "Response": { "data": dict1 }, "Error": { "code": 201, "message": "" } } return Response(response_json) serializer.py class ContactTransactionsImagesSerializer(serializers.ModelSerializer): imagePath = serializers.SerializerMethodField() def get_imagePath(self, obj): request = self.context.get("request") return str(request.build_absolute_uri(obj.image.url)) class Meta: model = ContactTransactionsImages fields … -
get field value from form and make an object from that value django
I want to get a field value from form when submitted(object a created) and use that value to make another object(object b, which is OneToOneRelationship), if it's possible. I tried something like this, but didn't work. # models.py class Employee(models.Model): ... number = models.CharField(max_length=10, unique=True) ... class Person(models.Model): ... employee = models.OneToOneField(Employee, on_delete=models.CASCADE) ... views.py def create(request, number): if request.method == "POST": emp_form = EmployeeForm(request.POST, request.FILES) p, _ = Person.objects.get_or_create( employee=Employee.objects.get_or_create(number=emp_form.data['number'])[0] ) person_form = PersonForm(request.POST, instance=p) if emp_form.is_valid() and person_form.is_valid(): e=emp_form.save(commit=False) number=e.number e.profile = request.FILES['profile'] if 'profile' in request.FILES else None e.save() person_form.save() return redirect('employee:detail', number=number) else: emp_form = EmployeeForm() person_form = PersonForm() context = { 'emp_form': emp_form, 'person_form': person_form, } return render(request, 'employee/member_create_or_update.html', context) I know I can create Employee object first, and then add Person object later, still I'd like to know if I can create both objects in one go in one submit. Thanks for your help in advance. -
How to change a field of model prior saving the model based on another field in django 3.1
I need to be able to set the KeyIndex field of the Settings model to a value that is equal to lastExtension - firstExtension How can i do that this is the content of my model models.py class Settings(models.Model): KeyIndex = models.CharField(max_length=150, blank=True, name='Key_Index') firstExtension = models.CharField(max_length=15, blank=False, null=False, default='1000') lastExtension = models.CharField(max_length=15, blank=False, null=False, default='1010') def save(self, *args, **kwargs): f = int(self.firstExtension) l = int(self.lastExtension) a = [0] * (l - f) self.KeyIndex = str(a) return super(Settings, self).save() class KeyFiles(models.Model): setting = models.ForeignKey(Settings, on_delete=models.CASCADE) keyFile = models.FileField(upload_to='key File', null=True, blank=True, storage=CleanFileNameStorage, validators=[FileExtensionValidator(allowed_extensions=['bin']), ]) this is the content of my form forms.py class ShowAdminForm(forms.ModelForm): class Meta: model = Settings fields = '__all__' files = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), label=_("Add key Files"), required=False,validators=[FileExtensionValidator(allowed_extensions=['bin'])] ) def save_keyFile(self, setting): file = KeyFiles(setting=setting, keyFile=upload) file.save() and t admin.py class KeyFilesAdmin(admin.TabularInline): model = KeyFiles @admin.register(IPPhone_Settings) class IPPhoneSettingsAdmin(admin.ModelAdmin): form = ShowAdminForm inlines = [KeyFilesAdmin] def save_related(self, request, form, formsets, change): super(IPPhoneSettingsAdmin, self).save_related(request, form, formsets, change) -
Export Django logs to Azure AppInsights with OpenCensus
I'm following this guidance for Django and Azure. I'm able to get dependancies and requests, but not traces. I added this to middleware: 'opencensus.ext.django.middleware.OpencensusMiddleware' Here is the LOGGING and OPENCENSUS portions of settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s\n%(message)s', }, }, "handlers": { "azure": { "level": "DEBUG", "class": "opencensus.ext.azure.log_exporter.AzureLogHandler", "instrumentation_key": assert_env('APPINSIGHTS_INSTRUMENTATIONKEY'), }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "default", }, }, "loggers": { "logger_name": {"handlers": ["azure", "console"]}, }, # For some reason, this is needed or logging doesn't show up in the # celery log file. 'skyforge.tasks': { 'handlers': ['azure','console'], 'level': assert_env('DJANGO_LOG_LEVEL'), }, } OPENCENSUS = { 'TRACE': { 'SAMPLER': 'opencensus.trace.samplers.ProbabilitySampler(rate=1)', 'EXPORTER': '''opencensus.ext.azure.trace_exporter.AzureExporter( service_name='skyforge' )''' #Assumes Environmental Variable 'APPINSIGHTS_INSTRUMENTATIONKEY' } } Any guidance on where to look for why no trace logs. The django-critical and django-tasks are still going to the console. -
SyntaxError: 'return' outside function (HELP me To add Try , Except block in my Code.) [closed]
please help to to add try and except block to my following code.As i am interacting with DB. Views.py class FacilityView(viewsets.ModelViewSet): queryset = Facility.objects.all() serializer_class = FacilitySerializer I AM add in this way but not working giving me an error SyntaxError: 'return' outside function class FacilityView(viewsets.ModelViewSet): try: queryset = Facility.objects.all() serializer_class = FacilitySerializer return JsonResponse(serializer_class.data, safe=False) except: return JsonResponse({'message':'Failed'}, status=400) -
django model forms does'nt save the data
i want to create a todolist app with django. i created a form for list model but when the user click on submit to submit a list, the form is'nt saved, why? this is views.py i have created an instance of the form and set the user field to it and then save the instance but fact it does'nt Create your views here. def index(request): if request.user.is_authenticated: user_ = User.objects.get(username=request.user.username) lists = user_.user.all() form = listForm() if request.method == "POST": form = listForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect(reverse("index")) context = {'lists':lists, 'form':form} return render(request, 'todolists/index.html', context) else: return render(request, 'todolists/login.html') this is index template {% extends "todolists/layout.html" %} {% block body %} {% if user.is_authenticated %} <div class="center-column"> <form method="POST" action="{% url 'index' %}"> {% csrf_token %} {{form.title}} <input type="submit" class="btn btn-info"> </form> <div class="todo-list"> {% for list in lists %} <div class="item-row"> <a class="btn btn-sm btn-info" href="{% url 'update' list.id %}">update</a> <a class="btn btn-sm btn-danger" href="{% url 'update' list.id %}">delete</a> <span>{{list}}</span> </div> {% endfor %} </div> </div> {% endif %} {% endblock %} this is urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name='index'), path('update/<str:id>/', views.update, name='update'), path("login", … -
Generating random string (for unique code) keeps returning the same random string
I have a Test model where each test can be identified by a unique randomly-generated string: from django.utils.crypto import get_random_string class Test(models.Model): code_length = 7 code = models.CharField(max_length=code_length, editable=False, default=generate_id(code_length)) name = models.CharField(max_length=100, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "Code: {} | Username: {} | Test: {}".format(self.code, self.user.username, self.name) def generate_id(length): return get_random_string(length) Tbh, it was working good before. It started to "bugged-out" after I updated my Django from Django 1.x to Django 3.x and I also cleared all the records of the Test model in django-admin (I want to have a fresh and clean database for testing). Right now, whenever I try and create a new Test, it's code is literally the same with all other new Tests that I create: I think I haven't done anything to it other than those two changes I made. Any ideas? Thanks a lot! -
Run Selenium tests in Gitlab CI (Django project)
I'm trying to have GitLab CI run (with a shared runner) Selenium tests on my Django project every time commits are pushed to the repo on Gitlab.com. gitlab-ci.yml: image: python:3.8.5 services: - selenium/standalone-chrome:latest cache: paths: - ~/.cache/pip/ before_script: - python -V - python -m pip install --force-reinstall pip==18.1 - pip install -r requirements.txt test: script: - python manage.py test tests.py: from django.test import TestCase from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities @override_settings(DEBUG=True) class CreateNewProjectTestCase(LiveServerTestCase): def setUp(self): selenium_url = 'http://selenium__standalone-chrome:4444/wd/hub' self.selenium = webdriver.Remote( command_executor=selenium_url, desired_capabilities=DesiredCapabilities.CHROME) super(CreateNewProjectTestCase, self).setUp() However, when the pipeline job executes, I get the following error, resulting in a job's failure: selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_CONNECTION_REFUSED Is there something I am missing? I think the URL is correct and I saw answers quite similar to this. -
Show all user articles from another view in profile [django]
I have Article model in news_app class Article(Created, HitCountMixin): title = models.CharField(max_length=120) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) snippet = models.TextField(null=False) with view: class AllArticlesListView(ListView): template_name = 'news/articles_list.html' model = Article paginate_by = 5 def get_queryset(self): return self.model.objects.all().order_by('-pk') in another app (user_app) I have Profile model: class Profile(AbstractUser): bio = models.TextField(blank=True, null=True, default='Brak') with view class ProfileView(HitCountDetailView): model = Profile template_name = 'profile/profile.html' In project url I have: path("<slug:slug>", ProfileView.as_view(), name='profile'), and in news_app url I have: path('all/', AllArticlesListView.as_view(), name='all_articles_list'), How can i show all user articles IN HIS USER PROFILE? class ProfileView(DetailView): model = Profile template_name = 'profile/profile.html' count_hit = True -
Error The current path, didn't match any of these
I'm trying to save the data submitted on a form, and redirect the user to a results.html. ------- Front template ------------------- Welcome to readability test V1 <form action="/addtext" method="POST">{% csrf_token %} <input type="text" name="title"/> <input type="text" name="content"/> <input type="submit" value="Add"/> </form> ---------- URLS.PY ----------------- from django.contrib import admin from django.urls import path from readtest.views import readtest, addtext urlpatterns = [ path('admin/', admin.site.urls), path('readability-test/', readtest), path('results/', addtext), enter code here ------------ VIEWS.PY ------------------------ from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TestedText # Create your views here. def readtest(request): return render(request, 'test.html') def addtext(request): a = TestedText(title=request.POST['title'], content=request.POST['content']) a.save() return HttpResponseRedirect('/results/') ------ ERROR IM GETTING ------------------ Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/addtext Using the URLconf defined in redability.urls, Django tried these URL patterns, in this order: admin/ readability-test/ results/ The current path, addtext, didn't match any of these. -
How to place text & Image side by side using CSS & HTML
For my Django Project, I want to align Text & Image side by side. But not able to achieve it. The Image is crossing the parent div box. Can someone please help me to achieve below structure as shown in image below. Below is my piece of HTML & CSS code. <!DOCTYPE html> <html> <head> <title>AKS NAGG</title> <style> body { padding: 0; margin: 0; } .container{ background: aqua; height: 100vh; display: flex; } .box{ position: relative; margin:20px; margin-top: 40px; float: left; background: yellow; height:400px; width: 400px; border-radius: 10px; flex: 1; overflow-y: auto; } .items{ position: relative; margin: 10px; padding: 10px; border: solid; border-width: 2px; height: 100px; width: 400px; } .title{ position: relative; width: 50%; border: dotted; float: left; flex: 50%; } .image{ position: relative; float: right; clear: both; border-width: 2px; border: solid; } /* Clearfix (clear floats) */ .row::after { content: ""; clear: both; display: table; } </style> </head> <body> <div class='container'> <div class='box'> {% for t,l,i in data %} <div class='items'> <div class='title'> <a href="{{l}}">{{t}}<a/> </div> <div class='image'> <a href="{{l}}"><img src="{{i}}"></a> </div> </div> {% endfor %} </div> <div class='box'> Box2 </div> <div class='box'> Box3 </div> </div> </body> </html> Output as per my current code. The image is overlapping between … -
How To Filter foreign key in seralizers django rest framework?
Hope You Are Good! my question is how can filter foreign key in serializer? first, let's look at my code then I will explain you everything in detail! models.py class Project(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) user = models.BigIntegerField() program = models.ForeignKey(Program, on_delete=models.CASCADE) class Meta: ordering = ['-id'] def __str__(self): return self.name class Sprint(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) user = models.BigIntegerField() project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return f"{self.name}" class Backlog(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) ...... as_a = models.ForeignKey(Persona, on_delete=models.CASCADE) sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" serializers.py class ProjectSerializer(serializers.ModelSerializer): date_created = serializers.SerializerMethodField() class Meta: model = Project fields = "__all__" read_only_fields = ("id", "user", "program", "date_created",) def get_date_created(self, instance): return timesince(instance.date_created) class SprintSerializer(serializers.ModelSerializer): date_created = serializers.SerializerMethodField() class Meta: model = Sprint fields = "__all__" read_only_fields = ("id", "user", "date_created", "project",) def get_date_created(self, instance): return timesince(instance.date_created) class BacklogSerializer(serializers.ModelSerializer): date_created = serializers.SerializerMethodField() project = ProjectSerializer(read_only=True) class Meta: model = Backlog fields = "__all__" read_only_fields = ("id", "user", "date_created", "project",) def get_date_created(self, instance): return timesince(instance.date_created) views.py class BacklogAPIView(ListCreateAPIView): serializer_class = BacklogSerializer def get_project_or_404(self): return get_object_or_404(Project, pk=self.kwargs.get("uuid")) def perform_create(self, serializer): serializer.save(user=self.request.user.id, project=self.get_project_or_404()) def get_queryset(self): query_set = Backlog.objects.filter(user=self.request.user.id, project=self.get_project_or_404()) return query_set now my page looks like this: but … -
How to store image in database using django models
I have few questions please guide on these I am try to stroe images in database but they are getting store in media directory 2.The corresponding url is stored in the db column but I need actual image to be stored in the db please advice -
Why when I try to start my docker container it doesn't connect to the ports?
I have a Django app with postgresql as a database and 2 containers inside my docker compose that look like this: version: '3.7' services: web: build: ../DevelopsTest command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db db: image: postgres ports: - 5432 volumes: - postgres_data:/var/lib/postgres/data environment: - POSTGRES_USER=dbuser - POSTGRES_PASSWORD=dbpassword - POSTGRES_DB=db volumes: postgres_data: my Dockerfile looks like this: # pull official base image FROM python:3.8-alpine # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . when I run docker-compose up it gives me the next error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Address not available web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? looks like Django can't connect to my db Here are … -
Why do I get CORS error when I have the header installed in Django and React?
So I'm running both React and Django application, in port 3000 and 8000 respectively. I'm aware of the CORS policy, so installed django-cors-headers and did as written in the documentation. Like below in my settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] I don't see anything wrong, but whenever I try to fetch the api in my React, I get error saying "Access to fetch at 'http://127.0.0.1:8000/main' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." What do you think went wrong? Thank you very much in advance. *I've tried adding slash(/) at the end of "~~:3000", but still got the error. -
Django cannot find my base template, but it's there
I am "trying" to develop a Django project with Bootstrap. Because each page requires the exact same Bootstrap code, it looks more logical to me to have one base template at project level. Learning from this guide and this guide, here's the content of my project files: settings.py 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), ] views.py def homepage(request): return render(request, 'homepage/index.html') index.html {% extends 'base.html' %} {% block title %}Hello from index.html{% endblock %} {% block content %} This is from the index.html {% endblock %} Now when I browse the homepage of site (localhost:8000) I get TemplateDoesNotExist error. When I look at the error details I see this: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: D:\Django Projects\omidshojaee.com\omidshojaee_com\templates\base.html (Source does not exist) So Django is looking into the correct folder, and base.html is there (I can see it with my own eyes), so why Django cannot load it? -
python: will a custom `__module__` attribute provided to a dynamic class attrs bite me later on?
I am constructing dynamic class with type(). For some reason, when printing the class, it says something like <class 'django.forms.widgets.MyClass'>, where all besides MyClass is wrong. So I found about __module__. With this, I can make MyClass belong to the module I want it in. As far as I understand, the __module__ attribute is not really a well established standard? Found this old SO: Is "__module__" guaranteed to be defined during class creation? that explains quite well...but my question remains - are there pitfalls, or is it even considered bad practice to change __module__ of a class? Also, bonus, how come it has django.forms.widgets.MyClass as __module__ when not explicitly defining it? The real world example/proof of concept is here: https://github.com/bnzk/djangocms-baseplugins/blob/develop/djangocms_baseplugins/baseplugin/factory.py -
Execute migrations in separate postgres schema using Django
I have a requirement where my Django project needs to be connected with multiple postgres schema. For ex: If we have 20 DB tables, then 10 will remain inside public schema, then will remain in project_one schema. While running migrations also I need to provide some option to python manage.py migrate so that the tables will be created in those specific schema only. Or may be some settings in the models itself. How can we achieve this ? My default settings look like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'localhost', 'NAME': 'project_one', 'USER': 'testing', 'PASSWORD': '', 'ATOMIC_REQUESTS': True, } } -
How can i get list of news_id from manytomanyfield table in django?
class news(models.Model): category = models.ForeignKey(category, on_delete=models.CASCADE) source = models.ForeignKey(source, on_delete = models.CASCADE) headlines = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) site = models.URLField(null=True) story = models.TextField(blank=True, null=True) datetime = models.CharField(blank=True, max_length=255) image_url = models.URLField(blank=True, null=True) favourite = models.ManyToManyField(User, related_name='favourite', blank=True) ----------------- news_favourite table has id, news_id, user_id I want to perform query like select news_id from news_favourite where user_id= 1 (or it can be any user_id). -
Django exception Issue [closed]
So I have a view which creates a form, saves info from the form and accepts a payment string from payment provider. Here is the code: if request.method == 'GET': #Step 1: create form elif request.method == 'POST': try: #Step 2: get form with inputs if form.is_valid(): #Step 2.1: save info except: # there is no form. #Step 3: I accept the query set from payment provider with transaction confirmation In the last step nothing happens. I've spent like 3 yours, but still can't fix the issue. -
How to do user authentication in django when using windows (crypt module is not supported on windows)
I was trying to register user in django using User model from 'django.contrib.auth.models', but when encrypting password, it shows 'The crypt module is not supported on Windows'. Also I tried importing from passlib.hash the pbkdf2_sha256 to encrypt the data. serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): encryptedpass = pbkdf2_sha256.encrypt(validated_data['password'], rounds=12000, salt_size=32) user = User.objects.create_user(username=validated_data['username'], email=validated_data['email'], password=encryptedpass) return user views.py class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): encryptedpass = pbkdf2_sha256.encrypt(request.data['password'], rounds=12000, salt_size=32) mydata = {'username':request.data['username'], 'password':encryptedpass} serializer = AuthTokenSerializer(data=mydata) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated,] serializer_class = UserSerializer def get_object(self): return self.request.user But during authentication in login part, it does not match the credentials, maybe because the function checking for validity uses some other encryption method. How to solve this issue. -
Django: Filter data between to dates | DatetimeField received a naive datetime
I simply want to filter my records between two dates. Let's say there is a record table Measurements that has the property timestamp: class Measurements(models.Model): id = models.BigAutoField(primary_key=True) timestamp = models.DateTimeField() When I checked the timestamp of the last record Measurements.objects.last().timestamp it returns: datetime.datetime(2020, 10, 13, 6, 29, 48, 90138, tzinfo=<UTC>) Now I want to filter the data between to dates from_date and to_date. According to previous questions about this issue, I used make_aware. For testing I used count to get the amount of entries. from .models import * from datetime import datetime from django.utils.timezone import make_aware def get_measurements(request): from_date = make_aware(datetime(2020, 10, 12, 15, 30, 0, 0)) to_date = make_aware(datetime(2020, 10, 12, 16, 0, 0, 0)) print(from_date) print(to_date) measurements = DriveMeasurements.objects.filter( plc_timestamp__range=["2020-01-01", "2020-01-31"]) print(measurements.count()) When printing the two dates in my shell, it returns: datetime.datetime(2020, 10, 12, 15, 30, tzinfo=<UTC>) datetime.datetime(2020, 10, 12, 16, 0, tzinfo=<UTC>) When I run the function above, Django fires the following message: RuntimeWarning: DateTimeField Measurements.timestamp received a naive datetime (2020-01-31 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" The print statement print(measurements.count()) prints 0 but there are ~ 18000 records in the database. So why is the filter … -
curl: (6) Could not resolve host: Token
I'm trying to make a Django and Vue.js Chat application. I used Django rest framework. I installed them using pip. I've created user using djoser. When I'm trying to run this in cmd to get the created user details ---> curl -LX GET http://127.0.0.1:8000/auth/users/me/ -H 'Authorization: Token ae44f43cbb2a9444ff4be5b75e60a712e580902c' ,I'm getting curl: (6) error Below is the Django views.py file : """Views for the chat app.""" from django.contrib.auth import get_user_model from .models import ( ChatSession, ChatSessionMember, ChatSessionMessage, deserialize_user ) from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import permissions class ChatSessionView(APIView): """Manage Chat sessions.""" permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): """create a new chat session.""" user = request.user chat_session = ChatSession.objects.create(owner=user) return Response({ 'status': 'SUCCESS', 'uri': chat_session.uri, 'message': 'New chat session created' }) def patch(self, request, *args, **kwargs): """Add a user to a chat session.""" User = get_user_model() uri = kwargs['uri'] username = request.data['username'] user = User.objects.get(username=username) chat_session = ChatSession.objects.get(uri=uri) owner = chat_session.owner if owner != user: # Only allow non owners join the room chat_session.members.get_or_create( user=user, chat_session=chat_session ) owner = deserialize_user(owner) members = [ deserialize_user(chat_session.user) for chat_session in chat_session.members.all() ] members.insert(0, owner) # Make the owner the first member return Response ({ 'status': 'SUCCESS', 'members': members, … -
How to get data by filtering with two different dates in django?
This is my model; class FundData(models.Model): fund = models.ForeignKey(Fund, on_delete=models.CASCADE, related_name="data_of_fund", verbose_name="Fund") date = models.DateField(auto_now_add=False, editable=True, blank=False, verbose_name="Date") price = models.FloatField(max_length=15, blank=False, verbose_name="Fund Price") This is my frontend where i want to choose dates; <div class="col-12 d-flex align-items-end"> <div> <label>Starting Date</label> <input id="startDatePicker" type="text" class="form-control datepicker" autocomplete="off"> </div> <div class="mx-2"> <label>Ending Date</label> <input id="endDatePicker" type="text" class="form-control datepicker" autocomplete="off"> </div> <a onclick="getFundReturnsByDate()" class="btn btn-info" href="javascript:void(0);"> Show<i class="fas fa-caret-right"></i></a> </div> All i want is that user should choose 2 dates and bring the data of the selected dates in a table. Any help is appreciated, thanks! -
Django Dashboard with Node.js
I am trying to build a Django app and currently, I wanted to program to shut down my server directly from a button and Rebooting from a separate button. html code..... <button onclick="powerOff()" class="button">Power Off</button> <p id="poweroff"></p> <button onclick="reboot()" class="Reboot">Reboot</button> <p id="reboot"></p> Javascript code:... <script> function powerOff() { if (confirm("Are you sure you want to power off ?")) { require('child_process').exec('sudo shutdown -r now', function (msg) { console.log(msg) }); } } function reboot() { if (confirm("Are you sure you want to reboot ?")) { } else { } </script> When I am running this code directly from my terminal it is functioning but it is not executing from the app.