Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do I fail Django migration in heroku server while succeeding in local server?
So I have deployed my Django project to Heroku, and now trying to migrate the database. I have everything working fine in my local sever. Then I tried to run the commands in heroku, as below. python manage.py makemigrations This worked fine. Migrations for 'app_name': contents\migrations\0001_initial.py - Create model Book - Create model Category - Create model Content Then of course, I tried : git add .git commit -m "migration" git push heroku master heroku run python manage.py migrate app_name But then I got this error CommandError: App 'app_name' does not have migrations. Strange thing is, after running python manage.py migrate, everything works fine in my local server. It's only the heroku server where the error occurs. I've done some research for possible issues, none of which were relevant to mine. For example I do have init.py in the migrations folder inside app_name directory. Also, I've tried heroku run python manage.py migrate as well as heroku run python manage.py migrate app_name but neither worked. I'm very confused. What do you think is the problem? Thanks in advance. :) -
I try to deploy my website in Django+Supervisor+NGINX on Ubuntu server 16.04
Here is my conf (supervisor): error massage FATAL Exited too quickly (process log may have details) ''' [program:gunicorn] directory=/home/ubuntu/allenon command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/allenon/app.sock AL-allenon.allenonproject.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn ''' -
How to show model data in django template?
I am working on project and i have a problem with it.The problem is that django is not showing model data in template and i an unable to solve problem. Here is the models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class videopost(models.Model): sno=models.AutoField(primary_key=True slug=models.CharField(max_length=130) title=models.CharField(max_length=255) image = models.ImageField(upload_to='staticfiles/images/') content=models.TextField() timeStamp=models.DateTimeField(blank=True) def__str__(self): return self.title Here is views.py def videoposts(request,slug): post=videopost.objects.filter(slug=slug).first() context={'post':post} return render(request,'videos/videopost.html',context) And here is template {% extends 'base.html' %} {% load static %} {% load embed_video_tags %} {% block title %}How to run python in mobile?{% endblock title %} {% block basecss%}"{% static '/css/home.css' %}" {% endblock basecss %} {% block extracss %}"{% static '/css/videos.css' %}" {% endblock extracss %} {% block classvideos%} current {% endblock classvideos %} {% block body %} {{post.content}} {{post.title}} {% endblock body %} -
unable to connect MongoDB with Django using PyMongo
Below issue is I'm facing while connecting the mongodb. Can someone help me out please Thanks Error============================ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'pymongo' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ======================================= Settings.py DATABASES = { 'default': { 'ENGINE': 'pymongo', 'NAME': 'workflow', 'HOST': 'localhost:27017/workflow', } } Views.py def dbconnection(): try: global _connection if _connection is None: client = MongoClient('mongodb://localhost:27017/', connect= False) db = client["workflow"] return db except Exception as ex: print(e , 'Exception') -
Django REST Framework: Updating via UpdateAPIView vs RetrieveUpdateDestroyAPIView / Prefilled Form in Browsable API
When I try to update a model instance via the generics.RetrieveUpdateDestroyAPIView I can see the instance's values prefilled in the form in the browsable API. However, when I use generics.UpdateAPIView I can't. Is this due to the fact that UpdateAPIView does not allow GET methods, so the view can't get the data to prefill the form or is there a special setting I need to add in my generics.UpdateAPIView to have the form prefilled automatically -
Related Field got invalid lookup while making a model relationship
I am trying to make relationships traversing through different models but am getting this error : django.core.exceptions.FieldError: Related Field got invalid lookup: occupational_group below are the models I have : class LoanApplication(models.Model, TimeStampedModel): loan_taker = models.ForeignKey( CustomerProfile, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Customer Profile'), related_name='loan_entries') class CustomerProfile(models.Model, TimeStampedModel): is_copy_component = models.BooleanField( _('Is copy component'), default=False) cooperation_partner = models.ForeignKey( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('Jurisdiction'), related_name='partner_user_profile') user = models.OneToOneField( EmailUser, on_delete=models.PROTECT, null=True, blank=True, verbose_name=_('User'), related_name='user_profile') approval_inquiry_sent_at = models.DateTimeField( _('Approval inquiry sent at'), null=True, blank=True) email_content_customer = models.FileField( _('Content of the customer email'), upload_to="customer-emails/", blank=True) approved_at = models.DateTimeField( _('Approved at'), null=True, blank=True) class CustomerProfilePerson(models.Model, TimeStampedModel): person = models.ForeignKey( Person, on_delete=models.CASCADE, verbose_name=_('Person'), related_name='customer_profile_relation') customer_profile = models.ForeignKey( CustomerProfile, on_delete=models.CASCADE, verbose_name=_('Customer Profile'), related_name='persons') class Person(models.Model, TimeStampedModel): occupational_group = models.CharField( _('Occupational group'), max_length=16, blank=True, choices=OCCUPATIONAL_GROUP_CHOICES) Am trying to filter the LoanApplication model with the relationship of an occupation group, below is the list of the occupational group : OCCUPATIONAL_GROUP_CHOICES = ( ('pharmacist', _('Pharmacist')), ('architect', _('Architect')), ('doctor', _('Doctor')), ('consulting_eng', _('Consulting engineer')), ('notary', _('Notary')), ('psychotherapist', _('Psychotherapist')), ('lawyer', _('Lawyer')), ('tax_consultant', _('Tax Consultant')), ('vet', _('Vet')), ('sworn_auditor', _('Sworn auditor')), ('surveyor', _('Surveyor')), ('auditor', _('Auditor')), ('dentist', _('Dentist')), ('other', _('Other')), ) So this is my query below but failing : LoanApplication.objects.filter(loan_taker__persons_person_occupational_group__in: ['pharmacist']) Am getting this exception : … -
Deploying Django on IIS and ngrok
I am trying to deploy Django on local host and "tunnel" using ngrok. The ngrok works but the IIS (Internet Information Manager) gives 500 Error <handler> scriptProcessor could not be found in <fastCGI> application configuration. Reference into fastcgi shows that this feature is deprecated but what is the replacement for serving Django using local server and ngrok. I also pip installed pyngrok. Can you suggest a clear solution? -
Send API data from Backend to Frontend in real time with Django and React
I am working and I need your help. I am working on a website with Django with DRF on the backend and react on the frontend. I need a way of sending api data to the client whenever any changes are made. The data is only coming from the database, the client is only viewing the progress. What options do I have to acheive. I need it to handle a large number on people. Say 20 000. Please your help will do a lot for me. -
Password is not saving to data base after hashing
I am creating user registration api in django_rest_framework. I created a serializer and class view. but there is some problem with password. I use Registration class which inherits CreateAPIView to create user-registration and user a ModelSerializer to serialize it. Before saving the data, I validate email and passwords. Then I hashed the password with user.set_password(password) then saved it. when I try to register with the api it shows following error Error :- File "/home/rasheed/PycharmProjects/DRFtutor/myappclass/views.py", line 72, in post user = serializer.save() File "/home/rasheed/PycharmProjects/DRFtutor/myapp/serializers.py", line 36, in save user.set_password(password) File "/home/rasheed/PycharmProjects/env/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 99, in set_password self.password = make_password(raw_password) File "/home/rasheed/PycharmProjects/env/lib/python3.8/site-packages/django/contrib/auth/hashers.py", line 77, in make_password raise TypeError( TypeError: Password must be a string or bytes, got tuple. My serializers.py is :- class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password', 'password2'] extra_kwargs = {'password': {'write_only': True}} def save(self): user = User( username=self.validated_data['username'], first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'], ) password = self.validated_data['password'], password2 = self.validated_data['password2'], email = self.validated_data['email'], if password != password2: raise serializers.ValidationError({'password': 'Passwords dose not match.'}) elif User.objects.filter(email=email).exists(): raise serializers.ValidationError({'email': 'Email is already in use.'}) user.set_password(password) user.save() return user views.py is:- class Registration(CreateAPIView): queryset = User.objects.all() serializer_class = RegistrationSerializer def post(self, request, *args, **kwargs): … -
AttributeError: 'tuple' object has no attribute 'fetchall' in django
While join multiple sql query getting error -
Django - updating user account breaks the user password
I'm trying to set up an account update form, where a user can update its info but only when he/she provides its password at the end of the form. Unfortunately, when I try to update it (even with a correct password), I get logged off and I cannot log back in. I don't know why, but the password breaks completely and I have to reset it via shell. Also, when I look into the database, the password for each user that I tried to update, it's not hashed anymore, it's just in plain text. forms.py class UserProfileForm(forms.ModelForm): username = forms.CharField(label="Username", min_length=4, max_length=50, help_text="Required") email = forms.EmailField( label="Email", max_length=100, help_text="Required", error_messages={"required": "Sorry, you will need an email"}, ) password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = UserAccount fields = [ 'username', 'email', 'first_name', 'last_name', 'about', 'password' ] def __init__(self,*args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields["username"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-username' } ) self.fields["email"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-email' } ) self.fields["first_name"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-first_name' } ) self.fields["last_name"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-last_name' } ) self.fields["about"].widget.attrs.update( { "class": "card bg-dark text-light form-control mb-3", "id": 'profile-about' … -
Django Resize Search Pane
I use to Django using this code forms.py from django import forms class PostSearchForm(forms.Form): search_word = forms.CharField(label='search', widget=forms.TextInput(attrs={'size': '80'})) views.py from django.views.generic import FormView class SearchDetailView(FormView): form_class = PostSearchForm template_name = 'search.html' search.html <form action="." method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-primary btn-sm"> </form> When I run this code, the size of the search bar is only horizontally longer. I want to make it bigger vertically, so if you know how, please let me know. -
how to make a char field behave like URLField in django
I am using Django and I want a field for URLs I know there is a URLField in Django but I want that field to be a charfield and I don't want users to submit anything other than URL in that charfield take a look at my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=500, blank=True, null=True) social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) Please answer how can I make a char field behave like a URL field -
Add more than 1 folder (network path) to static files with Django on IIS
I have a django website deployed on an IIS Server. in it, I have 2 different network paths I need to access via static STATICFILES_DIRS = [ "//server1/Shared1/folder/", "//Server2/folder2/", ] Now, currently my IIS has a static virtual directory that is set to "server1" this allows me to work with all the files I have in that shared network drive and opertate properly. The issue comes when I try to work with any files in the "server2" I don't know how to add it. I understand that exists something called "static root" but for that I need to do a "collect static" in this case, I can't do a collect static since both servers have over 60gb of data that I need to access. Is there a way I'm not seeing for adding this second server to be able to be used via IIS? -
How to apply multiple filters in a Django query without knowing if some filters are null or not
Let's say we have the following filters: filter1 = request.GET.get("blabla") filter2 = request.GET.get("blabla") filter3 = request.GET.get("blabla") filter4 = request.GET.get("blabla") filter5 = request.GET.get("blabla") filter6 = request.GET.get("blabla") Let's say we have the following query: user_projects = Project.objects.filter(element1=filter1, element2=filter2, element3=filter3, element4=filter4, element5=filter5, element6=filter6).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable") Some of the filters might be of type None (depends on the request) I would like to create a dynamic query that based on whether the filter exists or not, executes the query only with the non-null filters. Let's say for example filters 1, 2, and 3 have values, but filters 4, 5, and 6 are empty/null/None. Expected query: user_projects = Project.objects.filter(element1=filter1, element2=filter2, element3=filter3).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable") What I've tried: if filter1 is None or filter1.strip() == "": filter1 = "" elif is_valid_queryparam(filter1): user_projects = Project.objects.filter(element1=filter1).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable") And it works, but only for one filter, if I want that for 6 or N filters, it's extremely inefficient to execute multiple queries. Is it possible to achieve the desired result with a simple query? -
objects instances returning none using django bulk_create()
I am trying to bulk insert data into the database but upon appending these instances i find they are none model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' my view for skill_nme, skill_lvl in zip(skill_name, skill_level): skill_set = Skillset.objects.get(skill_name=skill_nme) seeker_skll.append(Seekerskillset( skill_set=skill_set, skill_level=skill_lvl, seeker=user)) print(seeker_skll) seeker_bulk = Seekerskillset.objects.bulk_create(seeker_skll) print('after insertion',seeker_bulk) return redirect('/users/dashboard') trace <class 'seekerbuilder.models.SeekerProfile'> [<Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>] after insertion [<Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>, <Seekerskillset: Seekerskillset object (None)>] [19/Jul/2021 14:27:12] "POST /users/app_det/ HTTP/1.1" 302 0 [19/Jul/2021 14:27:12] "GET /users/dashboard HTTP/1.1" 301 0 -
How to create and update user and User and custom model together in Django
Main Thing I want to register new user with User model and Custom user model data together. Problem Hello I'm a beginner it might be not a big deal at all and I may be overlooking it but I don't have any idea how can I do it. I'm using react in the fronted. can you please help me. Here is my code. Custom User Model class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="users", blank=True) birthday = models.DateField(blank=True) gender = models.CharField(max_length=100, choices=Gender_Choices, blank=True) User Serializer class UserSerializer(serializers.ModelSerializer): user_profile = ProfileSerializer(source='profile') class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'user_profile') Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user Register API 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] }) Frontend // Register User export const register = ({ username, password, email }) => dispatch => { // Headers const config = { headers: { 'Content-Type': 'application/json' } } // Request Body const body = JSON.stringify({username, email, password}) … -
ImportError: no module named typing on Mac OS X
Traceback (most recent call last): File "/usr/local/bin/pip", line 11, in load_entry_point('pip==21.1.3', 'console_scripts', 'pip')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 489, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2843, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2434, in load return self.resolve() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2440, in resolve module = import(self.module_name, fromlist=['name'], level=0) File "/Library/Python/2.7/site-packages/pip-21.1.3-py2.7.egg/pip/init.py", line 1, in from typing import List, Optional ImportError: No module named typing -
GeoDjango: How to create a geometry object from a bounding box?
I am intercepting a query parameter of bounding box ex. ?bbox=160.6,-55.95,-170,-25.89 in my GeoDjango application to filter my queryset of entries that intersects with the bbox. I want to know if how can I create an geometry object from the bbox or a list of the bbox object [160.6,-55.95,-170,-25.89]. bbox = GEOSGeometry('BBOX [160.6,-55.95,-170,-25.89]') -
Django CBV form submission returned JSON is displayed as a new page
I am using Django 3.2 I am creating a simple newsletter subscription form. The form submission returns JSON to the frontend, which should then be used to update parts of the page - however, when I post the form, the JSON string is displayed as text on a new page. Here is my class based view: class BlogsubscriberCreateView(CreateView): model = BlogPostSubscriber form_class = BlogSubscriptionForm http_method_names = ['post'] def post(self, request, *args, **kwargs): form = self.form_class(request.POST) content_type = "application/json" if not form.is_valid(): return JsonResponse({'ok': 0, 'msg': form.errors.get('email')[0]}, content_type=content_type, status=200) else: email = form.cleaned_data.get("email") subscriber = BlogPostSubscriber(email= email) subscriber.save() # send email to confirm opt-in email_message='Please confirm your subscription' message = f"A confirmation email has been sent to {email}. Please confirm within 7 days" return JsonResponse({'ok': 1, 'msg': message}, content_type=content_type, status=200) Here is a snippet of the HTML containing the form: <div class="col-lg-8 content"> <form id="blog-subscription"> {% csrf_token %} <br /> <h3>Some title</h3> <br /> <p>Lorem ipsum ...</p> <br /> <h4 id='submit-response-h4'>SUBSCRIBE TO OUR BLOG</h4> <div id="submit-response" class="input-group"> <span id="email-error"></span> <input type="email" id="blog-subscription-email" name="email" class="form-control" placeholder="Enter your email" required="true"> <span class="input-group-btn"> <button id="subscribe-btn" class="btn" type="submit">Subscribe Now</button> </span> </div> </form> Here is the Javascript that is responsible for updating the page: $().ready(function() { … -
How do i set and use the id field in django model and template
I need to be able to access a self incrementing integer field for my model and use it in my template. Is there a way to do that? My code accepts complaints from users so for each complaint I need the id to increment from 0,1,2,3,4, and so on and then I need to access these in the template to be able to use it accordingly models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter … -
Why are django-q scheduled tasks delayed randomly?
I'm finding that django-q is not executing tasks I schedule on time. There can be delays of several seconds to almost a minute. I schedule a task like so: from django.utils import timezone from django_q.models import Schedule def schedule_auction_deadlines(self): now = timezone.now() if self.deadline: name = "end_phase_%d" % self.id Schedule.objects.filter(name=name).delete() if now < self.deadline: Schedule.objects.create(name=name, func="myapp.views.end_phase", args=str(self.id), next_run=self.deadline, schedule_type=Schedule.ONCE) And here is my configuration in the settings.py file: Q_CLUSTER = { 'name': 'myproj', 'label': 'Django Q', 'timeout': 30, 'catch_up': True, 'guard_cycle': 1, 'redis': os.environ.get('REDIS_URL', 'redis://localhost:6379'), } From the docs it seemed like guard_cycle might be relevant, but I've got it set at the minimum setting. What could be causing these delays? -
Why is Django Easy Thubnails maintaining image extension?
I think I'm doing something foolish to cause this issue but django-easy-thumbnails seems to be maintaining the loaded image's file format, so I'm not getting best advantage of compression. I have the following within settings.py THUMBNAIL_HIGH_RESOLUTION = True THUMBNAIL_QUALITY = 50 THUMBNAIL_DEFAULT_OPTIONS = { 'crop': True, 'upscale': True, 'progressive': True, } #THUMBNAIL_EXTENSION = 'jpg' #THUMBNAIL_PRESERVE_EXTENSIONS = None THUMBNAIL_PROCESSORS = ( 'easy_thumbnails.processors.colorspace', 'easy_thumbnails.processors.autocrop', 'filer.thumbnail_processors.scale_and_crop_with_subject_location', 'easy_thumbnails.processors.filters' ) THUMBNAIL_ALIASES = { '': { 'full_width_image': {'size': (2220, 0), 'upscale': False}, 'hero': {'size': (2220, 0), 'upscale': False}, 'content_width_image': {'size': (1520, 0), 'upscale': False}, 'awards_image': {'size': (50, 50)}, 'carousel_slide': {'size': (1600, 900)}, 'modal_carousel_slide': {'size': (1500, 700)}, 'tablet_modal_carousel_slide': {'size': (700, 325)}, 'mobile_modal_carousel_slide': {'size': (310, 142)}, 'testimonial_avatar': {'size': (160, 160)}, 'core_service_icon': {'size': (64, 64)}, 'cta_carousel': {'size': (688, 0)}, 'image_carousel': {'size': (524, 524)}, 'search_result': {'size': (340, 340)}, 'news_article': {'size': (700, 470)}, 'carousel_main': {'size': (1090, 720)}, 'carousel_thumbnail': {'size': (240, 160)}, 'dropzone_thumbnail': {'size': (240, 240)}, 'manager_thumbnail': {'size': (510, 510)}, 'staff_thumbnail': {'size': (510, 510)}, 'brand_icon' : {'size' : (120, 120)}, 'mobile_brand_icon' : {'size' : (240, 240)}, 'native_logo' : {'size' : (180, 90)}, 'monaco_pdf': {'size' : (340, 200), 'extension':'png'}, 'monaco_brand' :{'size': (50, 50), 'extension':'png'}, 'monaco_half_size': {'size' : (163, 95), 'extension':'png'}, 'your_services_card' : {'size': (78, 78)}, 'my_shortlist_card' : {'size': (500, 300)}, 'extra_service_icon' : {'size': … -
Offline Cache Web Application with Django
I have faced some problems with offline web application which used VueJS(frontend) and Django(Backend) with postgres database. Currently postgres database are installed on cloud while frontend and backend are on local computer, in order to avoid retrieve or update data every time from cloud, I have used cache in Django to store data temporary. But when internet connection is disconnected, cache suddenly stop working and show error on database disconnected. Are there any solution to add some offline service worker to avoid database connection error and allow cache to work both offline and online ? Thank you -
Creating separate Date/Time Field in Models.py when clicked on calender and if try to select a date it does select the value the field remain empty
The issue is that when open django admin panel It shows the calender and time options but when I select any options it does not fill up the field and also for the time field it shows invalid time. Here is my models.py class Appointment(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) phone_number=models.CharField(max_length=12,null=False) date=models.DateField(null=True,blank=True) time=models.TimeField(blank=True) here is my js and css linking in base.html <head> <link rel="stylesheet" href="{% static 'static\css\jquery-ui.css' %}"> <link rel="stylesheet" href="{% static 'css\jquery-ui-timepicker-addon.css' %}"> <link href="{% static 'css\jquery-ui.min.css' %}" rel="stylesheet"> <link href="{% static 'css\jquery-ui.structure.min.css' %}" rel="stylesheet"> <link href="{% static 'css\jquery-ui.theme.min.css' %}" rel="stylesheet"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css"> </head> <script src="{% static 'js\jquery-ui.js' %}" ></script> <script src="{% static 'static\js\jquery-ui-timepicker-addon.js' %}"></script> <script src="{% static 'js\jquery-3.6.0.min.js' %}"></script> <script src="{% static 'js\jquery-ui.js' %}"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script> <script> <script> $(document).ready(function(){ $("#id_date").datepicker({changeYear: true,changeMonth: true, dateFormat: 'yy-mm-dd'}); }) $(document).ready(function(){ $('#id_time').timepicker({scrollbar: true,maxTime: '4:00pm'}); }); </script> </script> Here is admin.py from django.contrib import admin from .models import Appointment admin.site.register(Appointment) forms.py <form class="appoinment-form" method="POST" action="#" > {{ form.as_p }} <a class="btn btn-main btn-round-full" href="appoinment.html" >Make Appoinment <i class="icofont-simple-right ml-2 "></i></a> </form> Here is the screenshot of calender but date not getting selected Need to find out the reason and solve it Help will be appreciated.