Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Test cookies in django
I wanted to check if a browser accepts cookies, so I used set_test_cookie and test_cookie_worked methods to check the same. Then I deleted the test cookies using delete_test_cookie method if the browser passed the test. But to my surprise the session cookie still resides in the browser. This issue exists in both Firefox and Chrome. So what exactly the delete_test_cookie does? Does it delete session cookie? Or is it that session cookie and test cookie are different? -
How to make an asynchronous script for checking online from Minecraft servers?
I need a script to check online from Minecraft servers every 5 minutes. Now the script executes a query request to the server and saves one server to the online database only when entering the server page. Advise how to implement an asynchronous (background for the user) online validation script for all servers views.py class NewsDetailView(DetailView): model = Servers template_name = 'server/server_detail.html' def get_context_data(self, **kwards): ctx = super(NewsDetailView, self).get_context_data(**kwards) ctx['title'] = Servers.objects.filter(pk=self.kwargs['pk']).first() return ctx queryset = Servers.objects.all() def get_object(self): obj = super().get_object() try: server = MinecraftServer.lookup(obj.ip) status = server.status() try: obj.num_players = status.players.online obj.max_players = status.players.max except: print('[Error] Server', str(obj.ip), 'not available') obj.num_players = 0 obj.max_players = 0 obj.save() except: pass return obj -
how to pass another argument to url django?
dans my views.py of page1.html : def spwords(request, spray_id) if request.method == 'POST': value= request.POST["rangeVal"] #### the other argument that i want to pass it to views.py of the second page html ... form = forms.SprayKeywordsForm(request.POST) return HttpResponseRedirect(reverse('sp_url', args=[sp_id])) # if POST we go to page2.html on this url in my url.py : url(r'^queries/(.*)$', qviews.sp_queries, name='sp_url') in my views.py of the Page2.html : def sp_queries(request, sp_id): #### here i want to recupere arguments : sp_id and value i want to pass value= request.POST["rangeVal"] of the views.py of the first page html to the second page html, i.e , i want to pass value in arguments of "HttpResponseRedirect(reverse('sp_url', args=[sp_id]))". but i want to keep the format of urls.py : i.e just queries/sp_id -
how can i show images and checkboxes in xhtml2pdf using django
I am converting Html into pdf using xhtml2pdf using Django and this is my code def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def myView(request): pdf = render_to_pdf(pdf_template, params) return HttpResponse(pdf, content_type='application/pdf') everything's working fine till now, but I also want to show the company logo and some checkboxes on pdf and that is not working. no error, no wrong output, just blank space in place of image and checkboxes. Any idea of how can I get images and checkboxes in my pdf? -
How can I show the StringRelatedField instead of the Primary Key while still being able to write-to that field using Django Rest Framework?
Models: class CrewMember(models.Model): DEPARTMENT_CHOICES = [ ("deck", "Deck"), ("engineering", "Engineering"), ("interior", "Interior") ] first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField() department = models.CharField(max_length=12, choices=DEPARTMENT_CHOICES) date_of_birth = models.DateField() join_date = models.DateField() return_date = models.DateField(null=True, blank=True) leave_date = models.DateField(null=True, blank=True) avatar = models.ImageField(null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return f"{self.first_name} {self.last_name}" class RosterInstance(models.Model): date = models.DateField(default=timezone.now) deckhand_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="deckhand_watches") night_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="night_watches") def __str__(self): return self.date.strftime("%d %b, %Y") Views: class CrewMemberViewSet(viewsets.ModelViewSet): queryset = CrewMember.objects.all() serializer_class = CrewMemberSerializer filter_backends = [SearchFilter] search_fields = ["department"] def destroy(self, request, *args, **kwargs): instance = self.get_object() instance.active = False instance.save() return Response(status=status.HTTP_204_NO_CONTENT) class RosterInstanceViewSet(viewsets.ModelViewSet): queryset = RosterInstance.objects.all() serializer_class = RosterInstanceSerializer Serializers: class CrewMemberSerializer(serializers.ModelSerializer): class Meta: model = CrewMember fields = "__all__" class RosterInstanceSerializer(serializers.ModelSerializer): class Meta: model = RosterInstance fields = "__all__" The resulting data looks like this: { "id": 2, "date": "2020-12-09", "deckhand_watchkeeper": 1, "night_watchkeeper": 3 } But I want it to look like this: { "id": 2, "date": "2020-12-09", "deckhand_watchkeeper": "Joe Soap", "night_watchkeeper": "John Smith" } I can achieve the above output by using StringRelatedField in the RosterInstanceSerializer but then I can no longer add more instances to the RosterInstance model (I believe that is because StringRelatedField … -
show a new input in django forms with a button click
I have a form that has 13 inputs some of them are <input> and others are <select> In the beginning I only show the first two inputs and the others are completely ignored, now what I want is to make a button to show the next input. My Idea was that I make 13 forms in the forms.py file but I don't think it's a good idea. so how can I do that? -
Backend countdown timer in django
I am developing a quiz application in Django. I wish to maintain a timer for attending a quiz, and user shouldn't be able to change the time from the front end. There maybe ways to implement one using JavaScript, but those could be easily changed by the user. So what i want is something like maintain a timer at the server side so that the quiz gets automatically submitted once the time is up. I am working on django 3.1. Please help. -
Best approach to customize django admin page for existing app
I'm currently learning some basics of django by trying to implement admin page for the following app: PowerGSLB Though it already has nice UI based on W2UI my goal is to learn django and make role based authentication with help of django admin module. But it's actually not the point of the question. I got stuck with presenting basic list of DNS records to user. DB model looks like this: db_model_image So, I ran through inspectdb and created models, based on this structure. After all, my Records model looks like this: class Records(models.Model): id = models.BigAutoField(primary_key=True) name_type = models.ForeignKey(NamesTypes, models.DO_NOTHING) content_monitor = models.ForeignKey(ContentsMonitors, models.DO_NOTHING) view = models.ForeignKey('Views', models.DO_NOTHING) disabled = models.BigIntegerField() fallback = models.BigIntegerField() weight = models.BigIntegerField() def __str__(self): return f"{self.name_type} {self.content_monitor} {self.disabled} {self.fallback} {self.weight}" def get_all(self, in_var): self.result = dict() # Objects to get results from self.name_type_obj = NamesTypes.objects.get(id=self.name_type_id) self.content_monitor_obj = ContentsMonitors.objects.get(id=self.content_monitor_id) self.view_obj = Views.objects.get(id=self.view_id) self.names_obj = Names.objects.get(id=self.name_type_obj.name_id) self.domain_obj = Domains.objects.get(id=self.names_obj.domain_id) self.contents_obj = Contents.objects.get(id=self.content_monitor_obj.content_id) self.monitor_obj = Monitors.objects.get(id=self.content_monitor_obj.monitor_id) self.types_obj = Types.objects.get(value=self.name_type_obj.type_value_id) # Result vars self.result['domain'] = self.domain_obj.domain self.result['name'] = self.names_obj.name self.result['type'] = self.types_obj.type self.result['content'] = self.contents_obj.content self.result['ttl'] = self.name_type_obj.ttl self.result['id'] = self.id self.result['disabled'] = self.disabled self.result['fallback'] = self.fallback self.result['persistence'] = self.name_type_obj.persistence self.result['weight'] = self.weight self.result['monitor'] = self.monitor_obj.monitor self.result['view'] = self.view_obj.rule … -
drf if not verified create user
i have this app and i'm doing otp verification on mail after registration. if user not verified then send mail again so i have added this check on registration if user exist and is_verified then return user already exist otherwise i want to delete and create again because it'll proceed without deleting but i'm getting error on else condition: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'tuple'>` seems its expect response on else condition after deleting user and i want to create again after delete and also if user doestnotexist then simply create one and send mail @api_view(["POST"]) @permission_classes((AllowAny,)) def register(request): try: user = CustomUser.objects.get( email=request.data.get('email')) if user.is_verified: return Response({'message': 'Customer with this mail already exists', 'status': 'false', 'status_code': status.HTTP_401_UNAUTHORIZED, 'currentTimeStamp': datetime.datetime.now()}, status=status.HTTP_400_BAD_REQUEST) else: user.delete() except CustomUser.DoesNotExist: serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() serializers.py: class CustomUserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(required=False) password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile', None) user = CustomUser( email=validated_data['email'], mobile_number=validated_data['mobile_number'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], ) user.set_password(validated_data['password']) def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) … -
How to delete from queryset without deleting the original model itself in Django
So, I have two model sets like the following: # User class class User(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() ... email = models.EmailField(verbose_name='email', max_length=50, null=False, unique=True) password = models.CharField(verbose_name="password", max_length=200) name = models.CharField(verbose_name="name", max_length=50) username = models.CharField(verbose_name="nickname", max_length=50, unique=True) date_of_birth = models.DateField(verbose_name="birthday", max_length=8) profile_pic = models.ImageField(verbose_name="profile picture", default="default_profile.png") USERNAME_FIELD='email' REQUIRED_FIELDS=['password', 'name', 'username', 'date_of_birth'] followers = models.ManyToManyField( 'self', symmetrical=False, through='Relationship', related_name='followees', through_fields=('to_user', 'from_user'), ) @property def followers(self): follower_relationship = self.relationship_to_user.filter(relationship_type=Relationship.RELATIONSHIP_TYPE_FOLLOWING) follower_list = follower_relationship.values_list('from_user', flat=True) followers = User.objects.filter(pk__in=follower_list) return followers @property def followees(self): followee_relationship = self.relationship_from_user.filter(relationship_type=Relationship.RELATIONSHIP_TYPE_FOLLOWING) followee_list = followee_relationship.values_list('to_user', flat=True) followees = User.objects.filter(pk__in=followee_list) return followees def follow(self, to_user): self.relationship_from_user.create( to_user = to_user, relationship_type='f' ) def __str__(self): return self.username # Relationships class class Relationship(models.Model): RELATIONSHIP_TYPE_FOLLOWING = 'f' RELATIONSHIP_TYPE_BLOCKED = 'b' CHOICE_TYPE = ( (RELATIONSHIP_TYPE_FOLLOWING, '팔로잉'), (RELATIONSHIP_TYPE_BLOCKED, '차단'), ) from_user = models.ForeignKey( User, related_name='relationship_from_user', on_delete=models.CASCADE, ) to_user = models.ForeignKey( User, related_name='relationship_to_user', on_delete=models.CASCADE, ) relationship_type=models.CharField(max_length=1, choices=CHOICE_TYPE) def __str__(self): return f"{self.from_user} follows {self.to_user}, type={self.relationship_type}" And in the python manage.py shell, I did the following: >>> user1 = User.objects.get(id=1) # user1@gmail.com >>> user2 = User.objects.get(id=2) # user2@gmail.com >>> user3 = User.objects.get(id=3) # user3@gmail.com >>> user1.follow(user2) >>> user1.follow(user3) >>> user1.followees <QuerySet [<User: user2@gmail.com>, <User: user3@gmail.com>]> Now my main question is related to the user1.followees. I want to delete <User: … -
Using django Authentication form with the html form
I am trying to build a login module in django. I already have a nice HTML form for login which has username and password field. But in my views.py I have imported default Django AuthenticationForm, but if integrate it with my nice-looking HTML form, there will be two forms. How can I import the Authentication form and use it with the mt HTML form?? My code is here: My view: def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() authlog(request, user) return redirect('home') else: messages.error(request, 'Invalid username or password') # back_page = request.META.get('HTTP_REFERER') return redirect('login') # return HttpResponse(back_page) else: content = { 'form': AuthenticationForm() } return render(request, 'sign-in.html', content) If I use Django default form, the code will be following, but it won't look good as my other Html login page. My sign-in html: <hr> <form action="" method="post"> {% csrf_token %} {{form|crispy}} <button type="submit" class=" btn btn-success ">Sign-Up</button> </form> I haven't posted my other HTML form though as it is very large. Hope it explains. -
How to use a C++ UDF in MySql with Django cursor?
I have a Django project where I am using MySQL. I want to use a C function for a particular kind of filter. I read up about using C function in MySQL but I could get nowhere how to use it with a cursor in Django. I tried using cur.execute('CREATE FUNCTION udf RETURNS STRING SONAME "udf_example.so";'), but that did not work. This is my views.py def testSearch(subject, year=0, department="", paper_type="", keywords=""): year_filter = "AND p.year = {}".format(year) if year > 0 else "" dep_filter = "AND d.code = '{}'".format(department)\ if department != "" else "" type_filter = "AND p.paper_type = '{}'".format(paper_type)\ if paper_type != "" else "" keyword_filter = "AND kt.text IN {}".format(keywords)\ if keywords != "" else "" if subject == "": return [] if keyword_filter == "": query =\ """ SELECT p.subject, p.year, d.code, p.paper_type, p.link, p.id FROM papers p JOIN departments d ON p.department_id = d.id WHERE bitap(p.subject, '{}') = 1 {} {} {} ORDER BY year DESC LIMIT 30; """.format(subject, year_filter, dep_filter, type_filter) else: query =\ """ SELECT p.subject, p.year, d.code, p.paper_type, p.link, p.id, GROUP_CONCAT(kt.text) AS keywords FROM papers AS p JOIN departments AS d ON p.department_id = d.id LEFT OUTER JOIN ( SELECT pk.paper_id, k.text … -
Whats problem with my code because my navbar is not looks like i want to
Help me with my navbar design and code is below <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <body> <nav class = "navbar navbar-expand-lg navbar-light bg-light"> <div class = "container"> <ul class = "navbar-nav"> <li class="nav-item"> <a class = "navbar-brand" href="{% url 'index' %}">Django </a> </li> <li class="nav-item"> <a class = "navbar-link" href="{% url 'admin:index' %}"> Admin </a> </li> <li class="nav-item"> <a class = "navbar-link" href="{% url 'basic_app:register' %}"> Register </a> </li> </ul> </div> </nav> <div class="container"> {% block body_block %} {% endblock %} </div> </body> </html>[![enter image description here][1]][1] I have attacted the screenshot of my webpage also. Whats problem with my code because my navbar is not looks like i want to -
Django-channels : ChatConsumer is sending message to only one user instead of sending it to both users
I am implementing a chat application in django and angular using django-channels and redis. The sockets get connected and work properly but the problem I am facing is that when two users are online and connect the same chatroom with the same thread url it connects but the messages sent by any user are only sent to the user that connected the socket recently and they are sent twice to only that user. In django I did the following configurations: settings/base.py .... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'channels', 'chats' ] ASGI_APPLICATION = "influnite.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], # "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, }, } .... routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from chats.consumers import ChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^messages/(?P<thread_id>[\w.+]+)/", ChatConsumer()) ] ) ) ) }) I created three models namely Thread, ThreadMember & ChatMessage. chats/models.py from django.db import models from django.db.models import Q from django.utils import timezone from django.contrib.auth.models import User from base.models import BaseModel # Create your models here. MESSAGE_TYPE = [ ('text', 'Text'), ('audio', 'Audio'), ('img', 'Image'), ('doc', … -
Django Rest framework list object has no attribute lower when specifying date format in settings
I want to format date fields to d/m/y format. However when I use the below code in the settings file I get the following error: 'list' object has no attribute 'lower' when performing the get request to fetch the data. My model field looks like this: licence_expiry_date = models.DateField() https://www.django-rest-framework.org/api-guide/settings/#date-and-time-formatting REST_FRAMEWORK = { "DATE_FORMAT": ["%d/%m/%Y"], } -
XMLHttpRequest doesn't send the data
I'm making a POST request from my react component to django-backend. My request goes to my server but I can't take the data I sent. The thing is I can log the status with onload on browser and I get 200 and I do get a POSTrequest in django so there is no problem with making a POSTrequest, the problem is sending data. send seems the problem here. My react component: import React, { useEffect, useState } from "react"; import { BiMeteor } from "react-icons/bi"; import { registerUser } from "../lookup"; export function RegisterComponent() { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function registerUser(e) { e.preventDefault(); const url = "http://localhost:8000/register"; const method = "POST"; /* const data = JSON.stringify({ username, password }) */ const xhr = new XMLHttpRequest(); const csrftoken = getCookie("csrftoken"); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", csrftoken); … -
drf CustomUser matching query does not exist
i'm working on mobile app with customuser. i'm trying to send otp on mail while creating user and set is_verify to false and after that user verify with otp then is_verify will set to true but if user does't verify otp add closes app then again while signup we're adding check if user exist and is_verified to true then return already exist otherwise create user and send otp again. so i'm getting error on if user doesnotexist then its showing this error: users.models.CustomUser.DoesNotExist: CustomUser matching query does not exist. and its getting this error from except customuser.doesnotexist block models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_("last name"), max_length=50) email = models.EmailField(_('email address'), unique=True) mobile_number = models.CharField( _('mobile number'), max_length=12, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) user_type = models.IntegerField(_("user_type")) otp = models.CharField(_("otp"), max_length=10, default="0") is_verified = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'users'), (2, 'courier'), (3, 'admin'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserMananager() def __str__(self): return self.email seralizers.py: class CustomUserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(required=False) password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile') def … -
How to store form data as draft in django
I'm working on a project that requires to store form data as a draft if the user closes the browser or leave the tab or any other case. and when the user opens the same form next time the user can see the previously entered data -
The requested resource was not found on this server. React + Django
I'm deploying my first Django + React app do a Droplet with Apache2. I've deployed some Django apps but this is my first time deploying a React app not to mention a React and Django app. When I visit the homepage I get The requested resource was not found on this server. and when I visit /admin I get the login page but without any styles. I notice in my dev tools I see 404 in the network tab. settings.py import environ ROOT_DIR = ( environ.Path(__file__) - 3 ) REACT_APP_DIR = ROOT_DIR.path("react_frontend") STATICFILES_DIRS = [ os.path.join(str(REACT_APP_DIR.path("build")), 'static'), ] STATIC_ROOT = '/srv/react-django-portfolio/react_frontend/build/static' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ str(REACT_APP_DIR.path("build")), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] sites-available/portfolio.conf <VirtualHost *:443> ServerName example.com DocumentRoot /srv/react-django-portfolio/django_backend/django_backend SSLEngine on SSLCertificateFile /etc/ssl/example.crt SSLCertificateKeyFile /etc/ssl/example.key SSLCertificateChainFile /etc/ssl/example.ca-bundle ErrorLog ${APACHE_LOG_DIR}/portfolio-error.log CustomLog ${APACHE_LOG_DIR}/portfolio-access.log combined WSGIDaemonProcess portfolio processes=2 threads=25 python-path=/srv/react-django-portfolio/django_backend WSGIProcessGroup portfolio WSGIScriptAlias / /srv/react-django-portfolio/django_backend/django_backend/wsgi.py Alias /robots.txt /srv/portfolio/static/robots.txt Alias /favicon.ico /srv/portfolio/static/favicon.ico Alias /static/ /srv/django-react-portfolio/react_frontend Alias /media/ /srv/portfolio/media/ <Directory /srv/react-django-portfolio/django_backend/django_backend> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /srv/react-django-portfolio/react_frontend/build/static> Require all granted </Directory> <Directory /srv/reat-django-portfolio/django_backend/media> Require all granted </Directory> </VirtualHost> -
Django Multitenant Single Login. after logged in it should be redirect to sub-domain
I want to know how to access a Django multitenant user in a single login(my-domain.com/login). After logging in it should be redirected to a specific tenant subdomain(tenant1.my-domain.com). Please give me a solution to that. -
How to use group by and get every record in each group?
I want to summarize all attendance records of each person every day,in my current solution, i need to get all records then use for loop, is there a better way to get the queryset like the following: class AttendanceRecord(models.Model): f_UserInfo = models.ForeignKey(to=UserInfo, on_delete=models.CASCADE) f_Device = models.ForeignKey(to=Device, on_delete=models.CASCADE) f_time = models.DateTimeField(auto_created=True) # How to group record by user and get a queryset like the following? [ {user_id1: [ {'f_Device_id': 1, 'f_time': '2020-11-11 8:00:00'}, {'f_Device_id': 1, 'f_time': '2020-11-11 18:00:00'} ]}, {user_id2: [ {'f_Device_id': 2, 'f_time': '2020-11-11 8:00:00'}, {'f_Device_id': 2, 'f_time': '2020-11-11 18:00:00'} ]}, ] -
Python Datetime Showing one day ahead date
I encountered one weird issue. I have one Django project, which uses (America/Denver) timezone by default. I got a couple of records into the database. id name date_create 1 foo Dec. 8, 2020, 6:15 p.m. 2 bar Dec. 1, 2020, 8:28 p.m. When I print the above record, it behaves weirdly. >>> print(record_one.date_create.date()) >>> Dec. 9, 2020 >>> print(record_one.date_create) >>> Dec. 8, 2020, 6:15 p.m. >>> print(record_two.date_create.date()) >>> Dec. 2, 2020 >>> print(record_one.date_create) >>> Dec. 1, 2020, 8:28 p.m. I am using python 3.5 and Django2 Django setting LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Denver' USE_I18N = True USE_L10N = True USE_TZ = True -
django with dynamic country state and city selection field in template
I want a country, state, and city selection field in my HTML. I want to use Django forms for dynamically changing state list if I change the country. and also require Django form validation. for example how can I achieve this with Django forms and models? -
django.core.exceptions.ImproperlyConfigured: The included URLconf does not appear to have any patterns in it
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'basic_app.urls' from 'C:\Users\shree\learning_users\basic_app\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. code in basic_app.url from django.urls import path from basic_app import views app_name = 'basic_app' url_patterns = [ path('register', views.register, name='register'), ] code in learning_users.url from django.contrib import admin from django.urls import path,include from basic_app import views # from django.conf.urls import url,include urlpatterns = [ path('',views.index,name='index'), path('admin/', admin.site.urls), path('basic_app/',include('basic_app.urls')), ] -
gunicorn: command not found in django app configured for docker and azure
I'm trying to deploy a pretty simple dockerized Django app to Azure. I was successfully able to push the containerized repository to Azure. When I run docker run <myloginserver>/myappname:v1, per instructions here: https://docs.microsoft.com/en-us/azure/container-registry/container-registry-get-started-azure-cli I get two errors: /usr/local/bin/init.sh: line 2: -e: command not found /usr/local/bin/init.sh: line 6: gunicorn: command not found gunicorn is installed in both my pipfile and my requirements.txt, and comes up as a satisfied requirement when I try to reinstall. How should I approach this?