Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Como filtrar ModelMultipleChoiceField baseado em outro campo? / How to filter a ModelMultipleChoiceField based on another field?
Based on the form below, I would like to know If Is there a way (or a plugin) to use the field tipo_indicador to filter indicadores field: Baseado no form abaixo, gostaria de saber se existe alguma forma (ou plugin) de utilizar o field tipo_indicador para filtrar o field indicadores: tipo_indicador = forms.ModelChoiceField( queryset=TipoIndicador.objects.all(), label=u'Tipo de indicador', required=False, ) indicadores = forms.ModelMultipleChoiceField( label= _(u'Indicadores'), required=False, queryset=Indicador.objects.all(), widget=admin_widgets.FilteredSelectMultiple(verbose_name=_(u'indicadores'), is_stacked=False) ) -
Best way to refresh graph without page refresh (Python Django, ajax)
A bit of a general question - I am looking for ways to refresh a graph on a Django page based on user choices. The page has a graph, a few drop boxes where you can select parameters and a refresh button. Currently, I can capture the selections via ajax to my Django view and generate new data from database for the graph. I now need to feed that newly-generated data back into the graph and refresh it without a page refresh. Could anyone recommend the best methods of doing this? -
Convert template layout into crispy forms layout
I am currently trying to convert a django template that I have been using into a django-crispy-forms Layout. I am having some problems doing this as I want to do it on an inline formset that is currently being made with django-extra-views. I have attempted to do this but have not got the desired result so far, and the docs on this subject aren't exceedingly helpful (in my opinion). I have had no problems with changing my other form layouts to use crispy forms just the formsets. Currently, my template looks like this: <div class="col-md-8 col-lg-8"> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <div id="formset"> <div class="alert alert-info" role="alert"> Field names <strong>must</strong> be unique. </div> {{ field_inline.management_form }} {{ field_inline.non_form_errors }} {% for form in field_inline.forms %} {{ form.non_form_errors }} <div id="{{ field_inline.prefix }}-forms"> <div class="form-inline"> {% for field in form.visible_fields %} <div class="form-group"> <label for="{{ field.id_for_label }}" class="form-control-label m-2 requiredField"> {{ field.label }} <span class="asteriskField">*</span> </label> {{ field|add_class:"form-control" }} {{ field.errors }} </div> {% endfor %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} </div> </div> {% endfor %} </div> <hr> <button class="btn btn-primary pull-right ml-1" type="submit">{% trans "Next" %}</button> <a class="btn btn-light … -
Open RDP in Web page or with X11 forwarding
i'am building a bastion server so the user can connect over the bastion server over ssh then he will connect to allowed_hosts however there is hosts that uses RDP sessions so can we use RDPY secript over Forwarding X11 ?? if the answer is yes please help tell me how ? either how can we implement the RDPY script over a django web application ? -
__str__ returned non-string (type list)
I am having a django app in which I am storing the json variable.I have stored the json variable through admin and I am trying to print it in shell.My main aim is to pass this variable to a webpage with ajax method.But first when I was trying to print it in shell I get this error __str__ returned non-string (type list) My models.py is of this form from django.db import models from django.utils import timezone from jsonfield import JSONField # Create your models here. class newgrid(models.Model): data = JSONField() def __str__(self): return self.data My JSON variable is of this form [{"col":1,"row":1,"size_x":1,"size_y":1},{"col":2,"row":1,"size_x":1,"size_y":1},{"col":3,"row":1,"size_x":1,"size_y":1},{"col":4,"row":1,"size_x":1,"size_y":1},{"col":1,"row":2,"size_x":1,"size_y":1},{"col":2,"row":2,"size_x":1,"size_y":1},{"col":3,"row":2,"size_x":1,"size_y":1},{"col":4,"row":2,"size_x":1,"size_y":1},{"col":1,"row":3,"size_x":1,"size_y":1},{"col":2,"row":3,"size_x":1,"size_y":1},{"col":3,"row":3,"size_x":1,"size_y":1},{"col":4,"row":3,"size_x":1,"size_y":1},{"col":5,"row":1,"size_x":1,"size_y":1}] In shell I ran following commands from testforweb.models import newgrid newgrid.objects.all() It initially returned this <QuerySet [<newgrid: newgrid object (1)>]> But then I added def __str__(self): return self.data Just to see the actual JSON variable.But I am getting the error How to see the actual JSON variable which I inserted through admin coz I need to send it to webpage as it is -
TypeError: ufunc 'ndtri' not supported for the input types
Internal Server Error: /reports/rschighlevel/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/pulsedev2/prod/pulse.corp.uber.internal/ats/reports/views.py", line 167, in rschighlevel print norm.ppf(a) File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 1514, in ppf place(output, cond, self._ppf(*goodargs) * scale + loc) File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 2187, in _ppf return _norm_ppf(q) File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 2133, in _norm_ppf return special.ndtri(q) TypeError: ufunc 'ndtri' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Code : from scipy.stats import norm from scipy.special import ndtri import pdb sigma = [] for i in usigma: a = (1-i[6]) print type(a) print norm.ppf(a) - Error Line sigma.append([i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7], a]) print sigma -
How to access the value from select2 in django
I'm a beginner in this.I have a select2 plugin with multiple inputs.I want to get all the option values when submitted as an array (to query in views.py). for eg: [2,134,4,65] template <div class="col-sm-9"> <h1>Hello {{user.first_name}} {{user.last_name}}....</h1> <h4>Please Specify Your Symptoms</h4> <select class="js-example-basic-multiple" name="states[]" multiple="multiple" style="width:300px"> {% for sym in all_symptoms %} <option value={{sym.syd}}>{{sym.symptoms}}</option> {% endfor %} </select> <button type="submit" class="btn btn-success">Submit</button> </div> <script> $(document).ready(function() { $('.js-example-basic-multiple').select2(); }); </script> views.py -
CRFS token problems consuming django-oauth-toolkit
I deployed a Django OAuth Toolkit Oauth2 provider following the official tutorial https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_01.html I set the callback URI pointed to the next Django view and I try to retrieve some user information form the oauth server using an ad-hock view decorated with Login_required. This is the callback view. class OauthLoginView(View): def get(self, request, *args, **kwargs): code = request.GET["code"] next = kwargs.get("next", reverse('home')) URI = "http://" + request.META['HTTP_HOST']+reverse('oauth') # Ask /me from auth.deusto.io r = PM.request(method='post', url="http://auth/o/authorize/", fields={ "grant_type": "authorization_code", "client_id": "lololo", "client_secret": "lalala", "code": code, "redirect_uri": URI, "csrftoken": request.COOKIES['csrftoken'] }) r = PM.request(method='get', url="http://auth.deusto.io/api/me", headers={ "Authorization": r.data["token_type"] + r.data["access_token"] }) if r.status == 200: me = r.data["object"] try: user = User.objects.get_by_natural_key(me.username) except ObjectDoesNotExist as ex: user = User(username=me.username) login(request, user) return redirect(next) return HttpResponse(content=r.data, status=r.status) This is the View from the Oauth serve: class MeView(View): def get(self, request, *args, **kwargs): if request.user.is_authenticated: self.me = request.user context = {"username": self.me.username} return self.render_to_response(context) else: return HttpResponseForbidden("Not logged") def render_to_response(self, context, **response_kwargs): return JsonResponse(context) I call to the Oauht server and try to get the access token thorough sending the code received from the callback. I get a error from CsrfViewMiddleware. Althought I send the csrf token and I set CORS_ORIGIN_REGEX_WHITELIST in the … -
Clarity on Setting up Docker containers for django projects?
I'm experimenting with docker and have some basic hands-on with it. I would like to know how to structure the containers to scale in a better way. Auth Container - Using Auth0 for Authentication only. With JWT for authentication Profile Container- A python app to store user profile along with MongoDB as a database. I prefer keeping this in a separate container because it will not be used much as the other services. Blog Container- This is another python app that allows users to write/edit articles and uses the same MongoDB as the profile container. My Question is how two different python apps share the authentication from the auth container. I have developed similar monolithic apps with Django, but as a single project. I would like to do the same but both the profile and blog as different projects itself. What kind of Structure should I follow to implement such projects? -
Django form is still full after sign up
I have an app in django 1.11. Below is the view with the form where the user can sign up for the event, after saving he gets a message about the details - on the same page, at the same url. But, after saving the form is completed and after pressing F5 the next saving is performed. How can I avoid this? I think something with the form_valid method is wrong. class EventDetailView(DetailView, CreateView): model = models.Event form_class = forms.ParticipantForm context_object_name = 'event' template_name = 'events/event_detail.html' def get_success_url(self): return reverse('events:detail', kwargs={'slug': self.kwargs['slug'], 'pk': self.kwargs['pk']}) def form_valid(self, form): self.object = form.save() context = self.get_context_data() context['registered_event'] = context['event'] return self.render_to_response(context) -
Why shouldn't you use PHP within Django? [on hold]
I have seen in several websites people saying it is a really bad idea to mix PHP scripts within a server running Django. Plus, it is (apparently) a quite hard thing to do. Still, I don't understand why. Although I get that both run on server side I do not understand why you shouldn't use some PHP if there's anything you think would work better than python (or you just feel like using it). So, can/should you use PHP in a python server using Django? How and why? Thank you <3 -
Can i read a django file object straight into pandas dataframe?
I want to load a simple \t separated file into a pandas dataframe that I have loaded using django: views.py if request.method == 'POST': files = request.FILES.getlist('file_field') for f in files: df = pd.read_csv(f, sep='\t') -
Unable to install hiredis on Windows server 2012
As the title says, when trying with PowerShell as the library is required by my django project. command used : pip install hiredis installed on system : visual studio 2015 (for C compiler), .NET Framework 4.5., 4.6., Microsoft visual C++ 2012, 2013, 2015, WIndows 10 SDK, python 3.5.2, Python Launcher, winrar? The full error : PS C:\Programs\XAMPP\htdocs\mySiteProject> pip install hiredis Collecting hiredis Using cached hiredis-0.2.0.tar.gz Installing collected packages: hiredis Running setup.py install for hiredis ... error Complete output from command c:\users\administrator\appdata\local\programs\python\python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\pip-build-tx0pbghm\\hiredis\\setup.py';f=ge tattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec '))" install --record C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-4bydtxdv-record\install-record.txt --single-version-ext ernally-managed --compile: running install running build running build_py creating build creating build\lib.win-amd64-3.5 creating build\lib.win-amd64-3.5\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.5\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.5\hiredis running build_clib building 'hiredis_for_hiredis_py' library error: Unable to find vcvarsall.bat ---------------------------------------- Command "c:\users\administrator\appdata\local\programs\python\python35 \python.exe -u -c "import setuptools, tokenize; __file__='C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\pip-build-tx0pbghm\\hiredis\\setup.py';f=getattr(tokenize, 'open',open)(__file__); code=f.read().replace('\r\n', '\n');f.close(); exec(compile(code, __file__, 'exec'))" install --record C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-4bydtxdv-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-build-tx0pbghm\hiredis\ -
How do I save a cv2 processed image to django models?
I use opencv to crop images and I'd like to save them to the models, I load the file directly to computeLogoFromMemoryFILE where it is processed, from there how can I save the image to TempImage model? views.py: form = myForm(request.FILES) if form.is_valid(): cropped_image = computeLogoFromMemoryFILE(request.FILES.get('logo')) # ... temp_image = TempImage.objects.create(image=?) cv2: # (np == numpy) def computeLogoFromMemoryFILE(logo): logo.seek(0) image = cv2.imdecode(np.fromstring(logo.read(), np.uint8), cv2.IMREAD_UNCHANGED) cropped_img = crop_image(image) cropped_image variable is a numpy array : array([[ 52, 218, 255], [ 52, 218, 255], [ 52, 218, 255], ..., [ 52, 218, 255], [ 52, 218, 255], [ 52, 218, 255]]...], dtype=uint8) How should I proceed? -
can we use curdoc() in django
I want to achieve live graph in django using bokeh. I tried many ways but nothing has worked out for me. I got a code which is working fine as normal bokeh serve but not working in django. can anyone help me in this? I got stuck almost a week. code is below: import numpy as np from bokeh.client.session import push_session from bokeh.layouts import column from bokeh.models import Button from bokeh.palettes import RdYlBu3 from bokeh.plotting import figure, curdoc import pandas as pd import random from bokeh.embed import components # create a plot and style its properties p = figure(x_axis_type="datetime", title="EUR USD", plot_width=1000) p.grid.grid_line_alpha = 0 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.ygrid.band_fill_color = "olive" p.ygrid.band_fill_alpha = 0.1 # p.border_fill_color = 'black' # p.background_fill_color = 'black' # p.outline_line_color = None # p.grid.grid_line_color = None # add a text renderer to out plot (no data yet) r = p.line(x = [], y = [], legend='close', color='navy') s = p.triangle(x = [], y = [], legend='sell', color='red' ,size=10 ) t = p.triangle(x = [], y = [], legend='buy', color='green' ,size=10 ) # r = p.text(x=[], y=[], text=[], text_color=[], text_font_size="20pt", # text_baseline="middle", text_align="center") i = 0 dr = r.data_source ds = s.data_source dt = … -
Showing sensor reading in a django website
I 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 parameter
Im 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 form
Image 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 winrm
Actually 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 reload
I 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.usertype
I 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.wsgi
I 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 example
from 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