Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Showing sensor reading in a django websiteI want to design a web based application for showing sound sensor readings, collected from an Arduino based setup (and also show some analysis results). For making my arduino setup work I had developed a python program named 'ard_sensor_project.py' which collects readings and store in .csv file and create a graph. Now I want to display the readings generated in a django website. For that I have imported 'ard_sensor_project.py' in views.py of my django site and called a method to print the sensor reading at real time. But on running the program, it seems that though the reading collecting module has started, the site has not started yet and I can neither see the web page nor any reading. Is there any way such that I can show the readings on the django site? Here is my ard_sensor_project.py import matplotlib.pyplot as plt from datetime import datetime #necessary declarations sr = serial.Serial("COM6",9600) #self declared methods def getsensordata(): st = list(str(sr.readline(),'utf-8')) return int(str(''.join(st[:]))) def storedata(fname,val1,val2): #stores data in a .csv file, will update if required def plotgraph(): #method for plotting data in a matplotlib graph, will update if required #codes as part of main execution + function calls print("------Reading collection starts now------") …
- 
        Django - prefetch query - Cannot find set on object, invalid parameterIm trying to prefetch a mapping table based on a mapping table. How does prefetch link tables together? as the foreign key for circuits is the same in both tables, im not sure why they wouldn't join? circuits = SiteCircuits.objects.all() \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related('circuitnotes_set') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitfiles') \ .prefetch_related('circuit__provider') \ .prefetch_related('circuit__service_contacts') \ .prefetch_related('circuit__circuit_type') models are as such: class SiteCircuits(models.Model): site = models.ForeignKey(SiteData, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuits, on_delete=models.CASCADE) site_count = models.IntegerField(verbose_name="How many sites circuit is used at?", blank=True, null=True) active_link = models.BooleanField(default=False, verbose_name="Active Link?") class Meta: verbose_name = "Site Circuits" verbose_name_plural = "Site Circuits" unique_together = ('site', 'circuit',) class CircuitNotes(models.Model): circuit = models.ForeignKey(Circuits, on_delete=models.CASCADE) notes = models.ForeignKey(Notes, on_delete=models.CASCADE) class Meta: verbose_name = "Circuit Notes" verbose_name_plural = "Circuit Notes " unique_together = ('circuit', 'notes',) Ive also tried adding a QuerySet filter to match the circuit id's but the variable circuit_id doesnt exist, im not sure if I can filter based on an object id in this manner? circuits = SiteCircuits.objects.all() \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related( Prefetch( 'circuitnotes_set', queryset=CircuitNotes.objects.filter(circuit_id=circuit_id) ) ) \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitfiles') \ .prefetch_related('circuit__provider') \ .prefetch_related('circuit__service_contacts') \ .prefetch_related('circuit__circuit_type')
- 
        DRF tying to save image give error "The submitted data was not a file"this is django rest framwork project. im trying to create new product that contain a image. i used FileField for image in model ...im sending data to server by POST method . you can see request payload below.. you can see image that is sending is File but why it not save and give my error 400 with error: {image: ["The submitted data was not a file. Check the encoding type on the form."]} ? i tried enctype="multipart/form-data" too but no diffrent { full_description:"<p>asdasdasd</p>" image:File(2835) {name: "php.png", lastModified: 1520497841095, lastModifiedDate: Thu Mar 08 2018 12:00:41 GMT+0330 (+0330), webkitRelativePath: "", size: 2835, …} mini_description:"dasdasdasd" price:"222" title:"asdsadasds" video_length:"233" video_level:"pro" you_learn:"asdasdasd" you_need:"asdasdasd" } and server say : {image: ["The submitted data was not a file. Check the encoding type on the form."]} image : ["The submitted data was not a file. Check the encoding type on the form."] my view: class StoreApiView(mixins.CreateModelMixin, mixins.UpdateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer permission_classes = [IsAuthenticatedOrReadOnly] def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(mini_description__icontains=query) | Q(full_description__icontains=query) ).distinct() return qs def perform_create(self, serializer): serializer.save(author=self.request.user) def post(self, request, *args, **kwargs): if request.method == 'POST': file_serial = ProductSerializer(data=request.data) …
- 
        Add field dynamically in django formImage of the form In the Service Provided field, I want to add more text box dynamically,when the user wants to add more than one service name. How to achieve that? models.py from django.db import models from django.contrib.auth.models import User class CustomerProfile(models.Model): customer_username = models.ForeignKey('auth.User') first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) organisation_name = models.CharField(max_length=20) website = models.URLField() office_address = models.CharField(max_length=200) service_provided = models.CharField(max_length=100) contact = models.IntegerField() city = models.CharField(max_length=20) state = models.CharField(max_length=20) zip_code = models.IntegerField() number_of_employee = models.IntegerField() establishment_year = models.IntegerField() number_of_project_done = models.IntegerField() def __str__(self): return self.organisation_name forms.py from django import forms from .models import CustomerProfile class CustomerProfileForm(forms.ModelForm): class Meta: model = CustomerProfile fields = '__all__' exclude = ('customer_username',)
- 
        how to download the file from remote computer to local computer using winrmActually I have a requirement of download the folder from remote desktop to local desktop using winrm using python so can you suggest some ways how to achieve it
- 
        How to persist range control value on page reloadI have a Django application in which I want to persist range control value on page reload. At the moment on every page reload its value is getting reset to the default. I know HTTP is a stateless protocol and consider every request as new, So we have to find some way to store range value in a cookie or something like that and then retrieve it from clients machine on page reload somewhat like this. Can anybody show me the right direction, thanks in advance. <div class="slidecontainer"> <input type="range" min="1" max="100" value="50" class="slider" name="myRange" id="myRange"> </div>
- 
        django rest framework: allow any user can edit any data (remove object_permission)I am using django rest framwork's "viewsets.ModelViewSet" to list,create,update and delete table rows. For the following Tasks model it works fine. But it only allows to list,create,update and delete of self entries (ie, resource owner) or the user should be superuser. I want to make this api to other users can view and modify the delete regardless of the creator. In simple words, all authenticated user can view/edit anyones entries. Is there any way to do this? views.py class TasksViewSet(viewsets.ModelViewSet): queryset = Tasks.objects.all() serializer_class = TaskSerializer filter_backends = (filters.SearchFilter, filters.OrderingFilter) settings.py REST_FRAMEWORK = { 'DATETIME_FORMAT': "%m/%d/%Y %H:%M:%S", 'DATE_FORMAT': "%m/%d/%Y", 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 50, 'EXCEPTION_HANDLER': 'app_utils.utils.custom_exception_handler', 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), }
- 
        IntegrityError at /normalsignup/ NOT NULL constraint failed: polls_user.usertypeI have seen that there are other people having this issue as well as me, but having tried all of these solutions none of them appear to be helping. I keep getting an error saying: IntegrityError at /normalsignup/ NOT NULL constraint failed: polls_user.usertype Request Method: POST Request URL: http://127.0.0.1:8000/normalsignup/ Django Version: 1.11.6 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: polls_user.usertype Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py in execute, line 328 Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 Python Version: 3.5.2 Python Path: ['/Users/Ethan/mysite', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Users/Ethan/Library/Python/3.5/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages'] I understand that the issue is something to do with one of the fields, but have no idea what, or how to even start to try and fix it. I have copied in the relevant files that I think are necessary to fix this and would really appreciate any help that I can get given for this. Here are my views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404, render, render_to_response, redirect from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from polls.forms import NormalSignUpForm, VenueSignUpForm, BLSignUpForm, BMSignUpForm, ProfileForm from django.contrib.auth import get_user_model from django.views.generic.detail import SingleObjectMixin from django.views.generic import UpdateView, TemplateView from django.utils.decorators import method_decorator from django.db.models.signals import post_save from …
- 
        Django configuration issue with ImportError: No module named django.core.wsgiI know there'a a lot of topic whith this error. I've probably read 90% of these. But no one could fix my issue as each case is kind of specific. I've installed django with pip and I use no virtualenv. My server is dedicated to one website. (Originally I've installed django and its pacakges with the debian package manager but I've tried to remove it to use pip). I've installed mod_wsgi pip install django pip install mod_wsgi pip install requests ... Doing locate mod_wsgi gives me: /usr/lib/apache2/modules/mod_wsgi.so /usr/lib/apache2/modules/mod_wsgi.so-2.7 /usr/local/bin/mod_wsgi-express /usr/local/lib/python2.7/dist-packages/mod_wsgi /usr/local/lib/python2.7/dist-packages/... ... ... my wsgi file looks like: import os import sys # Add the app's directory to the PYTHONPATH sys.path.append('/var/www/NodeSoftware-12.07') sys.path.append('/var/www/NodeSoftware-12.07/nodes') os.environ['DJANGO_SETTINGS_MODULE'] = 'nodes.mecasda.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() but it seems that this last line gives me error in error.log [Thu Mar 08 09:54:27.975249 2018] [wsgi:error] [pid 27810] [client 192.168.13.24:50192] mod_wsgi (pid=27810): Target WSGI script '/var/www/NodeSoftware-12.07/nodes/mecasda/django.wsgi' cannot be loaded as Python module. [Thu Mar 08 09:54:27.975268 2018] [wsgi:error] [pid 27810] [client 192.168.13.24:50192] mod_wsgi (pid=27810): Exception occurred processing WSGI script '/var/www/NodeSoftware-12.07/nodes/mecasda/django.wsgi'. [Thu Mar 08 09:54:27.975286 2018] [wsgi:error] [pid 27810] [client 192.168.13.24:50192] Traceback (most recent call last): [Thu Mar 08 09:54:27.975303 2018] [wsgi:error] [pid 27810] [client 192.168.13.24:50192] File …
- 
        Little explantion of behaviour of web application with and without cookies. Sharing this so others might benefit from this very simple examplefrom django.shortcuts import render count = 0 behaviour of the code without cookies is below everytime a new connection is made by restarting the server count resets. def index(request): global count count += 1 context={'count':count} return render(request,'index.html',context=context) To avoid the above behaviour use any of the below 2 implementation server side cookies implementation and client side cookies. Server side cookies implementation def index(request): visited = request.session.get('visited',0) request.session['visited'] = visited+1 return render(request,'index.html',context={'visited':visited}) Client side cookies implementation. Not considered as a safe practice as server would definitely be more secure than your personal computer. Always try to use this approach def index(request): context = {} visited = 0 resopnse = render(request,'index.html',{'visited':visited}) if 'visited' in request.COOKIES: visited = int(request.COOKIES['visited']) visited += 1 response = render(request,'index.html',{'visited':visited}) response.set_cookie('visited',visited) return response
- 
        Could anyone tell me about the lazy loading and transaction of django?background like this: data = User.objects.get(pk=1) if data.age > 20: with transaction.atomic(): data.age -=2 data.save() I want to know ,if many process do the code at the same time,it like that,each process would get the data at the same time without transaction,for example ,age is 30. then,one process do the next,make age-2=28 and save. Then the next process do,when it do data.age -=2 ,the data get by data. age ,would be 18 or 20? If it is 20,did it means,the transaction add the wrong place? Or it means , the transaction would not work,because the transaction would add to the data do select lines,and can change and save.but the transaction add with out select line? second question: if I do like this: data = User.objects.get(pk=1) with transaction.atomic(): if data.age > 20: data.age -=2 data.save() this demo,add the transaction before the data.age > 20. For the lazy loading,the sql lines would do when I use it ,such as data.age > 20. But when it readly do sql lines,the transction had add before. So, I want to know,did this demo would add transaction on sql lines? thanks a lot,nice people.
- 
        Override widget templates in DjangoI have defined templates in settings.py as following: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'static/html/templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and tree for html/templates is this: when I edit for e.g. change_form.html , the changes are reflected, even when I change any template inside includes that also takes effect. However, when I edit templates inside widgets directory, no changes are reflected. If I edit that inside /django/contrib/admin/templates/admin/widgets that takes effect. How am I supposed to override widgets?
