Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show JsignatureField as images in pdf for Django3
here i am using Python3 and Django3 i am unable to display the signatures in my pdf view here is my views.py where it shows how i am saving my signatures class GasSafetyRecordView(View): def get(self, request, job_id, form_id): client = request.user.client job = get_object_or_404(AddJob, id=job_id, client=client) safety_form = GasSafetyForm() ...... .... return render(request, 'crm/jobforms/gas_safety_record.html', { 'safety_form': safety_form,'client': client, .... .... }) def post(self, request, job_id, form_id): client = request.user.client safety_form = GasSafetyForm(request.POST) if safety_form.is_valid(): form_obj = safety_form.save(commit=False) form_obj.client = client form_obj.save() return render(request, 'crm/jobforms/gas_safety_record.html', { 'safety_form': safety_form, 'client': client, ..... .... }) here is my forms.py for saving the signatures class GasSafetyForm(forms.ModelForm): engineer_signature = SignatureField(required=False) class Meta: model = GasSafetyRecord fields = ('client','engineer_signature') here is my template gas_safety_record.html <div class="col-sm-6 col-xs-12 margT10"> {{safety_form.engineer_signature}} </div> Now i want to display this engineer_signature in my pdf here is my views.py for pdf view def render_to_pdf_gasrecordform_view(template_src, context_dict): template = get_template(template_src) # context = Context(context_dict) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') return response return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html)) def generate_gasrecordform_pdf_view(request,id,pk,serialnumber): client = request.user.client gasrecord = GasSafetyRecord.objects.filter(client_id=client,formjob_id=id,serial_number=serialnumber).values() return render_to_pdf_gasrecordform_view('crm/gas_record_pdf.html',{'gasrecord':gasrecord,'client':client}) Here is my gas_record_pdf.html for pdf <td> <img src="{{ gasrecord.0.engineer_signature }}"/> </td> … -
Why is my Python path configuration not changing in Apache
I am trying to setup Apache 2.4 on Windows to work with a Django project. As a first try, I made just a base application showing the "welcome-rocket" of Django. After configuring the httpd.conf file of Apache, the well knwon error ModuleNotFoundError: No module named 'encodings' appears. I tried out all suggestions from here. Sadly, none of the ideas had an effect. I ended up using the following line in the config file: LoadFile "C:/Python/Python37/python37.dll" LoadModule wsgi_module "D:/Projects/TestProject/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "D:/Projects/TestProject/venv/Scripts" WSGIPythonPath "D:/Projects/TestProject/venv/Lib;D:/Projects/TestProject/venv/Lib/site-packages;C:/Python/Python37/DLLs" WSGIScriptAlias / "D:/Projects/TestProject/venv/backend/backend/wsgi.py" During this process, I noticed that the python path configuration printed to the error.log file never changed, no matter which paths I used in the lines above. Here is a snippet from the log: Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.path = ['C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' … -
Django 'None-Type' AttributeError
I have the following model: class Customer(models.Model): GENDER = [ ('M', 'Male'), ('F', 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(auto_now=False, auto_now_add=False, null=True) avatar = models.ImageField(upload_to='customer/avatars/', blank=True, null=True) height = models.DecimalField(max_digits=5, decimal_places=2, null=True, default=0) weight = models.DecimalField(max_digits=5, decimal_places=2, null=True, default=0, help_text="Please input your weight in kg") medical_gender = models.CharField(max_length=1, choices=GENDER, default='F', blank=True, null=True) membership = models.BooleanField(default=True) def age(self): today = datetime.datetime.now() age = (today.year - int(self.dob.year)) - ((today.month, today.day) < (self.dob.month, self.dob.day)) return age On local, it works. Once I deployed I got: Exception Value: 'NoneType' object has no attribute 'year' Exception Location: /workspace/core/models.py, line 51, in age The error appears to be coming from the age method in the model. <span>Age: {{ request.user.customer.age }}</span> Any ideas on how to fix this, please? -
Why in django-import-export doesn't work use_bulk?
I use django-import-export, line-by-line import via import_data works without problems, but when I turn on the use_bulk=True option, it stops importing and does not throw any errors. Why does not it work? resources.py class ClientsResources(resources.ModelResource): class Meta: model = Clients fields = ('id', 'name', 'surname', 'age', 'is_active') batch_size = 1000 use_bulk = True raise_errors = True views.py def import_data(request): if request.method == 'POST': file_format = request.POST['file-format'] new_employees = request.FILES['importData'] clients_resource = ClientsResources() dataset = Dataset() imported_data = dataset.load(new_employees.read().decode('utf-8'), format=file_format) result = clients_resource.import_data(imported_data, dry_run=True, raise_errors=True) if not result.has_errors(): clients_resource.import_data(objs, dry_run=False) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) data.csv id,name,surname,age,is_active 7,OFBCXMW,RTQPEWU,35,Y 8,DMEYSYQ,TVKHQXP,80,Y 9,ZQBQLKI,ACRDHPQ,73,Y 10,CETXHMS,BQNYNSA,52,Y 11,GWHVHAO,FUJUQLO,41,Y -
Django CBV queryset issue
this is my model class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=256) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True, auto_now=False) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return f'{self.author} --> {self.title}' def get_absolute_url(self): return reverse('blog:post_detail', kwargs={'pk': self.pk}) def publish(self): self.published_date = timezone.now() self.save() def unpublish(self): self.published_date = None self.save() and i registered it on Django admin. i have created two post on Django admin, the new post when i publish it and hit now and refresh the page, it won't show this post: this is the view: As you can see result of query1, query2 is different with query3. I think this is a bug, if it's not please light me up. -
how to call a view function in django without refreshing page
this is my home page I am working on a web application where user searches for a product and i am fetching that product from amazon flipkart and rendering on my home page. All i want is to store the data in the database when the user clicks on "Get Alert" button for a specific product without refreshing the page Here is my model class where data is supposed to be stored: class product(models.Model): product_id=models.CharField(max_length=50,primary_key=True) product_name=models.CharField(max_length=50) link=models.URLField() curr_price=models.IntegerField() old_price=models.IntegerField() website=models.CharField(max_length=10) Here is the view function that is been called when user searches for a product def search(request): if request.method == "POST": webList=request.POST.getlist('websites') q=request.POST.get('search') view=request.POST.get('view') if(q=="" or len(webList)==0): if request.user.is_authenticated: return render(request,'userLogin/userDashboard.html',{'error':True,'search':q,'weblist':webList,'userName':request.user}) else: return render(request,'home/searchProduct.html',{'error':True,'search':q,'weblist':webList}) AllWebProductList=[] FlipkartList=[] AmazonList=[] shopcluesList=[] snapdealList=[] MyntraList=[] if 'flipkart' in webList: FlipkartList=getInfoFromFlipkart(q) AllWebProductList.append(FlipkartList) #return render(request,'home/searchProduct.html',{'lists':productObj}) if 'amazon' in webList: AmazonList=getInfoFormAmazon(q) # Scrapping # AmazonList=getInfoAmazon(q) #PAPI AllWebProductList.append(AmazonList) if 'shopclues' in webList: shopcluesList=getInfoFromShopClues(q) AllWebProductList.append(shopcluesList) if 'snapdeal' in webList: snapdealList=getInfoFromSnapDeal(q) print ("welcome in snapdeal") if 'ajio' in webList: ajioList=getInfoFromAjio(q) if 'myntra' in webList: MyntraList=getInfoFromMyntra(q) AllWebProductList.append(MyntraList) print(" welcome in myntra") #sorting(AllWebProductList) mergeList=FlipkartList+AmazonList+shopcluesList # sorting(mergeList,asc) print(request.user.is_authenticated) if request.user.is_authenticated : return render(request,'userLogin/userDashboard.html',{'lists':mergeList,'val':view,'search':q,'weblist':webList,'userName':request.user}) else: return render(request,'home/searchProduct.html',{'lists':mergeList,'val':view,'search':q,'weblist':webList}) #messages.warning(request,name) return render(request,'home/searchProduct.html') Once this view is called we get the above page showing all the products fetched … -
I am getting thsi module not found error for my app in django . Why though?
(belov_wed_venv) prateek@prateek:~/belov_wed/project_belov_wed$ python manage.py runserver ModuleNotFoundError: No module named ' belov_wed_app' -
In DRF how do I serialize a related model(OneToOne) and display the data not in a list data type but single value instance?
The code is given below with the present output and expected output. Please help if, Thank you. In the ProductPriceMapping table the ProductDetail table and PriceList is related with a OneToOne relation, but When the data for Price is fetched with related_name= argument there must be one value for one product, but the data is being displayed is List data type. ##models.py class PriceList(models.Model): priceCode = models.BigAutoField(primary_key= True) maxRetailPrice= models.FloatField(max_length=20) baseDiscount = models.FloatField(max_length=20, default=0) seasonalDiscount = models.FloatField(max_length=20, default=0) def __str__(self): return '%s'% (self.maxRetailPrice) class ProductDetail(models.Model): productCode = models.BigAutoField(primary_key=True) productName = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) def __str__(self): return self.productName class ProductPriceMapping(models.Model): productPriceCode= models.BigAutoField(primary_key=True) productCode= models.ForeignKey(ProductDetail,on_delete=models.CASCADE,related_name='price') priceCode= models.OneToOneField(PriceList,on_delete=models.CASCADE) def __str__(self): return '%s' % (self.priceCode) ##serializers.py from .models import CategoryDetail, EmployeeDetail, ProductCategoryMapping, ProductPriceMapping, SalaryDetail, ProductDetail, PriceList class ProductPriceListSerializer(serializers.ModelSerializer): class Meta: model = PriceList fields = ('priceCode','maxRetailPrice', 'baseDiscount', 'seasonalDiscount') class ProductPriceMappingSerializer(serializers.ModelSerializer): class Meta: model= ProductPriceMapping fields= ('productPriceCode','productCode', 'priceCode') class ProductDetailsSerializer(serializers.ModelSerializer): category= serializers.StringRelatedField(many= True, read_only= True) price = serializers.StringRelatedField( many= True, read_only= True) class Meta: model = ProductDetail fields = ('productCode', 'productName', 'manufacturer','category', 'price') The API as it looks: [ { "productCode": 1, "productName": "NeoChef", "manufacturer": "LG", "category": [ "1: Microwave Oven" ], "price": [ "26000.0" ##expected the price value not be in a list … -
Can there be a DevStack for django? [closed]
Can someone create a devstack like https://localwp.com/ and https://kinsta.com/devkinsta/ it will attract a lot of developers, esp small and medium size startups to try django. -
How can i use django rest framework to create an API that is secured using api key
Am trying to create a RESTful API in django using django rest-framework and am unable to secure it with access key and.How do i go about it.please help -
502 bad gateway: Nginx, gunicorn, Django
Here is my nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; server { listen 80; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /myproject; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/root/myproject/myproject.sock; } } } This is my directory This is my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=nginx WorkingDirectory=/root/myproject/myproject ExecStart=/root/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target error.log 2022/04/13 12:45:30 [crit] 20474#20474: *8 connect() to unix:/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 10.81.234.10, server: 0.0.0.0, request: "GET / HTTP/1.1", upstream: "http://unix:/root/myproject/myproject.sock:/", host: "10.10.89.8" My gunicorn service is working properly Nginx.conf is also working properly with no errors All permissions have been granted to myproject directory Still I am getting a 502 Bad Gateway error. Please let me know if any additional information needed -
Django Models ManyToMany
I have two models Target and Location, each Target contains a Location: class Target(models.Model): uid = models.AutoField(primary_key=True) name = models.CharField(max_length=100) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True ) So, I created a default location and I added it to many targets, The problem is, when I update a location from one target, all target locations are updated. As if all the targets are referring to the same Location. I need to write a logic where each Target has its own Location -
I want to add custom countdown timer in my project where admin/teacher set time for exam,that time becomes input for timer
i tried creating timer in python but its not being as i wanted so i guess javascript is only going to help and im not very good in javascript do please help me to create a timer and page should close when timer runs out of time 'THIS IS : models.py' from django.db import models from student.models import Student class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() time_to_solve = models.IntegerField() required_marks_to_pass = models.IntegerField() def __str__(self): return self.course_name class Question(models.Model): course=models.ForeignKey(Course,on_delete=models.CASCADE) marks=models.PositiveIntegerField() question=models.CharField(max_length=600) option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) class Result(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE) exam = models.ForeignKey(Course,on_delete=models.CASCADE) marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now=True) 'THIS IS HTML TEMPLATE WHERE COUNTDOWN TIMER SHOULD APPEAR ' {% extends 'student/studentbase.html' %} {% block content %} {%load static%} {% block scripts %} <script src="{% static 'quiz.js' %}" defer></script> {% endblock scripts %} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> {% comment %} <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> {% endcomment %} <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <div class="jumbotron my-4"> <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/student/calculate-marks" method="POST"> {% csrf_token %} <h2 style="text-align: left;">Course: {{course.course_name}}</h2> <h2 style="text-align: right;">Countdown: </h2> {% comment %} <h2 id="timer-box" style="text-align: right;">Time: {{5:00}} min</h2> {% endcomment %} <h1 style="text-align: right;"><span id = "time">00:00</span></h1> {% for q in … -
NETWORK_ERROR apisauce
when i try to fetch data from my django server i got a NETWORK_ERROR corsheader in backend is work i just try localhost and my machine ip and notwork this is the result of console.log(response.originalError) Network Error at node_modules/apisauce/node_modules/axios/lib/core/createError.js:15:17 in createError at node_modules/apisauce/node_modules/axios/lib/adapters/xhr.js:96:22 in handleError at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit -
how to create login authentication based on some condition in django restframework
Hi Everyone current i am using default token base authentication, but now i need to some restriction on login time, i have One model called as Team where i assign one team name to multiple managers(users) i need to login only those users have team. also login based on username, password and get output token and team name., please help me out. models.py class Team(BaseModel): name = models.CharField(max_length=30) Logo=models.ImageField(upload_to=team_directory_path,null=True, blank=True) managers=models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) def __str__(self): return self.name -
How to use token base authentication in Django channels and testing on postman
By using Django channels I want to use token authentication and test on postman but I can't connect after using authentication.It's a notification app where user receive notification on websocket without refresh and without authentication It is working fine.. I have uploaded all the files .Please check it out I will be thankful to you. consumers.py from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from channels.generic.websocket import WebsocketConsumer from channels.auth import login from asgiref.sync import async_to_sync, sync_to_async import json from .models import * class OrderProgress(WebsocketConsumer): def connect(self): self.user = self.scope["user"] self.room_name = self.scope['url_route']['kwargs']['order_id'] print('the result is ....', self.scope['path']) print('the user is', self.scope["user"]) self.room_group_name = 'order_%s' % self.room_name print('order is this......', ) print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) if self.scope['user'].is_authenticated: order = Order.give_order_details(self.room_name) self.accept() self.send(text_data=json.dumps({ 'payload': order })) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'order_status', 'payload': text_data } ) def order_status(self, event): print('data in event............', event) data = json.loads(event['value']) self.send(text_data=json.dumps({ 'payload': data })) **middeleware.py** from django.contrib.auth.models import AnonymousUser from rest_framework.authtoken.models import Token from channels.db import database_sync_to_async from channels.middleware import BaseMiddleware @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token.user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, … -
How to make a global filter in Django admin?
Is it possible to make a global filter in the admin panel? For example, there are models: class Company(models.Model): name = models.CharField( 'Name company', max_length=200, help_text='Name company' ) city = models.CharField( 'City', max_length=200, help_text='City' ) class Object(models.Model): name = models.CharField( 'Name object', max_length=200, help_text='Name object' ) number = models.CharField( 'Number object', max_length=200, help_text='Number object' ) company = models.ForeignKey( Company, on_delete=models.SET_NULL, verbose_name='Company', null=True ) class Person(models.Model): name = models.CharField( 'Name, max_length=200, help_text='Name' ) number = models.CharField( 'ID person', max_length=200, help_text='ID person' ) object = models.ForeignKey( Object, on_delete=models.SET_NULL, verbose_name='Object', null=True ) It turns out that there are several companies. Each company has several facilities, which in turn have staff. I want to make a global filter by Companies in the admin panel. That is, not to filter every time, but let's say I chose the company "Horns and Hooves" and calmly worked in the admin area with objects belonging to this company. This is just an example, in reality there are many more models -
implementing admin.stackedinline in frontend
I have an inlineformset_factory: PollFormset = inlineformset_factory(Post, Poll, form=PollForm, max_num=10, extra=1, can_delete=False) and I want below the form the option to add and create another Poll like in the django admin panel, template: {% for form in poll_form %} {{ form.non_field_errors }} <div class="container" id="poll_form"> <div class="row" name="service_form"> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form %} <div class="col-sm"> {{ field.errors }} {{ field|as_crispy_field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> </div> {% endfor %} I also tried {{poll_form.management_form}} but it doesnt work. -
My deployment doesnt work Heroku error 500 Django in Debug=False
when i set my Debug = False i get the error 500 when i used in my console heroku logs --tail i got this, any ideias what to do? 2022-04-13T06:44:52.000000+00:00 app[api]: Build succeeded 2022-04-13T06:44:53.075990+00:00 app[api]: Release v35 created by user kaynanrodrigues.nt@gmail.com 2022-04-13T06:44:53.339661+00:00 heroku[web.1]: Restarting 2022-04-13T06:44:53.357861+00:00 heroku[web.1]: State changed from up to starting 2022-04-13T06:44:53.959374+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-04-13T06:44:54.452351+00:00 heroku[web.1]: Process exited with status 0 2022-04-13T06:45:05.748318+00:00 heroku[web.1]: State changed from starting to up 2022-04-13T06:45:25.830808+00:00 app[web.1]: 10.1.39.134 - - [13/Apr/2022:03:45:25 -0300] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36" 2022-04-13T06:45:25.873534+00:00 heroku[router]: at=info method=GET path="/" host=quiet-ravine-74023.herokuapp.com request_id=8226cd3b-d197-4d3b-bd37-eee9631f26fe fwd="177.124.150.24" dyno=web.1 connect=0ms service=1190ms status=500 bytes=451 protocol=https 2022-04-13T06:45:30.198206+00:00 app[web.1]: 10.1.39.134 - - [13/Apr/2022:03:45:30 -0300] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36" 2022-04-13T06:45:30.241595+00:00 heroku[router]: at=info method=GET path="/" host=quiet-ravine-74023.herokuapp.com request_id=ab31f68c-7b92-4d5a-90a5-db75f859de0d fwd="177.124.150.24" dyno=web.1 connect=0ms service=232ms status=500 bytes=451 protocol=https MORE CODE ABOUT THE PAGES THAT ARE BEING LOADED 2022-04-13T06:20:40.319695+00:00 heroku[router]: at=info method=GET path="/static/assets/jqr/scrollup.js" host=quiet-ravine-74023.herokuapp.com request_id=d686e3eb-52ed-48b6-88e6-2463398efed6 fwd="177.124.150.24" dyno=web.1 connect=0ms service=1ms status=200 bytes=2446 protocol=https2022-04-13T06:20:40.320227+00:00 app[web.1]: 10.1.56.53 - - [13/Apr/2022:03:20:40 -0300] "GET /static/assets/jqr/scrollup.js HTTP/1.1" 200 0 "https://quiet-ravine-74023.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36" 2022-04-13T06:20:40.322117+00:00 … -
Django bootstrap css 404 Not found
I'm trying to load in bootstrap into my html page but I get a 404 status code in the network tab in the developers tools saying that it could not find the file the request url is http://127.0.0.1:8000/static/css/bootstrap.css this is my html page where I am trying to use to the file <!-- templates/base.html --> {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Dog Groomers</title> <link rel="stylesheet" type="text/css" href="{% static '/css/bootstrap.css' %}"/> </head> </html> Here is my file structure in my settings.py file STATIC_URL = 'static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] Do I need to have a static folder in every folder instead of just having it in the root? -
How to run Django project in background
Recent I am running Django project on terminal using this command: python manage.py runserver 0.0.0.0:80 But Server is stopped by closing terminal, So I need to run server in background. How can I solve this issue? -
How to set all available values of one model to another model in django?
I have following code class Version(models.Model): version = CharFeild version_url = UrlField class MyModel(models.Model): name = CharFeild default_version = OnetoOneField(Version) available_versions = ForeignKeyField(Version) i am getting stuck at when selecting available version i am only able to pick one, where i want to select all available or all the ones i require. -
Bangladeshi Visa Card Payment Gateway Integration using django, python or React
I need integrate Bangladeshi Visa Card payment gateway into python, django application with frontend React. I want to use direct API, but don't getting any API link or documents for this. How can I do this? Can anyone help please? -
How to get child model field value from parent model serializer in Django Rest Framework?
I am trying to access child model value from parent model serializer. Parent Models class Course(models.Model): name = models.CharField(max_length=100) Child Models class CourseStaff(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='course_staff_course') staff = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_staff_user') enable = models.BooleanField() Serializer Class class TeacherCourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = '__all__' Expected Result [ { id: 1, name: "", staff_id: 5, #<---- It will come from the child model. is_enabled: true #<---- It will come from the child model. } ] How can I achieve this? Thanks -
Django, switch between databases listed in settings file in case result not found in default one
I have 2 databases listed in settings file. default database contains latest information and secondary contains older data. How to create a fall back mechanism where in, incase data for query dosen't exist in default database then it should fetch from secondary database and if it still dosen't exist there then it shows record dosen't exist. 'default': { 'NAME': 'gws', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'secondary':{ 'NAME': 'gwsautqe_ocar890', 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }