Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(-2147024891, 'Access is denied.', None, None)
I am developing a Django (v 3.2.6) application (Python 3.9.1.) which needs to write into an Excel file using pywin32.com. On the client side it works fine, but when I put in production using IIS (v 10) on a Windows 11 server, I get the error above. I have a routine that reads in a file input by the user and writes to the project directory: if request.method == 'POST': # Create a form instance and populate it with the file from the request (binding): form = Name1_uploadForm(request.POST, request.FILES) if form.is_valid(): # Create variable for uploaded file uploaded_excel_file = form.cleaned_data['excel_file'] # Write it to BASE_DIR with open(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name), 'wb+') as destination: for chunk in uploaded_excel_file.chunks(): destination.write(chunk) # Allow the write process to conclude time.sleep(12) # Close the file destination.close() # Call conversion function Name1_extraction(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name)) # redirect to a new URL: return HttpResponseRedirect(reverse('index') ) else: form = Name1_uploadForm() This calls another function (below) that should open that same file: def Name1_extraction(uploaded_excel_file): const = win32.constants # Need to run CoInitialize to use win32com.client pythoncom.CoInitialize() # Open Name1 excel with Win32com excelFile = win32.gencache.EnsureDispatch('Excel.Application') The complete error is the following: enter image description here enter image description here enter image description here … -
I want to deploy django app on AWS EC2 using docker container with nginx, gunicorn. 502 Gateway error is happening [closed]
I make a docker container for Django-app. I tested it on my local host, and everything is working fine. I want to implement it on the AWS Linux server(EC2). Docker-compose-up is running successfully, but a 502 gateway error happens. Last time i had the same issue, but there was no docker container and i find out the problem was in nginix config. I added user "mylinuxname"; and it was working. Now i don't know how to update that config file, because i'm using container and when i add user "mylinuxusername" it is not working. output : "it is not place where u can use user settings". Anyone can help me or give me any references.enter image description hereenter image description here[enter image description here](https://i.stack.imgur.com/6S9ow.png) -
(Django) Why my login only work for db table:auth_user can't work another table:myapp_user?
Sorry bad English! I have a login function in my project like: from django.contrib.auth.forms import AuthenticationForm from django.contrib import auth from django.http import HttpResponseRedirect from django.shortcuts import render def log_in(request): form = AuthenticationForm(request.POST) if request.method == "POST": form = AuthenticationForm(data=request.POST) username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(request,username=username,password=password) if user is not None and user.is_active: auth.login(request,user) return HttpResponseRedirect('/index') context = { 'form': form, } return render(request, 'login.html', context) This function can work for any accounts that save in database table:auth_user,but can't work for my define class User: from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class User(AbstractBaseUser): username = models.CharField(unique=True,max_length=20,default="") email = models.EmailField() date_of_birth = models.DateField() date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = AccountManager() USERNAME_FIELD = 'username' #類似主鍵的功用 REQUIRED_FIELDS = ['email','username'] #必填 def __str__(self): return self.email def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin If I use register page to create a new account data,it will save in table:function_user("function" is my app name),and if my login table:auth_user accounts it will jump to /index,this right,but when I login new register account,it not do anything , I really sure the username and password is already created in table:function_user. … -
Django slice variable in template
I am trying to cut a slice a list of images to split them over a few pages of a pdf I am generating. But im not sure what the syntax I need to use is. (or if there is a better way). {% for page in image_pages %} // range loop for number of pages (passed from view) <p style="page-break-before: always"></p> // new page break for each page <div class="img-wrapper"> {% for image in project_images|slice:"0:12" %} <div class="img-box" style="margin: 5px"> <img class="report-img" src="{{ base_url }}{{ image.path.url }}" /> </div> {% endfor %} </div> {% endfor %} What i want to do is adjust this line {% for image in project_images|slice:"0:12" %} To something like (to print 12 images from total image list sent) {% for image in project_images|slice:"page*12:page*12+12" %} -
Continuous deployment of django react project
I have a react app with django backend. Every time when I need to deploy the app I have to follow following steps - Git pull new django code Copy react build from local to aws Collect static files using python manage.py collectstatic I have to automate this process using bare minimum dependencies. What can be done in such case? Thanks in Advance. -
How to use AdminEmailHandler class to send mails to admins with celery task in django?
I'm trying to send a mails to admins with celery by overriding the current AdminEmailHandler class of django from django.utils.log import AdminEmailHandler from celery import shared_task class CeleryAdminEmailHanadler(AdminEmailHandler): @shared_task(bind=True) def celery_send(self,subject, message, *args, **kwargs): super().send_mail(subject, message, *args, **kwargs) def send_mail(self, subject, message, *args, **kwargs): self.celery_send.delay(subject, message, *args, **kwargs) whenever celery_send function run the super().send_mail function getting this error Error('super(type, obj): obj must be an instance or subtype of type') Traceback (most recent call last): File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "D:\cmms\core\utils\log.py", line 7, in celery_send super().send_mail(subject, message, *args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type I'm using this for logging purposes to send mail to admins on critical errors in the website with celery. -
How to get value by index in jinja2 list?
I am using plotly to make multiple graphs and django framework to present the graph to user. I am storing all the graphs in list, example: all_graphs=[graph1, graph2] I need to show only one graph at a time according to value selected in dropdown in HTML. I am using javascript and jinja2 element for the same. Below is my javascript code: ` function graphshow(s){ var id=Number(s[s.selectedIndex].id); var graph1 = {{ all_graphs.0 | safe}}; Plotly.plot('id_of_div_to_show_graph', graph1, {}); } ` The above code works perfectly but when i replace 0 in line 2 with 'id' which is the index value of graph to be shown the code doesn't work. The value stored in 'id' is correct i've already checked. -
Django using URL parameters in template
I need to redirect to another page with same url parameters so I don't understand how to use url parameters in current template to redirect. dborg.html: {% extends './frame.html' %} {% block content %} <a href="{% url 'create_user' {{orgtype}} {{deg}} %}">Создать нового пользователя</a> {% csrf_token %} {{form}} {% for i in o %} <p><a href='{% url "view_user" i.id %}'>{{i.fld}}</a></p> {% endfor %} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.main, name='main'), path('view_org/<str:orgtype>/<str:deg>', views.view_org_db, name='view_org'), path('token/<str:orgtype>/<str:deg>', views.get_token, name='token'), path('token/<str:orgtype>', views.get_token, name='token'), path('create/<str:orgtype>/<str:deg>', views.create_user, name='create_user'), path('search/', views.search_user, name='search_user'), path('report/', views.view_report, name='view_report'), path('view/<int:id>', views.view_user, name='view_user') ] -
How do I get a cloned Django project running?
When I do 'pip install -r requirements.txt', I get this message: python setup.py egg_info did not run successfully I tried python 'python3 -m pip install -U setuptools' but that didn't work. -
Django issue saving data to database
username is saving but information such as first_name, email and etc are not. `from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(required=True) first_name = serializers.CharField(max_length=50, required=True) last_name = serializers.CharField(max_length=50, required=True) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) is_admin = serializers.BooleanField(default=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2', 'is_admin') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user` i have searched online for hours, but have not managed to make much progress. if someone could elaborate on my issue and explain what I have done wrong that would be greatly appreciated -
Django - write Python code in an elegant way
I have a situation as shown below: in models.py: class singer(models.Model): name = models.CharField() nickName = models.CharField() numSongs= models.IntegerField() class writer(models.Model): name = models.CharField() numBooks = models.IntegerField() class weeklyTimeSinger(models.Model): singerID = models.ForeignKey(singer, on_delete = models.CASCADE, related_name = 'hook1') dayWeek = models.IntegerField() startHour = models.TimeField() stopHour = models.TimeField() class weeklyTimeWriter(models.Model): writerID = models.ForeignKey(writer, on_delete = models.CASCADE, related_name = 'hook2') dayWeek = models.IntegerField() startHour = models.TimeField() stopHour = models.TimeField() in view.py: class Filters(APIView): def queryFilter(self, querySet, request, singerOtWriter): param1 = int(request.GET.get('param1', 0)) param2 = int(request.GET.get('param2', 0)) if singerOtWriter == "singer": querySet = querySet.filter(weeklyTimeSinger_dayWeek=param1) querySet = querySet.filter(weeklyTimeSinger_startHour__lt=param2) querySet = querySet.update(..... ....a lot of operation on querySet else if singerOtWriter == "writer": querySet = querySet.filter(weeklyTimeWriter_dayWeek=param1) querySet = querySet.filter(weeklyTimeWriter_startHour__lt=param2) querySet = querySet.update(..... ....a lot of operation on querySet, the same of the case singer return querySet class Artist(Filters): def get(self, request): querySetSinger = singer.objects.all().annotate(numWorks= F('numSongs')) querySetSinger = self.queryFilter(querySetSinger , request, "singer") querySetSinger = querySetSinger.values('name', 'numWorks') querySetWriter = writer.objects.all().annotate(numWorks= F('numBooks')) querySetWriter = self.queryFilter(querySetWriter , request, "writer") querySetWriter = querySetWriter.values('name', 'numWorks') values = querySetSinger.union(querySetWriter) serialized = ArtistSerializers(values, many = True) return Response(serialized.data) In queryFilter function I have 2 different flows depending on singerOtWriter parameter. The 2 flows are long and identical execpt for "weeklyTimeWriter" or "weeklyTimeSinger" tables … -
Django complexity of one-to-one field reverse lookup
Reverse lookup of foreign key fields takes log(n) time as stated in this question. complexity of a reverse django foreign key lookup What is the complexity of reverse lookup of one-to-one field? -
Duplicate object with django-hitcount
I want to duplicate my current object with its values. So, I need to copy all of its old values to the new object. Duplication of all old values I implemented well, but I can't make hits (views) that are created with django-hitcount. I tried to do different options, but it doesn't work. Could you please give me advice on how to build it? models.py class Blog(models.Model, HitCountMixin): slug = models.SlugField() name = models.CharField() author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, blank=True, ) content = models.TextField(blank=True, null=True) bookmarkscount = models.IntegerField(null=True, blank=True, default=0) downloadscount = models.IntegerField(null=True, blank=True, default=0) hit_count_generic = GenericRelation( HitCount, object_id_field="object_pk", related_query_name="hit_count_generic_relation", ) hitcount.models.py from datetime import timedelta from django.db import models from django.conf import settings from django.db.models import F from django.utils import timezone from django.dispatch import receiver from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.utils.translation import gettext_lazy as _ from etc.toolbox import get_model_class_from_string AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') from .managers import HitCountManager, HitManager from .settings import MODEL_HITCOUNT from .signals import delete_hit_count @receiver(delete_hit_count) def delete_hit_count_handler(sender, instance, save_hitcount=False, **kwargs): """ Custom callback for the Hit.delete() method. Hit.delete(): removes the hit from the associated HitCount object. Hit.delete(save_hitcount=True): preserves the hit for the associated HitCount object. """ if not save_hitcount: instance.hitcount.decrease() … -
Missing 'path' argument in get() call
I am trying to test my views in Django, and when I run this i get the error from django.test import TestCase, Client from django.urls import reverse from foodsystem_app.models import discount,menu import json class TestViews(TestCase): def test_login_GET(self): client = Client response = client.get(reverse('login')) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response,'foodsystem/login.html') response = client.get(reverse('login')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Client.get() missing 1 required positional argument: 'path' ---------------------------------------------------------------------- Ran 4 tests in 0.005s FAILED (errors=1) I'm not sure what I am supposed to pass as the path name. This is the code for what I am testing def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("main:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) -
Getting (2006, 'MySQL server has gone away error) in kafka consumer in my django application
I recently written a kafka consumer in my django project which is running in the background and there's a mysql query which reads inside the consumer and the process is very light as I don't have that much of data. But I'm getting (2006, 'MySQL server has gone away) and I'm not getting why exactly it's happening and what's the solution for this? Any leads or solution for this would be highly appreciated. The below is my code:- `def job_listener(): listener = KafkaConsumer(topic, group_id=group_id, bootstrap_servers=settings.KAFKA_BOOTSTRAP_SERVERS, auto_offset_reset=settings.KAFKA_AUTO_OFFSET_RESET, enable_auto_commit=settings.KAFKA_ENABLE_AUTO_COMMIT) for message in listener: try: data = json.loads(message.value) logger.info("Data Received {}".format(data)) except Exception as e: data = None logger.error("Failed to parse the message with exception {}".format(e)) if data is not None: try: Job.objects.get(pk=data['id'] except ObjectDoesNotExist: logger.error("Keyword doesn't exist with data {}".format(data)) listener.commit({TopicPartition(topic, message.partition): OffsetAndMetadata(message.offset+1, '')}) except Exception as e: logger.error( "Failed to read data {} with exception {}".format(data, e)) listener.seek(TopicPartition(topic, message.partition), message.offset)` -
how to pass a context variable from a variable inside of an if statement?
Inside of an if statement I've check_order that I need to have as a context variable for my template, I'm getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without having to repeat the code to have it outside of the if statement? View if request.method == "POST": if request.user.is_authenticated: customer = request.user.customer check_order = OrderItem.objects.filter(order__customer=customer) if check_order: if form.is_valid(): #does logic else: messages.error(request, f"Failed") else: return redirect() context = {"check_order": check_order} -
Specific User permissions in Django
I need to make only TL and HR approve permissions for leave. how to achieve it in Django Rest framework? since am a newbie i find this scenario challenging. Help me out Techies This is my User model class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=150, unique=True) name = models.CharField(max_length=150, blank=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_HR = models.BooleanField(default=False) is_TL = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) This is my leave request model. class Leave(models.Model): leave_type = models.CharField(max_length=50) employee = models.ForeignKey(UserDetails, on_delete=models.CASCADE) manager = models.CharField(max_length=50) applied_on = DateTimeField(auto_now_add=True) from_date = DateField() to_date = DateField() number_of_days = IntegerField() purpose = models.CharField(max_length=100) status = models.CharField(max_length=50, choices=( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Rejected', 'Rejected') ),default='Pending') waiting_approval = models.BooleanField(default=True) TL_approved = models.BooleanField(default=False) TL_rejected = models.BooleanField(default=False) def approve(self): self.manager_approved = not self.manager_approved self.manager_rejected = not self.manager_rejected This is my views class LeaveManagerApproveView(APIView): def post(self, request): leave_id = request.data.get('leave_id') leave = Leave.objects.get(id=leave_id) leave.waiting_approval = False leave.manager_approved = True leave.status = 'Approved' leave.save() return Response({'successMessage': 'Leave Approved Successfully'}) In my views, i need only Hr or TL should approve or reject it? How to rock it? -
Django - Plesk - Centos7 - Apache
I have a rest-django project. The project uses plesk panel, centos 7 and apache. When I run my project, I get a python error. my site api.iyziwell.com print: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iyziwell.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() Please help me. -
Unable to load the custom template tags in django
templatetags : myapp_extras.py from django import template register = template.Library() @register.simple_tag def my_url(value,field_name,urlencode=None): url = '?{}={}'.format(field_name,value) if urlencode: querystring = urlencode.split('&') filtered_querystring = filter(lambda p:p.split('=')[0]!=field_name,querystring) encoded_querystring = '&'.join(filtered_querystring) url = '{}&{}'.format(url,encoded_querystring) return url home.html {% load myapp_extras %} . . . <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="{% my_url 1 'page' request.GET.urlencode%}">&laquo; first</a> <a href="{% my_url page_obj.previous_page_number 'page' request.GET.urlencode%}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{% my_url page_obj.next_page_number 'page' request.GET.urlencode%}">next</a> <a href="{% my_url page_obj.paginator.num_pages 'page' request.GET.urlencode%}">last &raquo;</a> {% endif %} </span> </div> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'facligoapp' ] views.py def do_paginator(get_records_by_date,request): paginator = Paginator(get_records_by_date,10) page_number = request.GET.get('page', 1) try: page_obj = paginator.get_page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) return page_obj : : if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) Based on the my templates tags when I filter the datas the url should change. But the url is not changing and template tags is not working. I had created the init.py in template tags also. Is there any solution to change the structure … -
Djagno User token is not passed in HTTP request header:-
I have created a login api using token based authentication in django rest framework.....API works fine in local setup.....But after committing the code on live server. Login done successfully but after passing that login token in headers. user is not permissible to open the next page. Here is my code:- 1) Login function @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): account = request.data.get("account") username = request.data.get("username") password = request.data.get("password") all_subs = [] for i in Subscriber.objects.all(): all_subs.append(i.username) if account in all_subs: connect_to_db(database=account) set_db_connection(account) try: if '@' in username: user = User.objects.using(account).get(email=username) else: user = User.objects.using(account).get(username=username) except: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if user.check_password(password): token, _ = Token.objects.using(account).get_or_create(user=user) user_data = User.objects.using(account).get(id=token.user_id) serializer = UserSerializer(user_data) return Response({'data': serializer.data,'token': token.key}, status=HTTP_200_OK) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) elif account == "enggforms": try: if '@' in username: user = User.objects.get(email=username) else: user = User.objects.get(username=username) except: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if user.check_password(password): token, _ = Token.objects.get_or_create(user=user) user_data = User.objects.get(id=token.user_id) serializer = UserSerializer(user_data) return Response({'data': serializer.data,'token': token.key}, status=HTTP_200_OK) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if username is None : return Response({'error': 'Please provide username'}, status=HTTP_400_BAD_REQUEST) elif password is None: return Response({'error': 'Please provide password'}, status=HTTP_400_BAD_REQUEST) elif account is None: return Response({'error': 'Please provide account name'}, status=HTTP_400_BAD_REQUEST) if … -
Django - AppRegistryNotReady("Models aren't loaded yet.") using cities_light library
I have installed the cities_light library in Django and populated the db with the cities as instructed in the docs. I added the app in INSTALLED_APPS and I have been able to pull the data in this simple view. All cities load as expected: def index(request): cities = City.objects.all() context = { 'cities': cities } return render(request,'templates/index.html',context) However, I am trying to create a model which has City as a foreign key, but when I run the app or try to make the migrations I get 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'. from cities_light.admin import City from django.db import models class Home(models.Model): location = models.ForeignKey(City, on_delete=models.CASCADE) I suspect I might need to override the model. Would that be the case? -
How to Display the data on webpage with a search option (search by valid resource number) and use below API details for data fetching
API Details: API Reference:* https://stat.ripe.net/docs/02.data-api/announced-prefixes.html* Method: GET Origin Url: https://stat.ripe.net/data/announced-prefixes/data.json?resource= Example URL: https://stat.ripe.net/data/announced- prefixes/data.json?resource=4007 Note: The bold value will be the user’s input from the search field. Data Output format in webpage: (https://i.stack.imgur.com/x7Qsk.png) Some valid resources number (ASN) are as below. 4007 17501 9238 141177 23752 By using python/django framework please help me. I have no knowledge about how to fetch data using API. -
Django session variable change in UI everytime when new request_id is created
I want to request id differ in every page data, same as request id is in available in approve_url . index function send session variable approve_url in test function. Here is index function global j, k, approve_url @api_view(['POST', 'GET']) def index(request): # j = '' # approve_url = '' if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): form.save() try: ids = form.cleaned_data['git_Id'] print(ids) obj = sql() query = f""" SELECT request_id FROM request_form_db.request_form_mymodel where git_Id= '{ids}' ; """ print(query) p = obj.fetch_query(query) print("Query Result", p) for i in p: print("Result[0] : ", i[0]) print("Result : ", p) i = i[0] j = i approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}" print("Url : ", approve_url) try: send_mail( 'KSA Test Activation', approve_url, 'Noreplygcontrol@airlinq.com', ['sorav.parmar@airlinq.com'], fail_silently=False, ) except Exception as e: print("Error : ", e) except Exception as e: print("Error : ", e) request.session['ids'] = ids request.session['approve_url'] = approve_url print('Request ID Sent : ', ids) print('Approve Url Sent : ', approve_url) form = InputForm() else: form = InputForm() return render(request, 'home.html', {'form': form}) Here is test function where approve_url getting from session variable and put into UI, but res value change in previous data as well.Its not same as request_id in approve_url. the latest request id … -
Django makemigrations in production?
I'm new to Django but one concern I'm running into is whether running makemigrations as part of the production deployment process is safe/deterministic? The main reason is some 3rd party apps will create new migrations beyond the pre-defined ones, i.e. hordak for example, when a new currency is added via CURRENCIES in settings.py. Since a currency can be added anytime later and these are part of an 3rd party app the migrations are not checked in to the repo. This requires makemigrations to be run on deploy? This seems dangerous since there will be untraceable changes to the DB? Is a way to explicitly check-in to the repo 3rd party migrations? -
Css static in html use django, css no show out
main.html add {% load static %} at top and {% static 'css/main.css' %} in link css href {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CM1</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" type="test/css" href="{% static 'css/main.css' %}"> </head> <body> {% include "accounts/navbar.html" %} {% block content %} {% endblock content %} <hr> <h5>Our footer</h5> </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </html> **setting.py code so longer, i just skip to important things, the STATICFILES_DIRS bracket is () or [] ** import os INSTALLED_APPS = [ ... 'django.contrib.staticfiles', #<-- already have ... ] STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), )