Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Django custom form validator to work?
I'm working on a custom valdator for my Django forms. Inexplicably, I can't get the result I want. Here is my code from django import forms from django.core import validators from django.core.exceptions import ValidationError from .models import Vote from django.core.validators import MaxValueValidator, MinValueValidator def use_one(value): if value != 1: raise forms.ValidationError("Value is not 1!") class MyForm(forms.Form): main_form = forms.IntegerField(validators = [use_one], label= 'Main', required = False, widget = forms.NumberInput( attrs={'id': 'mainInput', 'name': 'main, 'href': '#', 'value': '', 'class': "form-control"})) Any thoughts? views.py form = MyForm() main_result = request.GET.get(main_form) form.fields['main_form_result'].initial = main_result context = {form: form} -
Blank page on react production build with django and nginx on proxy server
I'm trying to deploy a django application on a proxy server (otlart.com, IP 111.22.333.44) and make it accessible from http://dome.com:8080/annotator. The django admin page and rest_framework render correctly, however the react build shows a blank page despite not throwing any error on page and script loading. All pages render correctly when I access 111.22.333.44:80 directly. Settings on dome.com for proxy: <VirtualHost *:8080> ServerName dome.com ServerAlias www.dome.com ServerAdmin scandav@example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ProxyRequests Off <Proxy *> Order deny,allow Allow from all </Proxy> ProxyPass /annotator http://111.22.333.44 ProxyPassReverse /annotator http://111.22.333.44 <Location /> Order allow,deny Allow from all </Location> </VirtualHost> The application folder tree is: 📦app ┣ 📂backend ┃ ┣ 📂static ┃ ┃ ┣ 📂admin ┃ ┃ ┣ 📂css ┃ ┃ ┣ 📂js ┃ ┃ ┣ 📂media ┃ ┃ ┗ 📂rest_framework ┃ ┣ 📜__init__.py ┃ ┣ 📜....py ┃ ┣ 📜settings.py ┃ ┣ 📜urls.py ┃ ┗ 📜wsgi.py ┣ 📂frontend ┃ ┣ 📂build ┃ ┃ ┣ 📂static ┃ ┃ ┣ 📜asset-manifest.json ┃ ┃ ┣ 📜index.html ┃ ┃ ┗ 📜robots.txt ┣ 📂web_annotator ┃ ┣ 📂migrations ┃ ┣ 📜admin.py ┃ ┣ 📜apps.py ┃ ┣ 📜models.py ┃ ┗ 📜views.py ┗ 📜manage.py Django settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "frontend" / "build", ], … -
How to upload picture using Ajax in Django ? Python
I am trying to upload profile picture using Ajax (using FormData) in Django. Following is the code I used it in html page, <img src="/media/{{user_profile.picture}}" width="150" height="150" alt="" id="pro_file"/> <input id="upload-file" type="file" name="file"/> and in jQuery (Ajax), var fd = new FormData(); var vidFileLength = $('#upload-file')[0].files.length; if(vidFileLength === 0){ var files = $('#pro_file').attr('src'); } else{ var files = $('#upload-file')[0].files[0]; } fd.append('file',files); Then I have sent the fd in data attribute in Ajax. However, in views.py following is my snippet code, fd = request.FILES try: profile_pic = fd['file'] except KeyError as e: profile_pic = request.POST['file'] profile_pic = str(profile_pic).replace("/media/","") Using this method, my code works but I doubt is it a proper way to do it ? Any suggestions please ? -
Using Client side camera, with Django, in FER
I am trying to make an emotion recognition app with Django and OpenCV. My app is also up on Azure, and I was informed that I need to access the client side camera, because there are no cameras where the Azure servers are located. I have tried to use channels to do this, but I can't seem to find a way to get the video to work the way I want to. Has anyone discovered a way to use OpenCV on the client side using Django/Channels? Here is my code so we can all look at what I have so far. camera.py import cv2 import mediapipe as mp from fer import FER import os import numpy as np from keras.models import model_from_json from keras.preprocessing import image json_file = open("emotion/fer.json") loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # Model setup loaded_model.load_weights('emotion/models/fer/fer.h5') detector = FER() # Media pipe face mesh mp_draw = mp.solutions.drawing_utils mp_face_mesh = mp.solutions.face_mesh faceMesh = mp_face_mesh.FaceMesh(max_num_faces=2) draw_specs = mp_draw.DrawingSpec((255, 0, 0), 1, 1) # OpenCV Haarcascade face_cascade = cv2.CascadeClassifier( 'emotion/haarcascade_frontalface_default.xml') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) self.prediction = "" self.score = 0 def __del__(self): self.video.release() def getScore(self): return self.score def getEmotion(self): return self.prediction def get_frame(self): success, frame = … -
Why can't my Django app find my function in views?
I'm new to Django and am trying to create a simple "Hello World" webpage. I've set up a project and an application, but in the urls.py of my application it says that the function I've defined in views can't be found. Pycharm seems to not even recognize the two lines of my function because it says "expected 2 blank lines, found 1" although that may not be what that means. Any ideas are appreciated. views.py main/urls.py -
Django: Urls Optional Query Parameters
Urls.py: app_name = 'main' urlpatterns = [ path('',include(router.urls)), path('player_id=<str:player>%season_id=<str:season>',views.MatchesList.as_view()) ] Views.py class MatchesList(generics.ListAPIView): serializer_class = MatchesSerializer permissions = (IsAuthenticated) def get_queryset(self): player = self.kwargs['player'] season = self.kwargs['season'] if season is None: queryset = Matches.objects.filter(player=player).all() else: queryset = Matches.objects.filter(player=player,season=season).all() return queryset Is there any way to request without the parameter 'season'? Something like that: app_name = 'main' urlpatterns = [ path('',include(router.urls)), path('player_id=<str:player>',views.MatchesList.as_view()) ] -
How to Use URL dispatcher to get clickable link to list contents of my page DJANGO
I want to make a list of items showing on my index.html page to be clickable, I used the url dynamic reverse technique but i keep getting this error. Please guide me on what I may be doing wrong. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%25%20url%20'entrypage'%20entry%20%25 Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order: admin/ [name='index'] wiki/<str:title> [name='entrypage'] The current path, {% url 'entrypage' entry %, didn’t match any of these. URLS.PY app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry_page, name='entrypage'), ] HTML <ul> {% for entry in entries %} <li> <a href="{% url 'entrypage' entry %">{{ entry }}</a> </li> {% endfor %} </ul> VIEWS.PY def entry_page(request, title): title = util.get_entry(title) if title: content = markdown2.markdown(title) context = { "title": title, "content": content, } return render(request, "encyclopedia/entrypage.html", context) else: return render(request, "encyclopedia/errorpage.html") What am i doing wrong please. I'm a beginner -
"This field is required." - in django
my model class User(models.Model): lang = models.CharField(max_length=40,choices=LANGUAGE_CHOICES, default='ru') email = models.EmailField(("E-mail"), max_length=254, unique= True) user_name = models.CharField(("Имя"),max_length=60) phone_number = models.CharField(("Телефон"),max_length=60, unique= True) date_of_meeting = models.CharField(max_length=50,choices = DATE_OF_MEETING,default = FIRST) def __str__(self): return "%s %s" % (self.user_name, self.email) my views.py I used modelform_factory() in my views to create form without forms.py. class UserView(APIView): def post(self,request,*args, **kwargs): if request.method == 'POST': form = modelform_factory(User, fields="__all__") response = form(request.POST) if response.is_valid(): response.save() return JsonResponse(status=status.HTTP_201_CREATED) else: return JsonResponse(response.errors, status=status.HTTP_400_BAD_REQUEST) my post request from postman { "lang": "ru", "email": "asdms@mail.m", "user_name": "asdasd", "phone_number": "123123", "date_of_meeting": "20-11-2021" } After post request I got: { "lang": [ "This field is required." ], "email": [ "This field is required." ], "user_name": [ "This field is required." ], "phone_number": [ "This field is required." ], "date_of_meeting": [ "This field is required." ] } How to handle that post request correctly and also write in my model? Is this error because of I didn't use serializer? -
control webpage remotely? ( telegram/discord bot )
I have a simple flask web app with a multi-step form like 3 steps for submitting information and I receive the data in a telegram bot My Question here is it possible to control the form? like if someone submits data he can pass step1 and step2 but he can't pass to step3 until I allow him by sending a command or request or something similar? and maybe display a loading or timing bar while waiting -
issue with setting up the username field in form initial in Django
I have a form with a username field. The form is available only for logged-in users. I am trying to populate the username in the User field but with no success. What am I doing wrong? models.py class Feedback(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) email = models.EmailField(default='') title = CharField(max_length=300, blank=True, null=True, default='') body = RichTextField(max_length=1500) published = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): self.user = self.user.username super(Feedback, self).save(*args, **kwargs) forms.py class FeedbackForm(forms.ModelForm): captcha = ReCaptchaField() user = forms.CharField(initial='username') # it displays username as a string but request.user.username doesn't work here class Meta: model = Feedback fields = ['user', 'email', 'title', 'body', 'captcha'] views.py @login_required def hal_feedback(request): if request.method == 'POST': form = FeedbackForm(request.POST, initial={"username": request.user.username}) # putting request.user.username in initial also it also doesn't work if form.is_valid(): obj = form.save(commit=False) email = form.cleaned_data['email'] title = form.cleaned_data['title'] body = form.cleaned_data['body'] current_site = get_current_site(request) subject = 'Feedback' message = render_to_string('articles/post_question_confirmation.html', { 'obj': obj, 'domain': current_site.domain, 'content': body, 'title': title, }) obj.save() send_mail(subject, message, "auth.ADMIN", [email], fail_silently=False) return redirect('success') else: initial = {'username':request.user.username} form = HALFeedbackForm(initial=initial) return render(request, "articles/question.html", {'form': form}) -
Complex join of two tables - columns are grouped values from second table
So, i'm trying to make somekind of a pivot (?) table for my django project, but with no luck - details: First table - 'keyword': | id | name | fk_project_id | | -------- | -------------- |-------------------| | 1 | stack | 1 | | 2 | overflow | 1 | Second table - 'position': | id | fk_keyword_id | rank |date_created| region | | -------- | ----------------|--------|------------|--------| | 1 | 1 | 22 |2021-01-01 | UK | | 2 | 1 | 44 |2021-01-02 | UK | | 3 | 1 | 55 |2021-01-02 | FR | | 4 | 2 | 11 |2021-01-01 | FR | | 4 | 2 | 22 |2021-01-02 | FR | I want to combine that tables to one, where first column is keyword.name, and all others would create dynamically based on values 'date_created' and 'region' from second table, to have something like this: | keyword_name| UK,2021-01-01 | UK,2021-01-02|FR,2021-01-01|FR,2021-01-02| | ----------- | ----------------|----------------|-------------|-------------| | stack | 22 | 44 | 55 | null | | overflow | null | null | 11 | 22 | I am using django with postgresql, so i can get all needed names for columns before making query … -
Django to postgres, OperationalError could not load plpgsql.dll even though it is there
I have an Angular frontend/Django backend webapp where the database is hosted on a remote Windows 2019 server in postgreSQL 13. The frontend code etc. is all fine, but I'm suddenly unable to do POST and PUT requests, bet GET requests work perfectly fine. It's the same thing connecting to the database via Data Studio, SELECT statements work, but not INSERT or UPDATE. When I try, I'm getting an error with not able to load the plpgsql.dll library since the resource cannot be found, but following the filepath it's clearly there. I decided to try to open pgAdmin4, but am getting a "Fatal Error: The application server cannot be contacted" I figure this must be the root of the issue. I believe there was an update recently that may have caused this, but I'm not sure and am not very familiar with postgres or pgAdmin. I've seen some solutions to similar problems like deleting everything in the "sessions" folder, specifically regarding the fatal error, but how will this effect the data that is currently there, and would this even solve the issue of the plpgsql.dll library? Thanks -
Delete 2 model different objects which reference each other as foreign keys
We have two Django models: class Project(models.Model): project_title = models.CharField(max_length=30) owner = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) class User(models.Model): usernmae = models.CharField(max_length=50) active_project = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING, related_name='current_project') I have a user with object (with id say 692). And this user created a project with id=12345, therefore these owner field will get have this particular referenced. I want to delete that user. But it shows error that delete on table "app_user" violates foreign key constraint This is expected as on_delete=models.DO_NOTHING, was set. One way I found out was using on_delete=models.CASCADE. Question: How should I go about deleting the user (692) without changing the model definition(having to re-run migration)? Doing it manually by deleting the project first, leads to the same foreign-key error, as owner field is User object. How to handle this mutual foreign key relationship while deleting, as deleting any one of those two throws the foreign-key exception? -
Send selected radio button id from Datatable to Django URL
I'm looking for a solution to get the value from my radio button and send it to my django url. When I get selected radio button in the first page of DataTables, it's working properly, However when select radio button from other page (not first page), I can't get the radio button value HTML <a href="{% url 'update_maintenance_issue' %}" id="edit"> <img src="{% static 'images/icons/edit3.png' %}"> </a> <table id="mytable1"> <thead align="center"> <tr align="center" style="font-weight:bold"> <th style="cursor:pointer" align="center">No</th> <th style="cursor:pointer" align="center">ID</th> <th style="cursor:pointer" align="center">Type</th> <th style="cursor:pointer" align="center">Line</th> <th style="cursor:pointer" align="center">Sequence</th> <th style="cursor:pointer" align="center">Module</th> <th style="cursor:pointer" align="center">Item</th> <th style="cursor:pointer" align="center">Sympton</th> <th style="cursor:pointer" align="center">status</th> <th style="cursor:pointer" align="center">Register</th> <th style="cursor:pointer" align="center">Assigned</th> <th style="cursor:pointer" align="center">Register dt</th> </tr> </thead> <tbody> {% for list in issue_list %} <tr> <td> <input name="radio_id" type="radio" id="radio_id" value="{{list.id}}"> </td> <td align="center">{{ list.id }} </td> <td align="center">{{ list.line_nm }} </td> <td align="center">{{ list.line_nm }} </td> <td align="center">{{ list.sequence}} </td> <td align="center">{{ list.division }} </td> <td align="center">{{ list.module }} </td> <td align="left">{{ list.sympton }}</td> <td align="left">{{ list.status }}</td> <td align="center">{{ list.register }}</td> <td align="center">{{ list.assigned }}</td> <td align="center">{{ list.register_dt|date:'d/m/Y H:i' }}</td> </tr> {% endfor %} </tbody> </table> <!--DataTables--> <script type="text/javascript"> $(document).ready( function (){ $('#mytable1').DataTable(); }); </script> <!--Get ID from selected radio button and insert … -
Mysqlclient Installation error in python Django
I try to build a sample project in Pycharm. But In the step migrate classes i face an error. I am using the code python manage.py makemigrations Then terminal shows install mysqlclient. I am using pip install mysqlclient Then shows a error below sreeju@Sreeju:~/PycharmProjects/pythonProject21/SampleProject123$ python manage.py makemigrations Traceback (most recent call last): File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/sreeju/PycharmProjects/pythonProject21/SampleProject123/manage.py", line 22, in <module> main() File "/home/sreeju/PycharmProjects/pythonProject21/SampleProject123/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/sreeju/PycharmProjects/pythonProject21/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line … -
Create a modules with models in python
I have a rather strange problem, I wanted to make a whole module of models but django does not recognize that module with models For example: I created this module in which I made a folder models I also made an init py in which I import the model but nothing happens to me How should I proceed in this situation? -
How to combine two queryset by a commin field
I have these two below querysets. They have a common road_type_id edges = Edge.objects.values("road_type_id", "edge_id", "name", "length", "speed", "lanes").filter(network=roadnetwork) roadtypes = RoadType.objects.values("road_type_id", "default_speed", "default_lanes" ).filter(network=roadnetwork) I would like to replace in edges : all lanes with None as value by roadtypes.default_lanes all speed with None as value by roadtypes.default_speed How can I do that please? -
How to save some data in user model and some data save in extended user model from a html form
model.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.db.models.fields import CharField, DateField Create your models here. class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) phone=models.CharField(max_length=20) DateOfBirth=DateField(max_length=50) profession=CharField(max_length=50) bloodGroup=CharField(max_length=20) gender=CharField(max_length=20) city=CharField(max_length=30) thana=CharField(max_length=30) union=CharField(max_length=30) postCode=CharField(max_length=20) otp=models.CharField(max_length=30) def __str__(self) -> str: return self.user.username views.py def registrations(request): if request.method == 'POST': fname = request.POST.get('fname') lname = request.POST.get('lname') username = request.POST.get('username') phone = request.POST.get('phone') email = request.POST.get('email') Password = request.POST.get('password') Password2 = request.POST.get('password2') DateOfBirth = request.POST.get('DateOfBirth') profession = request.POST.get('profession') bloodGroup = request.POST.get('bloodGroup') gender = request.POST.get('gender') city = request.POST.get('city') thana = request.POST.get('thana') union = request.POST.get('union') postCode = request.POST.get('postCode') check_user = User.objects.filter(email=email).first() check_profile = UserProfile.objects.filter(phone=phone).first() if Password != Password2: context1 = {"message1": "Password mismatch", "class1": "danger"} return render(request, 'UserProfile/registration.html', context1) if check_user or check_profile: context = {"message": "User already exist", "class": "danger"} return render(request, 'UserProfile/registration.html', context) user = User.objects.create_user( first_name=fname, last_name=lname, username=username, email=email, password=Password) user.save() profile= UserProfile(user=user, phone=phone, DateOfBirth=DateOfBirth, profession=profession, bloodGroup=bloodGroup, gender=gender, city=city, thana=thana, union=union, postCode=postCode, ) profile.save() context = {"message": "Successfully registrations Complate", "class2":"alert1 success ", } return render(request, 'UserProfile/login.html', context) return render(request, 'UserProfile/registration.html') enter image description here I want to save the user name, email, password in the user model and others field wants to save in the UserProfile … -
Display Django Admin group selection while creation User
I'm trying to simplify User creation, showing User Model fields, 1 field from an extended Model and the group selection from Django Admin. It's working fine, but I can't get the same selection as Update User page. I'm trying to make this: [Group selection from User Update][1] But I can only get to this: [Default Django Multiple Choices][2] Here is my admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User, Group from django.contrib.auth.forms import UserCreationForm from django import forms # Register your models here. from .models import * class UserCreateForm(UserCreationForm): group = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ('username', 'first_name' , 'last_name', 'group', ) class UserBoolInline(admin.StackedInline): model = UserBool fk_name = 'user' can_delete = False verbose_name_plural = 'UserBool' class UserAdmin(BaseUserAdmin): add_form = UserCreateForm inlines = (UserBoolInline,) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('first_name', 'last_name', 'username', 'password1', 'password2', 'group' ), }), ) admin.site.unregister(User) admin.site.register(User, UserAdmin)``` [1]: https://i.stack.imgur.com/N1LcX.png [2]: https://i.stack.imgur.com/7EApY.png -
Serializers django rest framework
I am new to Django rest framework, I am working on a small project and I am facing a truoble with serializsers what I need is one URL request with a list of all the name of school, and another URL request that has all the information about the school(name, city, street, student). The probleem is that in both URLs I get the same information which is (name, city, street, student). Can someone help me with that? serializers.py class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] class SchoolNameSerializer(serializers.ModelSerializer): class Meta: model = School fields = ['name'] views.py class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() class SchoolNameViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolNameSerializer queryset = School.objects.all() urls.py router.register(r'schoolname', SchoolNameViewSet) router.register(r'school', SchoolViewSet) -
RuntimeError at /signup
I am begginer in django. I am getting this error. "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings." Can anyone help to solve this error? urls of my app: from django.contrib import admin from django.urls import path, include from home import views urlpatterns = [ path('',views.home, name='home'), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('search/', views.search, name='search'), path('signup/', views.handleSignUp, name="handleSignUp"), ] views.py: def contact(request): messages.success(request, 'Welcome to contact') if request.method=="POST": name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] content = request.POST['content'] # print(name, email, phone, content) if len(name)<2 or len(email)<3 or len(phone)<10 or len(content)<4: messages.error(request, "Please fill the form correctly") else: contact = Contact(name=name, email=email, phone=phone, content=content) contact.save() messages.success(request, "Your message has been successfully sent") return render(request, "home/contact.html") models.py: from django.db import models class Contact(models.Model): sno= models.AutoField(primary_key=True) name= models.CharField(max_length=255) phone= models.CharField(max_length=13) email= models.CharField(max_length=100) content= models.TextField() timeStamp = models.DateTimeField(auto_now_add=True,blank=True) def __str__(self): return "Message from " + self.name + ' - ' + self.email admin.py: from django.contrib import admin from .models import … -
Why I am getting "Not Implemented Error: Database objects do not implement truth value testing or bool()." while running makemigration cmd in django
I am trying to connect Django with MongoDB using Djongo. I have changed the Database parameter but I am getting this error Not Implemented Error: Database objects do not implement truth value testing or bool(). when I am running makemigration command. Please can anybody explain why I am getting this error and how to resolve it? I have include settings.py file, error log and mongodb compass setup image. settings.py """ Django settings for Chatify project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-1k4mo05el_0112guspx^004n-i&3h#u4gyev#27u)tkb8t82_%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Chatify.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, … -
RuntimeWarning: DateTimeField Model.date received a naive datetime while time zone support is active
I am trying to filter a query set to obtain this year's all posts. def thisYearQuerySet(objects): start_day = datetime.date(datetime.date.today().year, 1, 1) end_day = datetime.date(datetime.date.today().year, 12, 31) return objects.filter(date__range=[start_day, end_day]) django moans about start_day and end_day declaration may conflicts django.utils.timezone, I think it is not a big deal. But the warning is annoying, any suggestion on dismissing it (not disable django warning) will be appreciated. something like, how to get first day of the year and the last from django.utils full warning RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-01-01 00:00:00) while time zone support is active. RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-12-31 00:00:00) while time zone support is active. -
Django heatmap d3.js passing returned data from search
am creating a searchable repository that displays heatmap after the search is completed in django (windows) and postgresql. my code for the search is not used to HTML. views.py def search_result(request): if request.method == "POST": ChemSearched = request.POST.get('ChemSearched') tarname = Bindll.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched)[:10] return render(request, 'Search/search_result.html', {'ChemSearched':ChemSearched,'tarname':tarname}) else: return render(request, 'Search/search_result.html',{}) Searchresults.html ... <br/><br/><br/><br/> <strong><h1>{% if ChemSearched %} <script> var margin = {top: 30, right: 30, bottom: 30, left: 30}, width = 450 - margin.left - margin.right, height = 450 - margin.top - margin.bottom; var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); {% for Bindll in tarname %} var myGroups = [ "{{ Bindll }}" ] var myVars = [ "{{ Bindll.ki_nm }}" ] {% endfor %} var x = d3.scaleBand() .range([ 0, width ]) .domain(myGroups) .padding(0.01); svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) var y = d3.scaleBand() .range([ height, 0 ]) .domain(myVars) .padding(0.01); svg.append("g") .call(d3.axisLeft(y)); var myColor = d3.scaleLinear() .range(["white", "#69b3a2"]) .domain([1,100]) d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) { svg.selectAll() .data(data, function(d) {return d.group+':'+d.variable;}) .enter() .append("rect") .attr("x", function(d) { return x(d.group) }) .attr("y", function(d) { return y(d.variable) }) .attr("width", x.bandwidth() ) .attr("height", y.bandwidth() ) … -
django rest framework model habit tracker
I'm trying to do an habit tracker using django rest framework as backend and react-native as frontend. I have same issue with the model of data in django. I want create one Daily instance for each date between start_date and end_date when a Tracker is created. Could you give me some help on how I can do it? Thank you in advance. models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime class Habit(models.Model): title = models.CharField(max_length=32) description = models.TextField(max_length=360) class Tracker(models.Model): habit = models.ForeignKey(Habit, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() published = models.BooleanField(default=True) def is_active(self): today = datetime.now().date() return (today >= self.start_date) and (today <= self.end_date) class Daily(models.Model): STATUS = [('DONE', 'DONE'), ('TODO', 'TODO'), ('NOTDONE', 'NOTDONE'),] date = models.DateField() status = models.CharField(choices=STATUS, max_length=10) tracker = models.ForeignKey(Tracker, on_delete=models.CASCADE) serializers.py from rest_framework import serializers from .models import Habit, Tracker, Daily from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) return user class HabitSerializer(serializers.ModelSerializer): class Meta: model = Habit fields = ['id', 'title', 'description'] class TrackerSerializer(serializers.ModelSerializer): class Meta: model …