Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: No module named 'secrets'
I am unable to start a project everything until this step works but after this, it shows this error A Picture of the Terminal window -
How to print the data in console log of list of values from a list of dicts in javascript
def checkproductname(request): # request should be ajax and method should be GET. if request.is_ajax and request.method=="GET": # get the productname form the clientside productname=request.GET.get("productname",None) product=Product.objects.filter(productname=productname).values() # check the productname in the database if Product.objects.filter(productname__icontains=productname).exists(): product=Product.objects.filter(productname=productname).values() data1=list(product) data=json.dumps(data1) print(data) # if productname is found return valid productname return JsonResponse({'valid':True, 'data':data, 'status':200, 'safe':False}) else: # if productname is not found return productname is invalid return JsonResponse({"valid":False},status=200) return JsonResponse({},status=400) ajaxfile $(document).ready(function () { $("#id_sell-0-product").focusout(function (e) { e.preventDefault(); // get the productname var productname = $(this).val(); // GET AJAX request $.ajax({ type: 'GET', url: '/get/ajax/validate/productname', datatype:'json', data: {"productname": productname}, success: function (response,data) { console.log({data}) // if not valid user, alert the user if(!response["valid"]){ alert("we donot have the product"); var productname = $("#id_sell-0-product"); var qty = $("#id_sell-0-qty"); var price = $("#id_sell-0-price"); var total = $("#id_sell-0-total"); console.log(productname) productname.val(""); // console.log(productdetailslist.amount) qty.val(""); price.val(""); total.val(""); productname.focus() } else{ var productname = $("#id_sell-0-product"); productname.val({data}); } }, error: function (response) { console.log(response) } }) }) }) description i want to print the qunatity data in the console log for testing.need to create a dict that has the keys from all the dicts and each value for every key is a set with item values from the list of dicts. In … -
ImportError: cannot import name 'UserSerializer' from 'user.serializers'
I started a project in django and I am having problems with imports. I think the problem is caused by cyclical imports. I have changed the code in many ways, but I cannot solve it. The error: File "/home/Workspace/vesta/vesta/urls.py", line 8, in <module> from user.api import UserModelViewSet File "/home/Workspace/vesta/user/api.py", line 8, in <module> from user.serializers import UserSerializer File "/home/Workspace/vesta/user/serializers.py", line 5, in <module> from core.serializers import (UUIDSerializer) File "/mhome/Workspace/vesta/core/serializers.py", line 2, in <module> from user.serializers import UserSerializer ImportError: cannot import name 'UserSerializer' from 'user.serializers' (/home/Workspace/vesta/user/serializers.py) And the code: vesta/vesta/urls.py from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import include, re_path from rest_framework.routers import DefaultRouter from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) from core.api.schemas.schema_view import schema_view from user.api import UserModelViewSet router = DefaultRouter() router.register(r'user', UserModelViewSet, basename='user') urlpatterns = [ # API documentation and playground re_path(r'^api-doc/$', schema_view.with_ui('redoc', cache_timeout=0), name='api-doc'), re_path(r'^api-playground(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='api-playground-json'), re_path(r'^api-playground/$', schema_view.with_ui('swagger', cache_timeout=0), name='api-playground-ui'), # Admin re_path(r'admin/', admin.site.urls), # Authentication token re_path(r'auth/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), re_path(r'auth/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), re_path(r'auth/token/verify/', TokenVerifyView.as_view(), name='token_verify'), # API re_path(r'', include(router.urls)) ] urlpatterns += staticfiles_urlpatterns() vesta/user/api.py from django.utils.decorators import method_decorator from drf_yasg.utils import swagger_auto_schema from rest_framework import mixins from core.api.parameters import query_parameter from core.viewsets import BaseModelViewSet from user.models import User from user.serializers import UserSerializer @method_decorator(name='retrieve', decorator=swagger_auto_schema(manual_parameters=[query_parameter])) … -
i am getting a warning mentioning devtools failed to load source map
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/vendor/bootstrap/js/popper.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE like this so please help me out with this -
Adding db_table to model added a last_login field
Background: I started a project with a custom User model. However, noob that I am, I was unaware of the AbstractBaseUser class. So I just wrote my own. The app has been deployed to prod and working fine. But now I want to switch to using AbstractBaseUser so I can take advantage of some of the built-in Django utilities (like the pre-made password resetting process). I had done this with a different app and it worked fine. But that one wasn't in prod while I made the change. Because this one is, I needed to keep the old user table while I made the changes with a copy of it. So my first step was to add db_table = test_users to my old user model, so as to keep the prod app running with an unchanged table. I ran the migration, and two unexpected things happened (I'm a noob, and that's why they were unexpected): The old user table was renamed. I thought a new table would be created. No problem, I quickly copied the new table and named the copy with the old table's name so the prod app could still find its users A column last_login was added. … -
You're running the worker with superuser privileges: this is absolutely not recommended
I have Python/Django project and have this error. Explain lease, what is mean? [2020-07-11 00:43:20,663: INFO/MainProcess] Received task: lots.tasks.notify_subscriber_about_new_lots[98514e1c-2843-47c6-8ed6-33b7fa493d38] /webapps/django_shop/django_env/lib/python3.6/site-packages/celery/platforms.py:801: RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended! Please specify a different user using the --uid option. User information: uid=0 euid=0 gid=0 egid=0 uid=uid, euid=euid, gid=gid, egid=egid, [2020-07-11 00:43:20,719: ERROR/ForkPoolWorker-2] Task lots.tasks.notify_subscriber_about_new_lots[98514e1c-2843-47c6-8ed6-33b7fa493d38] raised unexpected: AttributeError("'NoneType' object has no attribute 'id'",) Traceback (most recent call last): File "/webapps/django_shop/django_env/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(args, kwargs) File "/webapps/django_shop/django_env/lib/python3.6/site-packages/celery/app/trace.py", line 650, in protected_call return self.run(args, kwargs) File "/webapps/django_shop//lots/tasks.py", line 301, in notify_subscriber_about_new_lots receiver = findAllFavoriteSearchReceiver(article) File "/webapps/django_shop//lots/tasks.py", line 320, in findAllFavoriteSearchReceiver if ((favorite.city and article.city.id in [item.id for item in favorite.city]) AttributeError: 'NoneType' object has no attribute 'id' [2020-07-11 00:43:20,729: WARNING/ForkPoolWorker-1] /webapps/django_shop/django_env/lib/python3.6/site-packages/urllib3/connectionpool.py:986: InsecureRequestWarning: Unverified HTTPS request is being made to host 'ows.***'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning, -
Tablesorter Jquery library is not working
I'm having troubles getting the Jquery Tablesorter plugin to work, nothing happens when I click on the column headers. I'm using django to fill the rows. Heres the code: <!-- Load jQuery if not already loaded. --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script> <!-- Load the TableSorter plugin. --> <script src="{% static 'mainApp/jquery.tablesorter.js' %}" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $("#feedbackTable").tablesorter(); }); </script> <!-- Load a theme i.e. "ice". --> <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.21.5/css/theme.ice.min.css" rel="stylesheet" /> ... <table id="feedbackTable" class="tablesorter table table-dark table-hover sortable" > <thead class="thead-light"> <tr> <th style="cursor: pointer;" >Submitted By <i class="fa fa-fw fa-sort"></i></th> <th style="cursor: pointer;" >Category <i class="fa fa-fw fa-sort"></i></th> <th style="cursor: pointer;" >Date Added <i class="fa fa-fw fa-sort"></i></th> <th style="display:none;" >Feedback</th> </tr> </thead> <tbody> {% block content %} {% for feedback in feedbacks %} <tr style="cursor: pointer;" @click="showFeedback = !showFeedback"> <td >{{feedback.submitted_by}}</td> <td > {{feedback.type_choice}} </td> <!--<td>{{feedback.feedback}}</td>--> <td>{{feedback.created_at}}</td> <td style="display:none;"> {{feedback.feedback}}</td> </tr> {% endfor %} {% endblock content %} </tbody> </table> -
how can I add css class to a django form field that is generated by RelatedFieldWidgetWrapper
how can I apply css classes to the guardian field. In the following code I used widgets option in the Meta class but that does not change any style. this is forms.py class StudentProfileForm(ProfileForm): guardian = Student._meta.get_field('guardian').formfield( widget=RelatedFieldWidgetWrapper( Student._meta.get_field('guardian').formfield().widget, Student._meta.get_field('guardian').remote_field, accounts_admin_site, can_add_related=True, ) ) class Meta: model = Student widgets = {'guardian' : forms.Select(attrs={'class':'selectpicker'})} exclude = ['user', 'guardian', 'salary', 'date_left', 'contact_number', 'status', 'reg_number', 'roll_number'] -
Django orm MTM through filtering bug
I have two models: class Training(models.Model): statuses = models.ManyToManyField('company.Company', through='TrainingStatus') class TrainingStatus(models.Model): training = models.ForeignKey('Training', on_delete=models.CASCADE) company = models.ForeignKey('company.Company', on_delete=models.CASCADE) state = FSMField(default=TrainingStatusStates.NEW, choices=TrainingStatusStates.choices) When I do query like this: trainings = Training.objects.filter(trainingstatus__state='new') if not self.request.user.is_superuser: trainings = trainings.filter(trainingstatus__company__id=3016) I expected to see my queryset filter training by trainingstatus that have state new and company_id=3016 What I see: SELECT `user_management_training`.`id` FROM `user_management_training` INNER JOIN `user_management_trainingstatus` ON (`user_management_training`.`id` = `user_management_trainingstatus`.`training_id`) INNER JOIN `user_management_trainingstatus` T3 ON (`user_management_training`.`id` = T3.`training_id`) WHERE (`user_management_trainingstatus`.`state` = new AND T3.`company_id` = 3016) I get incorrect results because filtering applying two times to whole trainingstatus queryset But If I modify my code to this: trainings = Training.objects.filter(trainingstatus__state='new') if not self.request.user.is_superuser: trainings = trainings.filter(trainingstatus__state='new', trainingstatus__company=3016) It works like expected. Python 3.7 Django 1.11 -
how to return to redirect absolute object url django function based
i'm confused why cant redirect to absolute url django function based view class Post(models.Model): title = models.CharFieldl(max_length=13) def get_absolute_url(self): return reverse('blog:blog-post',kwargs={'pk':self.pk}) my views.py def createPost(request): if request.method == 'POST': blog_post= PostForm(request.POST) if blog_post.is_valid(): obj = blog_post.save(commit=False) obj.admin = request.user obj.save() messages.success(request,'added') i'vent used FBV before as much as CBV , i dont know where should i use redirect(reverse_lazy('blog:blog-post',pk=obj.pk})) app_name = 'blog' path('blog/<int:pk>', views.PostDetailView.as_view(),name='blog-post'), my detail view class PostDetailView(LoginRequiredMixin,DetailView): model = Post context_object_name = 'objs' template_name = 'blog/post.html' i tried many ways but non worked ? -
How to encrypt JWT token with django rest api?
So, the JWT token returned by rest_framework_jwt of django doesn't seem to be encrypted. It can be signed using the SECRET_KEY from settings.py so a fake jwt token can't be sent to the server, but the payload of the JWT can be decoded without the secret key on basically any site like http://calebb.net/. How can I encrypt the JWT so the payload is not visible? -
Django Authentication to Only Allow POST Requests from Frontend
I want to implement authentication so that POST requests to my endpoints can only be done from my frontend. I've looked into the various solutions here but not sure if I need to use Basic, Session, or Token authentication, or if there is another better solution. What do I need to do to ensure that only POST requests from my frontend go through? Thanks! -
How to employ an error alert system in a deployed Django Site
I am deploying my django site soon!! In debug=True mode, there is an error page that comes up when there is some bug in the code. When in debug=False mode, after I deploy, I want to set up something so that I am alerted whenever anyone on the prod site reaches this page. Is there any way to do this? Thanks! -
How do I connect my Django project to MySql using Windows?
I am trying to connect my Django project to the MySQL database but have run into a number of problems. I have tried running the Xampp Control Panel and starting the service there but received this error message... 18:55:35 [mysql] Attempting to start MySQL app... 18:55:35 [mysql] Status change detected: running 18:55:39 [mysql] Status change detected: stopped 18:55:39 [mysql] Error: MySQL shutdown unexpectedly. 18:55:39 [mysql] This may be due to a blocked port, missing dependencies, 18:55:39 [mysql] improper privileges, a crash, or a shutdown by another method. 18:55:39 [mysql] Press the Logs button to view error logs and check 18:55:39 [mysql] the Windows Event Viewer for more clues 18:55:39 [mysql] If you need more help, copy and post this 18:55:39 [mysql] entire log window on the forums 19:15:09 [mysql] Problem detected! 19:15:09 [mysql] Port 3306 in use by "Unable to open process"! 19:15:09 [mysql] MySQL WILL NOT start without the configured ports free! 19:15:09 [mysql] You need to uninstall/disable/reconfigure the blocking application 19:15:09 [mysql] or reconfigure MySQL and the Control Panel to listen on a different port I have also tried to install mysqlclient through the terminal, however this resulted in the following enormous error... Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz … -
How to pass ForeignKey in dict to create Model object. Django
I have created one model to store User name and place class UserDetails(models.Model): name = models.CharField(max_length=50) place = models.ForeignKey(City, on_delete=models.CASECADE) I have one JSON file there I have data of more than 1000 users. like { {"name": "A", "place":1}, {"name": "B", "place":3}, {"name": "C", "place":4}, {"name": "D", "place":1}, .. .. } There place field is related to City object id. When I am using below syntax UserDetails.objects.create(**{"name":"A", "place": 3}) then getting an error, I know instead of passing place id I have to pass obj like: loc = City.object.get(id=3) UserDetails.objects.create(**{"name":"A", "place": loc}) This is fine, but I have a large amount of data how can I pass place id or should use bulk_create to save all JSON data in model? -
Add help_text only for a few fields. Django
I have registration form and I want to output help text only for password field. How can I do it? I want to do something like this in html {% for field in form.visible_fields %} if field.name == password: {{ field.help_text }} {% endfor %} My code: forms.py from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField(required=True, label="Email") class Meta: model = User fields = ("username", "email") field_classes = {'username': UsernameField, 'email': forms.EmailField} views.py class RegisterFormView(FormView): form_class = RegisterForm success_url = "/login/" template_name = "blog/register.html" def form_valid(self, form): # Создаём пользователя, если данные в форму были введены корректно. form.save() # Вызываем метод базового класса return super(RegisterFormView, self).form_valid(form) register.html {% for field in form.visible_fields %} <div class="control-group"> <div class="controls"> <!-- Username --> <label class="control-label" for="username">{{ field.label_tag }}</label> {{ field }} <p>{{ field.help_text }}</p> </div> </div> {% endfor %} -
Ajax taking to much time to load ! Why?
Ajax take 20 to 15 seconds that is not Good and also not Normal I am using a POST request to use send data All function Work fine but time matters Here is my Code vews.py def Placse_order(request): if request.method == 'POST': first_neme = request.POST['firstname'] last_neme = request.POST['lastname'] country = request.POST['country'] street = request.POST['street'] street2 = request.POST['street2'] postcode = request.POST['zipcode'] City_or_town = request.POST['city'] email = request.POST['email'] phone = request.POST['phone'] messages.add_message(request,messages.SUCCESS,'Order i placsed succesfuly') return redirect('HomePage') javascript Done the ajax $('.place-btn').click(function(e) { e.preventDefault(); document.getElementById('PlaceOrderbtn').innerHTML = `Placing Order <span><img src="{% static 'order\spinner.gif' %}" width="11%" style="padding-left: 5px;" alt="Spineer"></span>`; $.ajax({ async: false, type: 'POST', url: '/PlaceOrder/', data: { firstname: $('input[name=firstname]'), lastname: $('input[name=lastname]'), country: $('input[name=country]'), street: $('input[name=street]'), street2: $('input[name=street2]'), city: $('input[name=city]'), email: $('input[name=email]'), phone: $('input[name=phone]'), }, encode: true, complete: function(data) { document.getElementById('PlaceOrderbtn').innerHTML = 'Order Placed'; } }) }) -
'QuerySet' object has no attribute 'ontbijt' - Django QuerySet
My model: class planner(models.Model): datum = models.DateField(unique=True) ontbijt = models.CharField(max_length=100) tussendoor = models.CharField(max_length=100) lunch = models.CharField(max_length=100) tussendoor_1 = models.CharField(max_length=100, default='Amandelen') avondeten = models.CharField(max_length=100) My view: def voedingplanner_interface(request): dt_now = datetime.datetime.now().strftime('%Y-%m-%d') data_planning = planner.objects.filter(datum__gte=datetime.date.today()) print (data_planning.ontbijt) < CAUSE !!!! My error: 'QuerySet' object has no attribute 'ontbijt' My question: I know i can return the models trough str (self) etc, but that way makes it hard for this program in the future. As in HTML i can just write {{dataplanning.ontbijt}} and it appears. The same way i want it in my backend. As far as i searched and study + my knowledge i didn't find a answer. Does someone has the solotuin for this one ? Your help is apreciated ! -
Django Permissions -- same codename, different name issue
If I happen to have separate models, each with corresponding permissions, but with the same codename, is there a way to distinguish between the two when checking to see if a User has the permissions of each individual type of model? For example, I have two models, each with permissions like: class Meta: permissions = ( ('can_execute', 'Can execute class1'), ) class Meta: permissions = ( ('can_execute', 'Can execute class2'), ) then, when checking if a user has these permissions, like user.has_perm('app.can_execute') is there no way to distinguish between the two? Should I always have it so that the codenames are distinct for each separate model? -
How to add display dropdown fields HTML Django
i know this is probably a very easy question, but i'm trying to add a category field to my blog posts model in django. When i make a post with the admin panel it shows the choices in a drop down list, however does anyone know how to display choices in html. Here is the form in my HTML file: <div class="container"> <div class="row"> <div class="col-lg-7 offset-lg-1"> <form class="create-form" method="POST" enctype="multipart/form-data">{% csrf_token %} <!-- title --> <div class="form-group"> <label for="id_title">Title</label> <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus> </div> <!-- Body --> <div class="form-group"> <label for="id_body">Content</label> <textarea class="form-control" rows="10" type="text" name="body" id="id_body" placeholder="Put the description of your post here..." required></textarea> </div> <div class="form-group"> <label for="id_category">Category</label> <select class="form-control" name="category" id="id_category" required></select> </div> <!-- Image --> <div class="form-group"> <label for="id_image">Image</label> <input type="file" name="image" id="id_image" accept="image/*" required> </div> Thanks in advance! -
Django sitemap generates with double https:\\ when on Heroku
I am using the sitemap framework to generate a sitemap. The google search consol states that the sitemap is an invalid file format. It seems to be valid XML but the URL's in the sitemap have a double https:// and I can't figure out why!? This only happens when hosting on Heroku and the allowed host in settings.py is set to the Heroku domain name. When I run the app locally with no allowed host the sitemap generates perfectly. Please help! Sitemap: <URL> <loc>https://https://swflreliefrealty.herokuapp.com/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <URL> <loc>https://https://swflreliefrealty.herokuapp.com/contact/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> Django sitemap.py: from django.contrib.sitemaps import Sitemap from django.urls import reverse from blog.models import Post class StaticViewSitemap(Sitemap): changefreq = 'daily' priority = '0.5' def items(self): # Return list of url names for view to include in sitemap return ['home', 'contact', 'success', 'blog'] def location(self, item): return reverse(item) class BlogSitemap(Sitemap): changefreq = 'daily' priority = '0.5' def items(self): return Post.objects.all() Django settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG_VALUE') ALLOWED_HOSTS = ['swflreliefrealty.herokuapp.com'] # Application definition INSTALLED_APPS = … -
One to many field Django Rest Framework
I'm new to DRF and django in general, saw the DRF documentation on serializer relationships but it still didn't solve my problem. I have these two models: class Estabelecimento(models.Model): endereco = models.ForeignKey(Endereco, related_name='estabelecimento_endereco', on_delete=models.SET_NULL, null=True) nome = models.CharField(max_length=32) telefone = models.CharField(max_length=11) email = models.EmailField() cnpj = models.CharField(max_length=14) imagem = models.CharField(max_length=128) horario_atendimento = models.CharField(max_length=32) aberto = models.BooleanField() ativo = models.BooleanField(default=True) class Usuario(models.Model): estabelecimento = models.ForeignKey(Estabelecimento, related_name='usuario_estabelecimento', on_delete=models.SET_NULL, null=True) endereco = models.ForeignKey(Endereco, related_name='usuario_endereco', on_delete=models.SET_NULL, null=True) nome = models.CharField(max_length=32) sobrenome = models.CharField(max_length=32) email = models.EmailField() cpf = models.CharField(max_length=11) password = models.CharField(max_length=64) role = models.CharField(max_length=12) ativo = models.BooleanField(default=True) These are there serializers: class EstabelecimentoSerializer(serializers.ModelSerializer): pedidos = pedido_serializer.PedidoSerializer(many=True, read_only=True) usuarios = usuario_serializer.UsuarioSerializer(many=True, read_only=True) class Meta: model = models.Estabelecimento fields = ('id', 'nome', 'telefone', 'email', 'cnpj', 'imagem', 'horario_atendimento', 'aberto', 'ativo', 'endereco', 'pedidos', 'usuarios',) read_only_fields = ('id',) class UsuarioSerializer(serializers.ModelSerializer): pedidos = pedido_serializer.PedidoSerializer(many=True, read_only=True) class Meta: model = models.Usuario fields = ('id', 'nome', 'sobrenome', 'email', 'cpf', 'password', 'role', 'ativo', 'estabelecimento', 'endereco', 'pedidos',) read_only_fields = ('id',) The result I wanted would be something like this (example from the DRF documentation): { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [ '1: Sunflower', '2: Whitetail', '3: Dinosaur Act', ... ] } "Estabelecimento" should have a list of "usuarios" … -
why wont my script run in html using django [duplicate]
My page isnt doing what i programmed the javascript to do is know the code i correct if i call expand() it works but not check() function check(i) { if (document.getElementById(i).style.visibility == "hidden") { expand(i); } else { collapse(i); } } function expand(i) { document.getElementById(i).style.visibility = "visible"; } function collapse(i) { document.getElementById(i).style.visibility = "hidden"; } <div id="brand" onclick="check('brand-show')"> brand </div> <div class="brand-show" id="brand-show" style="visibility: hidden">dcdv</div> <div id="brand" onclick="check('brand-show')"> brand </div> <div class="brand-show" id="brand-show" style="visibility: hidden">dcdv</div> Please help i cant get the onlick to work in django for some reason. -
How to use SQL statements to fill an array with information from a column out of a database?
I have a django project I am working with. This project is connected to an SQlite database filled with information. This database has a table titled "product_table" and consists of 'product_name', 'product_type', 'product_cost'. I am trying to fill an array named "names" with ALL of the values under the "product_name" column. How can I do this using SQL SELECT statements? -
Static files not loading on one template but loading on another
I got a template from online, and managed to get the CSS and JS working with one of my HTML templates; but for another one, the same CSS/JS won't load despite the code being identical. Here is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") This is my views: from django.shortcuts import render # Create your views here. def home_view(request, *args, **kwargs): return render(request, "about.html", {}) def contact(request, *args, **kwargs): return render(request, "contact.html", {}) def work(request, *args, **kwargs): return render(request, "work.html", {}) Here are my URL Patterns: from django.contrib import admin from django.urls import path from pages.views import home_view from pages.views import contact from pages.views import work from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', home_view , name='home'), path('contact/', contact, name = 'contact' ), path('work/', work, name = 'work'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here is the CSS of my template that works; I had to hard code it because the static tag wouldn't work for some reason: { % load static %} <html lang="en"> <head> <title>Mighty &mdash; Website Template by Colorlib</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href = https://fonts.googleapis.com/css?family=Muli:400,700 …