Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querying for GroupBy in Django
class Author(models.Model): first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10, null=True, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' class Book(models.Model): name = models.CharField(max_length=100) author = models.ManyToManyField(Author, related_name='book_author') price = models.SmallIntegerField() def __str__(self): return self.name Hello there! I've been trying to group by the cost of books in the above model according to the author (as there can be multiple authors for a single book). I know it can be done using groupby but I don't know how to query for it in Django ORM, I tried searching the web but didn't get the relevant solution. What I'm trying to do is, for e.g., if a book 'Wonder' has two authors 'A' and 'B' and they have written together with other books as well, like 'Wonder' by 'A' and 'B' and 'New' by 'A' and 'B' So, I want to query for the books with the combination of their authors + a total cost field of all the books written by the authors (many-to-many author combination). If there is a way, please help and sorry for the bad English. -
suit_form_tabs is not working in Django-Admin
I am using django-suit to create my website's admin. I want to create different tabs in a form, for that I am using suit_form_tabs property I added it in my admin but it does not working and not showing in admin form. change_form_template = 'admin/view_order.html' def customer_username(self, obj): return format_html(f'''<a href="/admin/signin/customer/{obj.username.id}/change/">{obj.username.username}</a>''') def generate_invoice(self, obj, request): print("Generating invoice......") return messages.info(request,message="generate invoice") def view_order(self, obj): return f"Order No #{obj.id}" list_display = ['view_order', 'customer_username', 'full_name', 'email','shipping_mobile_number', 'created_at', 'order_status'] suit_form_tabs = (('info', 'Info'), ('address', 'Address'),('products', 'Products'),('tracking','Tracking')) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url='', extra_context=None): if not object_id: self.form = OrderForms2 self.inlines = [orderProduct,OrderTrackingAdminTabular] self.fieldsets = [ ('Info', { 'classes': ('suit-tab', 'suit-tab-info',), 'fields': ['full_name'] }), ('Address', { 'classes': ('suit-tab', 'suit-tab-address',), 'fields': []}), ('Products', { 'classes': ('suit-tab', 'suit-tab-products',), 'fields': []})] self.suit_form_tabs = (('info', 'Info'), ('address', 'Address'),('products', 'Products'),('tracking','Tracking')) extra_context = {} extra_context.update({ 'show_save': True, 'show_save_and_continue': True, 'show_save_and_add_another': False, 'show_delete': False, 'Add_Order': True,}) return admin.ModelAdmin.changeform_view( self, request, object_id=object_id, form_url=form_url, extra_context=extra_context) obj = self.get_object(request, unquote(object_id)) if request.method == 'POST' and 'generate_invoice' in request.POST: self.generate_invoice(obj, request) return redirect(f'/api/v1/order/generate_invoice/{obj.id}/') self.form = OrderForms self.inlines = [] if request.method == 'POST' and 'save_delivery_partner' in request.POST: if not len(request.POST['delivery_partner']): del_partner = None else: del_partner = request.POST['delivery_partner'] obj.delivery_partner = del_partner obj.save() return HttpResponseRedirect(request.get_full_path()) if request.method == … -
Could not determine join condition between parent/child tables on relationship Product.collections
The relationship between Product and Collection is many to many. A product can be in many collections and each collection can have many products. For such case, I want to convert the django models to sqlalchemy in fastapi. Below is a table for product and collection in django models class Product(models.Model): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) name = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) class CollectionProduct(models.Model): collection = models.ForeignKey( "Collection", related_name="collectionproduct", on_delete=models.CASCADE ) product = models.ForeignKey( Product, related_name="collectionproduct", on_delete=models.CASCADE ) class Collection(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) products = models.ManyToManyField( Product, blank=True, related_name="collections", through=CollectionProduct, through_fields=("collection", "product"), ) background_image = VersatileImageField( upload_to="collection-backgrounds", blank=True, null=True ) I tried the below way to migrate django model to sqlalchemy. However, I got following error sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Product.collections - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. sqlalchemy class Product(Base, TimestampMixin): id = Column(Integer, primary_key=True, index=True) title = Column(String(255), nullable=False) slug = Column(String, index=True, unique=True) # referencing the parent product_type_id = Column(Integer, ForeignKey("producttype.id")) product_type = relationship("ProductType", back_populates="products") collections = relationship( "Collection", back_populates="product", ) collectionproduct … -
Django mongoengine rendring pdf file
I am trying to open my pdf file from my search result as i am using mongoengine in django. Recently i shift from sql to mongodb. how to open pdf file from frontend mongoengine django search.html for sql db.below code is for sqldb and i am looking for similar to this in mongoengine django ''' <h1>You searched for {{ searched }} </h1> <br/> {% for i in Document %} <a href="{{ i.file.url }}" class="btn btn-outline-secondary" target="_blank"> {{i.filename}}</a> <br/> ''' This is my search function ''' def search(request): if request.method == "POST": if request.POST.get('searched'): searched = request.POST.get('searched') dbname = my_client['resume'] collection_name = dbname["user_resumes"] collection_name.create_index([("num2","text")]) Document = collection_name.find({"$text": {"$search": str(searched)}},{"score": {"$meta": "textScore"}}).sort([("score",{"$meta":"textScore"})]) return render(request,'search.html'{'searched':searched,'Document':Document}) ''' if you have any reference please share it with me. -
Returning data from task Django+Celery
I'm new to Django and Celery. So what I'm trying to do is return data after it has been queried via the corresponding models object in a task. tasks.py from celery.decorators import task from .models import * from .serializers import * from .views_api_utils import * from rest_framework import status from rest_framework.response import Response @task(name="get_all") def get_all(): dummies = Dummy.objects.all() return dummies views.py @api_view(["GET"]) @authentication_classes([]) @permission_classes([]) def dummy_list_all(request): """ list all dummy objects """ if request.method == "GET": dummies = get_all.delay() serializer = DummySerializer(dummies, many=True) return Response(dummies, status=status.HTTP_200_OK) The issue at hand is that I keep getting this error TypeError: Object of type AsyncResult is not JSON serializable. Advise? -
emotion detection face-api-js models connot load in the django
''' Failed to load resource: the server responded with a status of 404 (Not Found) :8000/models/face_landmark_68_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) :8000/models/face_recognition_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found) face-api.min.js:1 Uncaught (in promise) Error: failed to fetch: (404) Not Found, from url: http://127.0.0.1:8000/models/tiny_face_detector_model-weights_manifest.json at face-api.min.js:1 at face-api.min.js:1 at Object.next (face-api.min.js:1) at n (face-api.min.js:1) (anonymous) @ face-api.min.js:1 (anonymous) @ face-api.min.js:1 (anonymous) @ face-api.min.js:1 n @ face-api.min.js:1 :8000/models/face_expression_model-weights_manifest.json:1 Failed to load resource: the server responded with a status of 404 (Not Found)''' anyone help to solve this error to load models can i give path for inside the js file? means can we used load static in js ? if yes pleas help ''' const video = document.getElementById('video') Promise.all([ faceapi.nets.tinyFaceDetector.loadFromUri({% static '/models' %}), faceapi.nets.faceLandmark68Net.loadFromUri({% static '/models' %}), faceapi.nets.faceRecognitionNet.loadFromUri({% static '/models' %}), faceapi.nets.faceExpressionNet.loadFromUri({% static '/models' %}) ]).then(startVideo) function startVideo() { navigator.getUserMedia( { video: {} }, stream => video.srcObject = stream, err => console.error(err) ) } video.addEventListener('play', () => { const canvas = faceapi.createCanvasFromMedia(video) document.body.append(canvas) const displaySize = { width: video.width, height: video.height } faceapi.matchDimensions(canvas, displaySize) setInterval(async () => { const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions() const … -
Django Help: AttributeError: module 'django.db.models' has no attribute 'BooleanFeild'
I am working on a simple chat application in Django 3.2.5, I faced an issue here when I gave python manage.py makimigrations command, the terminal showed this error File "C:\Python\Python3.9.6\Scripts\ChatApp\chat\models.py", line 8, in Message is_read = models.BooleanFeild(default=False) AttributeError: module 'django.db.models' has no attribute 'BooleanFeild' And the code of the models.py file is from django.contrib.auth.models import User from django.db import models class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=12000) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) Please help me in resolving this error. Your kind response will really be helpfull. -
How <object> or <iframe> does not work with Nginx reverse proxy
My website has a section to display another website by using . It works fine if user access the web server directly. However, that section does not show anything if I put the web behind nginx reverse proxy. I wonder if any nginx configuration shoud be added to support this application. Thank you. HTML <div class="container-fluid"> <div id="terminal" style="height: 800px; width: 100%;"> <div> </div> JS $("#consolebutton").click(function(e) { e.preventDefault(); var device = $('#device option:selected').text(); $.ajax({ type: "POST", url: "{% url 'Generate_Console_Session' %}", headers: { "X-CSRFToken": "{{ csrf_token }}" }, data: { "device": device }, success: function(result) { var instance = JSON.parse(result); var ip_address = instance["ip_address"]; var console_string = '<object type="text/html" data="http://172.18.1.10:8888?hostname=' + ip_address + 'width="1500px" height="800px" style="overflow:auto"></object>'; $("#terminal").html(console_string); }, error: function(result) { alert('Internal Error'); } }); }); Nginx server { listen 8443 ssl; server_name 127.0.0.1 172.18.1.10 managementserver; ssl_certificate /etc/nginx/cert.crt; ssl_certificate_key /etc/nginx/cert.key; ssl_session_cache builtin:1000 shared:SSL:10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4; ssl_prefer_server_ciphers on; access_log /var/log/nginx/app.log; location / { proxy_set_header Host $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://console:8000; proxy_read_timeout 90; } } -
How to access user details in all pages in django?
After login I want to access User details when ever I want (Particularly in navigation bar). I did not use user model provided in django. I created my own model like this for authentication. My database is stored in mysql on phpmyadmin(Xampp). AdminUser Modal class adminUser(models.Model): username=models.CharField(max_length=50) firstname=models.CharField(max_length=50) department=models.CharField(max_length=50) name=models.CharField(max_length=50) mail=models.CharField(max_length=50) id=models.IntegerField(primary_key=True) password=models.CharField(max_length=200) class Meta: db_table="admin_users" admin_users.py def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username is not None and password is not None: user=adminUser.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) print(is_check) if is_check==True: return redirect(reverse('faq_index')) else: return render(request,'AdminUsers/login.html') return render(request,'AdminUsers/login.html') During the login User Details can be only access by login function but I want to access user details in all pages for navigation bar and also want to find out whether user is authenticated or not. As I am not using User Model in django so I can not user user.is_authenticated(). So How do I do this? -
How i can to refactor code model using Built-in class-based generic views in django?
i implements Views with Built-in class-based generic views in django. i using a Listview CreateView UpdateView DeleteView like this. @method_decorator(decorators, name='dispatch') class CustomerListView(ListView) @method_decorator(decorators, name='dispatch') class CustomerCreateView (CreateView ) @method_decorator(decorators, name='dispatch') class CustomerUpdateView(UpdateView ) @method_decorator(decorators, name='dispatch') class CustomerDeleteView(DeleteView ) and this urls.py path('customer/', views.CustomerListView.as_view(), name='customer-list'), path('customer/add', views.CustomerCreateView.as_view(), name='customer-add'), path('customer/update/<id>', views.CustomerUpdateView.as_view(), name='customer-update'), path('customer/delete/<id>', views.CustomerDeleteView.as_view(), name='customer-delete'), this code work normally. but i have implement multiple model with this pattern such as Customer,Employees,Woker, ..... and more. i want to know how to refacetor code like this. in views.py ------------- class Customer(Somthing): # this include Listview CreateView UpdateView DeleteView model = CustomerModel class Employee(Somthing): # this include Listview CreateView UpdateView DeleteView model = EmployeeModel class Woker(Somthing): # this include Listview CreateView UpdateView DeleteView model = WokerModel in urls.py ------------- path('customer/', views.Customer.as_view()), path('employee/', views.Employee.as_view()), path('worker/', views.Worker.as_view()), how the best way to implements?. thank you for expert. -
Why "CSRF verification failed. Request aborted." in CreateModelMixin in django rest framework?
I am new to django rest framework, and trying to write a view to register users but whenever i am running my view by hitting the desired url i get the following error. Error:- Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. View:- class UserRegistration(mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = RegistrationSerializer def post(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) Serializer:- class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True} } def save(self): password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'error': 'p1 and p2 must be same'}) if User.objects.filter(email=self.validated_data['email']).exists(): raise serializers.ValidationError({'error': 'email already exists'}) account = User(email=self.validated_data['email'], username=self.validated_data['username']) account.set_password(password) account.save() return account Note:- I am using postman forAPI testing. I know there are some great way to do the same, but for this instant i would like make this … -
How to use query result in if statement tag in Django template
Is it possible to use query result in if statement template tag category.html (template): {% for ETF in ETFs %} <td>{{ ETF.ticker }}</td> <td>{{ ETF.full_name }} {% if ETF.asset_class == "Inverse" %} <! –– this don't work ––> <span class="alert-warning" > Inverse </span> {% endif %} </td> {% endfor %} views.py def etf_list(request): filtered_results = ETF.objects.all() return render(request, "etf/category.html", { "ETFs": filtered_results, }) It does not work here because ETF.asset_class is not a string object. So it cant equal to another string. Is there other ways to make it work? I have a table of items in the html and want to highlight some items that have some model attributes. -
Django - how can i insert '.json' file to SQLite DB?
my '.json file' like { "users": [ { "userId": 1, "firstName": "AAAAA", "lastName": "as23", "phoneNumber": "123456", "emailAddress": "AAAAA@test.com", "homepage": "https://amogg.tistory.com/1" }, { "userId": 2, "firstName": "BBBB", "lastName": "h5jdd", "phoneNumber": "123456", "homepage": "https://amogg.tistory.com/2" }, { "userId": 3, ... i was search that to google, and try to this problem.. but unresolved. so i use pandas and sqlite3 import sqlite3 as db import pandas as pd df = pd.read_json('test.json') con = db.connect('./test.db') df.to_sql('test', con=con) so DB is created, but .json file data dont save in DB how can solve this problem...? -
Django - Serialize a list of primary keys for ManyToMany attribute?
So I have this test that generates a list of goal categories, which are the primary key then it populates the model described below. When it goes to UserInterestViews if I pass the list of goal_category_list I get an error that they aren't valid PKs, but when I just pass in 1 string it's fine. How do I pass in a list of primary keys to a ManyToManyField in the serializer? test import json from django.urls import reverse from django.test import TestCase from rest_framework import status from cheers.models import GoalCategory from dummy_factory.Factories import UserFactory class UserInterestsTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.goal_category_list = ['health', 'fitness', 'academic', 'spiritual'] for gc in cls.goal_category_list: GoalCategory.objects.create(category=gc, emoji_url='some_url') cls.user = UserFactory() def test_create(self): response = self.client.post(reverse('set_user_interests'), data=json.dumps({'user': str(self.user.uuid), 'categories': self.goal_category_list}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) view.py class UserInterestsView(APIView): """ View for UserInterests object * requires token authentication """ # Create user interests @swagger_auto_schema( request_body=UserInterestsSerializer, operation_description="Create user interests object" ) def post(self, request): serializer = UserInterestsSerializer(data=request.data) if serializer.is_valid(): try: serializer.save() except django.db.utils.InternalError as e: return Response(dict(error=e), status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) model.py class UserInterests(AbstractBaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE) categories = models.ForeignKey(GoalCategory, on_delete=models.CASCADE) -
setting limit to floatfield according to another floatfield
I have these fields in a form. demand = forms.FloatField(label='Demand:', min_value=0) production_rate = forms.FloatField(label='Production rate:', min_value=0) I need producion_rate to be greater than the demand value. It's possible? -
Exist any way of automatic validation in the django serializer for primaryKey (author_slug or phrase_slug)?
I have my CRUDs with models, serializares and views. # models.py from django.db import models class Author(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() class Meta: db_table = 'authors' class Phrase(models.Model): author_slug = models.ForeignKey(Author, db_column='author_slug', on_delete=models.DO_NOTHING) text = models.TextField() class Meta: db_table = 'phrases' # serializers.py from rest_framework import serializers from .models import Author, Phrase class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('slug', 'name', 'description') class PhraseSerializer(serializers.ModelSerializer): author = AuthorSerializer(source='author_slug', read_only=True,) class Meta: model = Phrase fields = ('id', 'text', 'author_slug', 'author') # views.py from rest_framework import viewsets from .models import Author, Phrase from .serializers import AuthorSerializer, PhraseSerializer class AuthorViewSet(viewsets.ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() class PhraseViewSet(viewsets.ModelViewSet): serializer_class = PhraseSerializer queryset = Phrase.objects.all() Now i need to do a new specify endpoint GET /exist-relationship-bwt-author-phrase when this body: { "author_slug": "an-author", "phrase_slug": "a-phrase" } Exist any way of automatic validation in the django serializer for primaryKey (author_slug or phrase_slug)? -
DRF test if JSON list of objects contains a specific object
I'm testing an endpoint from Django DRF, which produces a JSON list of objects. I'm trying to check if a specific object is in the returned list. I've tried assertIn and assertContains, but they produce errors. Test code for the assertIn: def test_list(self): client = APIClient() response = client.get('/api/some_list/', format='json') self.assertEqual( len(response.data), 19 ) self.assertIn( response.data, { "id": 2, "name": "WhatToDo" } ) assertIn produces TypeError: unhashable type: 'ReturnList' Test code for the assertContains: def test_list(self): client = APIClient() response = client.get('/api/some_list/', format='json') self.assertEqual( len(response.data), 19 ) self.assertContains( response, { "id": 2, "name": "WhatToDo" } ) assertContain just failed the test. What is the best approach to test if a specific object exists in the JSON list in response? -
ValueError: The view blog.views.post_search didn't return an HttpResponse object. It returned None instead
I'm implementing "search function" to my django blog, using Solr and Haystack. In "http://127.0.0.1:8000/blog/search/", it says TypeError at /blog/search/ post_detail() missing 3 required positional arguments: 'year', 'month', and 'day' Also in "http://localhost:8000/blog/search", it says ValueError at /blog/search The view blog.views.post_search didn't return an HttpResponse object. It returned None instead. blog/forms.py from django import forms class SearchForm(forms.Form): query = forms.CharField() blog/search_indexes.py from haystack import indexes from .models import Post class PostIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) publish = indexes.DateTimeField(model_attr='publish') def get_model(self): return Post def index_queryset(self, using=None): return self.get_model().published.all() blog/urls.py from blog.feeds import LatestPostsFeed from django.conf.urls import url from django.urls import include, path from . import views app_name = 'blog' urlpatterns = [ path('search', views.post_search, name='post_search'), ] blog/views.py from .forms import SearchForm from haystack.query import SearchQuerySet def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) blog/templates/blog/post/search.html {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} {% if "query" in request.GET %} <h1>Posts containing "{{ cd.query }}"</h1> <h3>Found {{ total_results }} result{{ total_results|pluralize}}</h3> {% for result in results %} … -
Nginx 502. Bad Gateway but working with CORS. Should I use CORS in production?
Im trying to dockerize a Django App + React with Nginx and proxy pass the request to my backend with upstream. The issue im having is that if I do not enable cors and allow localhost:4000 within my backend the connection gets refused. Nginx throws: 2021/09/02 21:57:02 [error] 26#26: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.21.0.1, server: , request: "GET /api/users/me HTTP/1.1", upstream: "http://172.21.0.4:8000/api/users/me", host: "localhost:4000", referrer: "http://localhost:4000/" Side Note: I don't know where ... client: 172.21.0.1 ... from the log error above is coming from. I tried to set ALLOWED_HOSTS to ["*"], ["localhost", "localhost:4000", "127.0.0.1", "127.0.0.1:4000"] but it doesn't seem the problem is here. With CORS: CORS_ALLOWED_ORIGINS = [ "http://localhost:4000", "http://127.0.0.1:4000", ] It works just fine. I haven't tried to deploy the app with cors to test it in production So my questions are: Is this the right way of allowing traffic through my web server? Is it okey to have cors in production if it Here is my Nginx.conf: upstream backend { server backend:8000; } server { listen 8080; #mapping port 4000:8080 from docker-compose error_log /var/log/nginx/api.error.log; location /api { proxy_set_header host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-forward-for $proxy_add_x_forwarded_for; proxy_pass http://backend; } location /staticbe/ … -
import declarations may only appear at top level of a module and disallowed MIME type
I'm trying to load a script that includes an import statement, but Firefox shows the "import declarations..." error in the console. The import in my script looks something like this: import { foo } from './path/to/js/file'; I can get rid of this error by including type="module" as an attribute of the script tag in my HTML, but then I get a different error in the console: "Loading module from “http://localhost:8000/path/to/js/file” was blocked because of a disallowed MIME type (“text/html”)." It also shows a 404 in the console for the script I'm trying to import. Interestingly, I can get rid of both of these by appending .js to my import statement: import { foo } from './path/to/js/file.js'; But since file.js is part of a larger library with its own import statements, all subsequent import statements raise MIME type errors and 404s. I'm using Django as my backend framework and the application is in a docker container. What am I doing wrong? -
How to turn off django logging INFO to console?
For some reason I cannot figure out how to get django to stop spamming INFO level information to the console. I've tried logging.disable(logging.CRITICAL) in settings.py, as well as this dict in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False }, } Can anyone help me with this? Thanks! -
Django how can I redirect after post request result
def postDataRequest(request): if request.method == 'POST': username = request.POST['username'] userid= request.POST['userid'] if(userid== "21310"): context = { "result" : Dataengine(username,userid).dataFunc() } messages.add_message(request, messages.SUCCESS, context) return render(request, 'pages/dataresult.html', context) I show some data to users with post request.What I want to do is redirect 'pages/index.html' within 30 seconds after the user sees the result on the 'dataresult.html' page. How can I do that? -
Iterate over variable and insert additional rows Postgres
Just to note, yes I have seen similar questions on here but none quite close enough for the particular issue. I have a table (let's call it 'table 1') in postgres with three columns based on a django model, 'ID' (auto incrementing value), 'affiliation', and 'entry'. What I need to do is take every entry where affiliation = 52, and then add an additional row with entry = query.entry and affiliation = 48 (just to reiterate, I need additional rows, not changed values). I also need to make sure that the entry + affiliation pair don't already exist. No matter what I do I get a syntax error! Any help? The latest call was: do $$ declare id_array int[]; begin insert into id_array table_1.entry where table_1.affiliation = 52; for id in id_array loop if not exists (select entry from table_1 where affiliation = 48) then insert into table_1 (affiliation, entry) values (48, id); else raise notice "already exists"; end if; endloop; end; $$ Any ideas? I'm at a complete loss...This is by far the most complex query I've ever ran. -
How to use register users in django that are register in Laravel?
The website is develop in Laravel. I want to add some functionalities in it. Kindly help me to that how can i get Users in django that are register in Laravel? -
Django/Python change content.innerHTML to a src page
I am running a page that on a click, replaces the content in an iFrame. The JS in index.js looks like this: if (page == 'stationData') { content.innerHTML = '<h1>Station Data</h1>'; content.innerHTML += '<iframe class="site_data_tab" src="stationDataHTML.html"></iframe>'; } The old iFrame data goes away and the text "Station Data" appears as expected, but I can't figure out how to get the stationDataHTML.html page to appear in the iFrame. I've tried something like this: index.js: if (page == 'stationData') { content.innerHTML = '<h1>Station Data</h1>'; content.innerHTML += '<iframe class="site_data_tab" src="{% url \'data-stationData\' %}"></iframe>'; } urls.py: urlpatterns = [path('', AboutView.as_view(template_name="stationDataHTML.html")),] views.py: class AboutView(TemplateView): template_name = "stationDataHTML.html" When I run, and I click the button to change the iframe content, I recevie and error Not Found: /data/stationDataHTML.html [02/Sep/2021 16:02:04] "GET /data/stationDataHTML.html HTTP/1.1" 404 6279 Is there a a way to change the iframe content to a locally hosted page? (stationDataHTML.html)