- 
        render video from mongod in django using html5Here is my two errors-> Error : No video with supported format and MIME type found. & Error : 404 inside my requirement.txt file: pkg-resources==0.0.0 django==1.6.5 django-mongokit==0.2.6 pymongo==2.8 I am using Mongokit- python module for Mongodb. DjangoProject files: inside models.py from django_mongokit import connection from django_mongokit.document import DjangoDocument from mongokit import * import datetime connection = Connection() @connection.register class StoreLargeFiles(Document): __database__ = "test2" __collection__ = "largefiles" structure = { "title" : unicode, } gridfs = { 'files': ['source','template'], 'containers':['images'], } inside user.py urlfile from django.conf.urls import patterns, include, url urlpatterns = patterns('DjangoProject.App.views.user', url(r'^[/]$','User',name='User'), url(r'^/showimg/$','showimg',name='showimg'), ) inside user.py viewfile def showimg(request): instance=connection.test2.largefiles.StoreLargeFiles() for f in instance.fs.images.find(): de = f.read() html = '<video width="400" controls><source src="%s" type="video/mp4"></video>' %de return HttpResponse(html)
- 
        error when installing django in virtualenv with dockerfileFROM webdevops/base:ubuntu-16.04 RUN apt-get update && apt-get -y upgrade && apt-get install -y --no-install- recommends \ apache2 \ openssh-client \ python3 \ python3-dev \ python3-venv \ python3-psycopg2 \ python3-pip \ pyflakes3 \ pylint3 \ pep8 \ pep257 \ postgresql-client \ libapache2-mod-wsgi-py3 \ && apt-get clean \ && rm -fr /var/lib/apt/lists/* RUN mkdir /var/www/html/hotels-project RUN cd /var/www/html/hotels-project/ \ && python3 -m venv hotels-venv \ && /bin/bash -c "source hotels-venv/bin/activate" RUN pip install 'django<2.0' RUN pip install requests RUN pip install psycopg2 show message: ERROR: Service 'apache-python' failed to build: The command '/bin/sh -c pip install 'django<2.0'' returned a non-zero code: 127
- 
        deploy django-mysql application to windows server 2012 iisi already deployed my django application to windows 2012 server iis succesfully, it works fine with mysql in local, but it showing error in windows server iis production as raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb i installed python-mysql package, django everything.still i am getting error Thanks
- 
        Install hstore extension for django testsI am trying to install the hstore extension before running django tests. For that, I have overridden the default DiscoverRunner's setup_databases method. However, the extension is not installed & the tests show this error django.db.utils.ProgrammingError: type "hstore" does not exist Here's my code to override the default discover runner. settings.py TEST_RUNNER = 'project.tests.CustomDiscovererRunner' tests.py from django.db import DEFAULT_DB_ALIAS, connections from django.test.runner import DiscoverRunner class CustomDiscovererRunner(DiscoverRunner): def setup_databases(self, **kwargs): result = super().setup_databases(**kwargs) connection = connections[DEFAULT_DB_ALIAS] cursor = connection.cursor() cursor.execute('CREATE EXTENSION IF NOT EXISTS HSTORE') return result
- 
        How to change JSON object structure into JSON Array Structure for highchartsI want to change this JSON object structure [ { "tahun": "2010", "apel": 100, "pisang": 200, "anggur": 300, "nanas": 400, "melon": 500 }, { "tahun": "2011", "apel": 145, "pisang": 167, "anggur": 210, "nanas": 110, "melon": 78 } [ into this JSON Array Structure for my highchart in django, [ ["2010",100], ["2010",200], ["2010",300], ["2010",400], ["2010",500], ["2011",145], ["2011",167], ["2011",210], ["2011",110], ["2011",78] ] or if u have any method like using AJAX it will be very helpful
- 
        ConnectionAborted Error: [WinError 10053] in Django ServiceI am working on Login,Registration of users through my Chrome extension. While registration in the extension, Django service is stopping abruptly and throughing some exceptions and errors. The error Message is as follows: " C:\Users\Anusha\Desktop\DjangoServices>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 08, 2018 - 11:15:04 Django version 2.0.1, using settings 'hello.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [08/Mar/2018 11:15:44] "POST /polls/? HTTP/1.1" 200 21 Traceback (most recent call last): File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [08/Mar/2018 11:15:44] "POST /polls/? HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52297) Traceback (most recent call last): File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\Anusha\AppData\Local\Programs\Python\Python36-32\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File …
- 
        How to I Fix django.utils.datastructures.MultiValueDictKeyError: in djangowhen I try to create a new instance of an Employee I get an error: django.utils.datastructures.MultiValueDictKeyError: "'bio'" When I print this line print(request.data) within the post method in 'EmployeeAddView` class I get: <QueryDict: {'joining_date': ['2018-03-04'], 'designation': ['1'], 'csrfmiddlewaretoken': ['5AeZ7lFOE2Z5j8cPNNZtygh208Esw65tvf5fzka56nCAj1oUFWCR3fcNHuOok2JK'], 'bio.marital_status': ['1'], 'bio.preferred_language': ['English'], 'tax_id_number': ['333333333ed'], 'bio.birthday': ['2018-03-04'], 'bio.user.first_name': ['Jack'], 'department': ['2'], 'bio.user.last_name': ['Sparrow'], 'bio.phone_number': ['9999999'], 'bio.main_id_type_no': ['459opppp'], 'bio.id_type': ['1'], 'bio.gender': ['1'], 'account_number': ['qwwwwwwww3r3']}> Internal Server Error: /hr/employee_add/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'bio' I have this at views.py class EmployeeAddView(generics.CreateAPIView): queryset=Employee.objects.all() serializer_class=EmployeeSerializer def post(self, request, format=None): print(request.data) designation = Group.objects.get(id=self.request.data['designation'],) department = Group.objects.get(id=self.request.data['department'],) bio = Bio.objects.get(id=self.request.data['bio'],) employee = Employee.objects.create( tax_id_number=request.data['tax_id_number'], account_number=request.data['account_number'], joining_date=request.data['joining_date'], designation =designation, department =department, bio=bio, ) return Response(status=status.HTTP_201_CREATED) Then I have created a serializer like this: # Nest Bio With User seriializer class EmployeeSerializer(serializers.ModelSerializer): # TODO: Define serializer fields here bio = BioSerializer() #user = UserSerializer() class Meta: model = Employee # fields = ['user','tax_id_number','account_number','joining_date','designation','department','gender','marital_status','id_type','birthday','ethnicity','preferred_language','phone_number','em_contact','address'] fields = '__all__'
- 
        No 'Access-Control-Allow-Origin' header Javascript and DjangoHere is my Django view @method_decorator(csrf_exempt,name='dispatch') def get_mail_by_id(request): if request.method == 'POST': try: # import pdb;pdb.set_trace() message_id = request.POST['message_id'] email = Email.objects.filter(message_id=message_id) if email.exists(): email = email[0] mail = email.mail_message return JsonResponse({'status':True,'data':mail}) else: return JsonResponse({'status':False,'data':None}) except Exception as e: print e return JsonResponse({'status':False,'data':None}) And here is my POST request $.post('http://127.0.0.1:8000/mail/get_mail_by_id/',{'message_id':message_id}) .done(function(response){ if(response.status){ console.log(response) $('.mail_message').text(response.data) } }); Problem is when I post a request to Django view it runs fine and Django view sends back response but on front end I get the following error: Failed to load http://127.0.0.1:8000/mail/get_mail_by_id/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. I have also added {% csrf_token %} in my jinja template.
- 
        Setting SECURE_HSTS_SECONDS can irreversibly break your site?I'm wanting to implement SECURE_HSTS_SECONDS to my Django settings for extra security - however the warning from the Django docs is making me abit scared so I want some clarification. Here is what is says: SECURE_HSTS_SECONDS Default: 0 If set to a non-zero integer value, the SecurityMiddleware sets the HTTP Strict Transport Security header on all responses that do not already have it. Warning: Setting this incorrectly can irreversibly (for some time) break your site. Read the HTTP Strict Transport Security documentation first. What has to happen for it to "break my site"? I read the HTTP Strict Transport Security documentation first and it didn't make it any clearer.
- 
        Is it possible to automate extraction and inlining of critical css with Django using gulp-critical or webpack?I'm new to programming and I've recently built a website using Django + Bootstrap 4 and was trying to improve my pagespeed on Google SEO Google Page Speed Insights Page Speed Insights suggested using Critical and this led me to discover front-end tools such as Gulp and Webpack. I've read on tutorials on how to use Critical with Webpack here but the problem my django templates are fragmented to keep things organized using {% block content %}. This in turn hinders using the HTML Webpack Plugin + Critical combination to extract the critical css and inline it. Any suggestions or is my only option to manually extract my site's critical css? Hoping for a step-by-step answer or maybe a link to a website to guide me as I am relatively new to all this. Thanks in advance!
- 
        I am getting a module error in my django projectI am building a new django application and for some reason I am getting an error while i am trying access the models from the models.py file from the forms.py file. Here is the error: File "/Users/omarjandali/Desktop/MySplit/mysplit/general/forms.py", line 13, in <module> from models import * ModuleNotFoundError: No module named 'models' Yet I have the general app added to the installed settings. and I have all the models saved. Why is it saying that the module is not there... I am going blank. I know it is a simple answer but for some reason I cant figure it out. here is the forms.py file: # all model imports related to this project from models import * class LoginForm(forms.Form): username = forms.CharField(max_length=20) password = forms.CharField(max_length=20, widget=forms.PasswordInput) here is the models.py file: from django.db import models from django.contrib.auth.models import User, UserManager from localflavor.us.models import USStateField, USZipCodeField # the following is the users profile model class Profile(models.Model): # users basic info user = models.ForeignKey(User, on_delete=models.CASCADE) f_name = models.CharField(max_length=25, default='first') l_name = models.CharField(max_length=25, default='last') bio = models.CharField(max_length=220, default='bio') # users location street = models.CharField(max_length=200, default='street address') city = models.CharField(max_length=100, default='city') state = USStateField(default='CA') zip_code = USZipCodeField(default=12345) # users other profile info phone = models.IntegerField(default="000-ooo-oooo") dob …
- 
        django-wiki: how to list all articles under root articleI am a newbie in Django and am currently building a site. I have downloaded django-wiki ver 0.4a3 to have a wiki app for my site. Everything works fine, out-of-the-box. But instead of showing the root article as the main page, how can I show a list of all articles under the root article, so users can just click on any child article to open up that article? At the moment, users have to click a menu option to browse up one level or to browse at the current level to have a listing of all articles at that given level. I find this rather tedious. I rather have an "Windows Explorer tree-and-branch-like" navigation, e.g., root |_child 1 | |_child 1.1 | |_child 1.2 | |_child 2 | |_child 2.1 | |_child 2.1.1 | |_child 3 Please note I am asking how to get a list all of articles under the root article, not how to create a template to implement the tree-and-branch articles navigator. Once I know how to get a listing of all articles, I think I can implement the necessary HTML and CSS to have that kind of navigator. I appreciate any pointers. P.S. I have previously …
- 
        Loop through items into Django 1.8 templateI have this method: def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList=req.json() userData = {} for data in jsonList: userData['html_url'] = data['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData}) This code looks into an url like this githubtraining As You can see, the response contains lots of repositories, however, not every github user has more than 1 repo. Anyways, on my html view I have this: <div class="table-responsive"> <table class="table table-bordered table-hover table-striped tablesorter"> <thead> <tr> <th class="header"> Url <i class="icon-sort"></i></th> <th class="header"> Created at <i class="icon-sort"></i></th> <th class="header"> Updated at <i class="icon-sort"></i></th> <th class="header"> Forks count <i class="icon-sort"></i></th> </tr> </thead> <tbody> {% for key in data %} <tr> <td>{{ key.html_url }}</td> <td>{{ key.created_at }}</td> <td>{{ key.updated_at }}</td> <td>{{ key.forks_count }}</td> </tr> {% endfor %} </tbody> </table> </div> What happens then? Well, right now, if, for instance, I query the githubtraining user to see it's repos, it shows only the last one, on that and every other user, so, what am I doing wrong here? The loop is there, what am I missing?