Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I am trying to run django development server (using command line),I get following error traceback:
My system is: Ubuntu16.04. Python version: 3.5.2 Django version: 2.0.2 root@nanlyvm:/home/mydj/mysite# python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fbb791cd1e0> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/mydj/mysite/mysite/urls.py", line 22, in <module> url(r'^blog/',include('blog.urls', namespace='blog', app_name='blog')), TypeError: include() got an unexpected keyword argument … -
Passing field from extended user model to template in Django
I am having an issue passing a field from an extended user model to a template in Django. I defined the extended user fields in a model in a new app called user_management: #user_management/models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class lab_user(models.Model): user = models.OneToOneField(User) personal_order_list_url = models.URLField("Personal order list URL", max_length=255, blank=False, unique=True) abbreviation_code = models.CharField("Abbreviation code", max_length=3, blank=False, unique=True) def save(self, force_insert=False, force_update=False): self.personal_order_list_url = self.personal_order_list_url.lower() self.abbreviation_code = self.abbreviation_code.upper() super(lab_user, self).save(force_insert, force_update) I then registered the new fields in admin.py: #user_management/admin.py from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import lab_user class lab_user_inline(admin.StackedInline): model = lab_user can_delete = False verbose_name_plural = 'Additional Fields' class UserAdmin(BaseUserAdmin): inlines = (lab_user_inline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) I can see the new fields in "Authentication and Authorization", which I guess means I've done everything "right". When I try to call fields from a template using {{ request.user.x }} where x could be first_name, personal_order_list_url or abbreviation_code, I can retrieve the desired value for first_name and personal_order_list_url, but not for abbreviation_code. If request.user.personal_order_list_url works, request.user.abbreviation_code should work too, shouldn't it? -
Language Option in Django Html
i am developing A web application using (Django ,Html5,css)in pycharm.i want to add language option top of my webpage where three link shown (ENG FI SVK).user can click on of these and page will translate into that language.like this website:https://danskebank.fi .how can i do that...i am very new in django ,trying to learn thanks -
Django : AttributeError: 'str' object has no attribute 'strftime'
This is my code: signals.py from record.models import Record person1Age = record.person1Age person1AgeFormat = person1Age.strftime('%d-%m-%Y') print(person1AgeFormat) Result in Django Console: person1AgeFormat = person1Age.strftime('%d-%m-%Y') AttributeError: 'str' object has no attribute 'strftime' The same code works fine in the python3 shell. This problem only occurs in my Django Signal. Should I import something else specific to Django? -
Django :There is no unique constraint matching given keys for referenced table"
There are countless questions related to this error, but after over a month I've still not been able to solve this problem, since in my setup there is in fact a unique constraint. I have already asked this question before, but the answer was to add a unique field to my model which IS already present. I'm running an older django version, 1.7.11, and circumstances do not allow me to upgrade. I have a Photo class, which contains multiple foreign keys to other classes. class Photo(UserBase): """ Photograph """ scene_category = models.ForeignKey( SceneCategory, related_name='photos', null=True, blank=True) artist = models.ForeignKey( Artist, related_name='photos', null=True, blank=True) gallery = models.ForeignKey( Gallery, related_name='photos', null=True, blank=True) The inheritance for UserBase class UserBase(ModelBase): #: User that created this object user = models.ForeignKey(UserProfile) class Meta: abstract = True ordering = ['-id'] class ModelBase(EmptyModelBase): """ Base class of all models, with an 'added' field """ added = models.DateTimeField(default=now) class Meta: abstract = True ordering = ['-id'] class EmptyModelBase(models.Model): """ Base class of all models, with no fields """ def get_entry_dict(self): return {'id': self.id} def get_entry_attr(self): ct = ContentType.objects.get_for_model(self) return 'data-model="%s/%s" data-id="%s"' % ( ct.app_label, ct.model, self.id) def get_entry_id(self): ct = ContentType.objects.get_for_model(self) return '%s.%s.%s' % (ct.app_label, ct.model, self.id) class Meta: … -
Django url parameters prevent download exported excel file
I have a url like this: " http://localhost:8001/browse/4/766821590082433/" and when i click the button to download excel file my url gets : "http://localhost:8001/browse/4/766821590082433//export/xls/". In my urls.py url(r'export/xls/$', main.export_users_xls, name='export_users_xls') but when I pass any other url params like : "http://localhost:8001/browse/4/766821590082433/?earliest=2018-01-10&latest=2018-01-17" I cant download the excel file and url gets updated to : http://localhost:8001/browse/4/766821590082433/?earliest=2018-01-10&latest=2018-01-17/export/xls/ the error I get is unconverted data remains: /export/xls/ Any idea how to fix this in order to download excel data even when url has parameters. -
Django: get() returned more than one items -- it returned 3
I got an error MultipleObjectsReturned: get() returned more than one items -- it returned 3!. I want edit and update an existing record in the database. Below are my model, views and html code. Model.py import datetime from django.db import models from django.utils import timezone class Purchases(models.Model): bottle = models.CharField(max_length=20) bottle_purchased = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now_add=True) bottle_total= models.CharField(max_length=20) transportation_cost = models.CharField(max_length=20) total_cost = models.CharField(max_length=20) class Meta: verbose_name_plural = 'Purchases' def __str__(self): return self.bottle Views function for editing. Views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from .models import Purchases from .forms import PurchasesForm def purchases(request): purchases = Purchases.objects.order_by('date_added') context = {'purchases': purchases} return render(request, 'ht/purchases.html', context) def edit_purchase(request): entry = get_object_or_404(Purchases) purchase = entry.purchase if request.method != 'POST': # Initial request; pre-fill form with the current entry form = PurchasesForm(instance=entry) else: # POST data submitted; process data. form = PurchasesForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('geo_gas:purchases')) context = {'entry': entry, 'purchases': purchases, 'form': form} return render(request, 'geo_gas/edit_purchase.html', context) edit_purchase.html <form action="{ url 'geo_gas:edit_purchase' %}" method='post'> {% csrf_token %} {{ form.as_p}} <button name="Submit">save changes</button> </form> Attached is the returned error. get() returned more than one items -- it returned 3! enter image description here -
Django rest framework combine/nested serializer
I have 2 table, appointment and schedule. schedule has these field: scheduleid, title, 'starttime', 'endtime', 'date' appointment has these field: id, scheduleid, clinicid, 'time', 'queueNo', 'date' schedule starttime is = appointment time. So is the date When ever a user create a Appointment, it will also create a schedule as u can see on above. I know how to make a nested serializer but what i do not know is. If a schedule hasn't been created, what do i insert the scheduleid in the appointment table. Reason is because, create appointment first, how to create so that in appointment django know how to create a scheduleid for it ? -
Django Admin prefetch not working - duplicating queries ~1000 times
Ive added a prefetch to django admin as I noticed it was running nearly 1000 queries for a model. However the prefetch seems to have had zero effect. as far as I can see the prefetch query is correct? example duplicate: SELECT "sites_sitedata"."id", "sites_sitedata"."location", "sites_sitedata"." ... FROM "sites_sitedata" WHERE "sites_sitedata"."id" = '7' Duplicated 314 times. 0.09126367597049141% 0.24 Sel Expl Connection: default /itapp/itapp/circuits/models.py in __str__(88) return '%s | %s | %s | %s ' % (self.site_data.location, \ there are also duplicates for, circuit providers, and circuit types glancing at a high level admin.py class SiteSubnetsAdmin(admin.ModelAdmin): search_fields = ['site_data','device_data','subnet','subnet_type','vlan_id','peer_desc'] list_display = ('site_data','device_data','subnet','subnet_type','vlan_id','peer_desc') ordering = ('site_data','device_data',) def get_queryset(self, request): queryset = super(SiteSubnetsAdmin, self).get_queryset(request) queryset = SiteSubnets.objects \ .prefetch_related( Prefetch( 'circuit', queryset=Circuits.objects.prefetch_related('site_data').prefetch_related('service_contacts').prefetch_related('circuit_type').prefetch_related('provider'), ), ) \ .prefetch_related('site_data') \ .prefetch_related('device_data') \ .prefetch_related('subnet_type') return queryset admin.site.register(SiteSubnets, SiteSubnetsAdmin) subnets.models class SiteSubnets(models.Model): device_data = models.ForeignKey(DeviceData, verbose_name="Device", \ on_delete=models.PROTECT, blank=True, null=True) site_data = models.ForeignKey(SiteData, verbose_name="Location", \ on_delete=models.PROTECT, blank=True, null=True) subnet = models.GenericIPAddressField(protocol='IPv4', \ verbose_name="Subnet", blank=True, null=True) subnet_type = models.ForeignKey(SubnetTypes, verbose_name="Subnet Type") circuit = models.ForeignKey(Circuits, verbose_name="Link to circuit?", \ on_delete=models.PROTECT, blank=True, null=True) vlan_id = models.IntegerField(verbose_name="Vlan ID", blank=True, null=True) peer_desc = models.IntegerField(verbose_name="Peer description", blank=True, null=True) class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" def __str__(self): if self.device_data != None: return … -
How to run multi domainname in one django with nginx and uwsgi
I want to use multi domain for one django project one domain name for one app now my project's like this Project - domain/ -> Homepage - domain/appa -> App A - domain/appb -> App B I want to change to www.test.com -> Homepage appa.test.com -> App A appb.test.com -> App B I think I can use nginx virtual host to solve this problem but now I have no idea pleas help me. -
How to prevent a site from allowing its users to provide their own templates
I am developing a web app and in the Django documentation I read this: The template system isn’t safe against untrusted template authors. For example, a site shouldn’t allow its users to provide their own templates. Given the fact that I won't be allowing the end-user to upload any code, I reckon that the above would only be possible if the user would somehow gain access to the server and upload his (malicious) templates or by an XSS attack. Is there something else I am missing here and should be aware of? Are there any additional measures (except for securing my server and looking out for XSS attacks) I must take in order to prevent this from happening? -
Django - django-autocomplet-light fields does not display with gunicorn
dal fields of my app are working perfectly when I use "python manage.py runserver" but when I try to run my app with gunicorn the dal fields are empty (as if I didn't put form.media in my template ...). Except for dal field there is no problems. Is there something to change in the code for dal to work with gunicorn? My code is on github (https://github.com/jmcrowet/limonada/blob/master/limonada/forcefields/forms.py) -
One model interface to read/write to multiple tables Django
I've the following models in Django. class User(models.Model): name = models.CharField(max_length=50) ... ... class UserInformation(models.Model): user = models.ForeignKey(User) key = models.CharField(max_length=250) value = models.TextField() ... ... class UserAddress(models.Model): user = models.ForeignKey(User) address = models.TextField(null=True) city = models.CharField(max_length=200) ... ... Basically I want to create an interface for User through which I can route read and write operations to UserInformation and UserAddress. user = User.objects.get(id=1) Ex - If someone wants to get all addresses of a user. user.get_information('address') --> This will in turn search UserAddress table and return a list of addresses. Ex - If someone wants to get the current age of a user. user.get_information('age') --> This will in turn search UserInformation table with key=age and return the value. Similarly given a key I want to write data through the interface. Ex - Insert age of a user. user = User.objects.get(id=1) user.update_information('age', value=30) --> This will in turn insert a row in UserInformation table with key=age and value=30. Problems: I'm planning to create another table TableKeyMapping to keep the mapping of keys to table names. Such as if key_name=age, table_name=UserInformation. If key_name=address, then table_name=UserAddress. What should I save in table_name..the model name UserAddress or the complete path including the the … -
Django. How to get the object corresponding to a GenericForeignKey
Simple question. I have this model: class Discount(models.Model): discount_target = GenericForeignKey('content_type', 'object_id') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) How do I get the object the GenericForeignKey is pointing? -
How to pass variable value from one view function to another one?
I have a project that I need to pass a value from a function to another. And I have searched so many information on stackoverflow, so many people suggest to use session to pass values.→How to pass data between django views Then I did all what he taught, but it always shows "None" on my website. I am sure that I have already activated 'django.contrib.sessions.middleware.SessionMiddleware', I think this is not the problem. from django.shortcuts import render from django.shortcuts import render_to_response # Create your views here. from django.template.loader import get_template from django.http import HttpResponse from django.db import connection from django.contrib.sessions.models import Session def generic1(request): if request.method=="GET": urn=str(request.GET['username']) psd=request.GET['password'] cursor=connection.cursor() sql="""SELECT password FROM `table1` WHERE `username`=%s""" cursor.execute(sql,(urn)) a=cursor.fetchall() print a[0][0] request.session['value']=str(a[0][0]) def result(request): message=request.session.get('value') return render_to_response('result.html',{'message':message}) result.html <html> <body> {{message}} </body> </html> urls.py from django.conf.urls import url from django.contrib import admin from mainsite import views urlpatterns = [ url(r'^$',views.index), url(r'^admin/', admin.site.urls), url(r'^generic.html',views.generic), url(r'^result.html',views.result), ] -
Django url not resolving in similar case to working one
I know this has been asked a lot but I can't find any answers that are general enough to learn something from them. I setup a Django project for the first time but am a little confused as I have 2 forms on 1 page and they both submit to a different view ('tick' and 'bestel') it does everything it is supposed to do under 'bestel' but then I submit to tick it gives me this error: Using the URLconf defined in Que.urls, Django tried these URL patterns, in this order: 1. [name='index'] 2. signup/ [name='signup'] 3. <int:user_id>/ [name='user'] 4. <int:user_id>/bestel [name='bestel'] 5. <int:user-id>/tick [name='tick'] 6. admin/ The current path, 11/tick, didn't match any of these. where can I be going wrong in this? -
Wagtail: How to filter text in streamfield within model.py
I would like to write a filter which replaces some $variables$ in my streamfield text. What is the best way to do this in my "Page" model? I tried the following but it is sometimes not working if I save my model as draft and publish it afterwards. Does anyone know a better way doing this? class CityPage(Page, CityVariables): cityobject = models.ForeignKey(CityTranslated, on_delete=models.SET_NULL, null=True, blank=True) streamfield = StreamField(BasicStreamBlock, null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('cityobject', classname="full"), StreamFieldPanel('streamfield'), ] def get_streamfield(self): for block in self.streamfield: if type(block.value) == unicode: block.value = self.replace_veriables(block.value) elif type(block.value) == RichText: block.value.source = self.replace_veriables(block.value.source) else: print "notimplemented" return self.streamfield And this is just the class which replaces $variables$ with values from my database. class CityVariables(): def replace_veriables(self, repstr): reprules = self.get_city_context() for key, value in reprules.iteritems(): repstr = repstr.replace(key, value) return repstr def get_city_context(self): context = {} if self.cityobject.population: context['$population$'] = unicode(self.cityobject.population) if self.cityobject.transregion: context['$region$'] = unicode(self.cityobject.transregion) return context -
I don't know how to display my customuser and user in same form
I have 2 models: teacher and student. They both extend User class with a OneToOneField and they both have receivers defined for creation and saving. Now, in my forms I can only display the fields from student or teacher only, the other fields that come with user I don't know how to include them. But I want that a student or a teacher won't be able to create account, unless all fields are filled in. Here are my forms and view: class StudentSignUpForm(forms.ModelForm): class Meta: model = Student fields = ('student_ID', 'photo', 'phone') class TeacherSignUpForm(forms.ModelForm): class Meta: model = Teacher fields = ('academic_title', 'photo', 'phone', 'website', 'bio') class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'student_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index') class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'teacher_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return render_to_response('index.html', {'form': form},) -
ImportError: cannot import name 'users'
I am new to python , I am building djangorestframework API following below tutorial http://www.django-rest-framework.org/tutorial/quickstart/ I have configured Python 3.5 PIP 9.0.1 Django 2.0 tutorial/tutorial/urls.py from django.conf.urls import url, include from django.contrib import users from rest_framework import routers router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^users/', user.site.urls), ] Error : File "/home/pradeep/tutorial/tutorial/tutorial/urls.py", line 18, in from django.contrib import users ImportError: cannot import name 'users' -
How to provide additional data in "PUT" request for update in Django REST Framework?
Here is what I have so far: [serializers.py] class EmployeeSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) user = UserSerializer(required=False) company = serializers.CharField(read_only=True) employee_type = serializers.ChoiceField(choices=EMPLOYEE_TYPES, default='manager') is_blocked = serializers.BooleanField(required=False) def update(self, instance, validated_data): instance.user = validated_data.get('user', instance.user) instance.company = validated_data.get('company', instance.company) instance.employee_type = validated_data.get('employee_type', instance.employee_type) instance.is_blocked = validated_data.get('is_blocked', instance.is_blocked) instance.save() return instance [views.py] class EmployeeDetail(APIView): def get_employee(self, pk): try: return Employee.objects.get(pk=pk) except Employee.DoesNotExist: raise Http404 def put(self, request, pk, format=None): employee = self.get_employee(pk) serializer = EmployeeSerializer(employee, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) [request] http -a admin:password PUT http://localhost:8000/api/employees/list/2/ As a result I am able to update that employee with id=2, but the only thing that I am able to change is "employee_type" cause it has default value = 'manager', and if "employee_type" of that employee with id=2 is let's say "admin" after my request it will become "manager". The problem is that I can't figure out how to add some extra data to my request so I would be able to change "employee_type" to "director" for example, is something like below can be accomplished ? [request_as_I_want] http -a admin:password PUT http://localhost:8000/api/employees/list/2/employee_type='director'/company='some_value'/ Is that can be done, or I misunderstand something ? -
Django Posts not showing on live server
I made a small blog site and is not showing all the items from the database. If i try to see the posts from my phone i see only 3 posts, when in my DB there are 9. When i click on one post i got a Not Found error saying that the requested URL posts/legea etc was not found on server. This is the link that should have all of the posts: http://cohen.ro/posts/ However, if i enter in admin trhourgh site/admin i can see all of the posts in DB and when i go back to the site all of the items are out there and i can read the posts. Can someone, please help me in order to fix this?! thank you! My post List: {% extends "base.html" %} {% load crispy_forms_tags %} {% block head_title %} Blog | {% endblock %} {% block content %} <div class="container-fluid" style="width:91%;color: currentColor;!important;"> <div class="row" id="list_posts" style="background-color: white;padding-top: 40px;"> <br/> <br/> <br> {% for obj in object_list %} <div class="col-sm-4"> <div class="thumbnail"> {% if obj.image %} <img src="{{ obj.image.url }}"/> {% endif %} <div class="caption" style="color:currentColor"> {% if obj.draft %} <h3>Staff Only Draft</h3> {% endif %}{% if obj.publish > today %}<h3>Staff … -
How to use PostgreSQL ArrayAgg function on a grouped by query set in Django ORM?
To keep it simple I have four tables(A, B, Category and Relation), Relation table stores the Intensity of A in B and Category stores the type of B. A <--- Relation ---> B ---> Category I am trying to eliminate joins in my query to reduce calculations time using PostgreSQL's ArrayAgg and indexing feature of the database based on this gist. (Since there are 18000 relations, 4000 Bs, and 1500 categories my calculations of each report would take almost two hours) and the error I get is: psycopg2.ProgrammingError: aggregate functions are not allowed in GROUP BY LINE 1: ... U0."id", U2."B" HAVING U0."id" = ANY((ARRAY_AGG(... I have used Brad Martsberger solution to my previous question to calculate sum of each A's intensity occurred in B grouped by B's categories, Minimum and Maximum of calculated Intensity-sums in each category of B and the rate of occurrence of each A in each B category and the occurrence of B itself in that category : annotation0 = { 'SumIntensity': Sum('ARelation__Intensity'), 'A_Ids': ArrayAgg('id') } annotation1 = { 'BOccurrence' : Count('id', distinct=True), } sub_filter0 = Q(id__any=OuterRef('A_Ids')) sub_filter1 = Q(Category_id=OuterRef('ARelation__B__Category_id')) subquery0 = A.objects.filter(sub_filter0).values('id','ARelation__B__Category_id').annotate(**annotation0).order_by('-SumIntensity').values('SumIntensity')[:1] subquery1 = A.objects.filter(sub_filter0).values('id','ARelation__B__Category_id').annotate(**annotation0).order_by('SumIntensity').values('SumIntensity')[:1] subquery2 = B.objects.filter(sub_filter1).values('Category_id').annotate(**annotation1).values('BOccurrence')[:1] result = A.objects.values( 'id','id','ARelation__B__Category_id' ).annotate( **annotation0 ) … -
Django Ubuntu 16.04 "unsupported hash type"
I've deployed a web app to an Ubuntu 16.04 VM. I implemented the standard Django login by the books. Everything is working properly on my production environment (OS X); however, when I attempt to login I receive the error ExceptionValue: unsupported hash type Ubuntu is running python 3.5.2 OS X is running python 3.6.1 Both are running Django Version 1.11.6 My requirements.txt blessings==1.6 bpython==0.16 certifi==2017.7.27.1 chardet==3.0.4 curtsies==0.2.11 Django==1.11.6 django-extensions==1.9.6 geopy==1.11.0 greenlet==0.4.12 idna==2.6 psycopg2==2.7.3.2 Pygments==2.2.0 pytz==2017.2 requests==2.18.4 six==1.11.0 urllib3==1.22 wcwidth==0.1.7 I am using a virtual environment to run this project. The traceback path is as follows, Traceback: File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/views.py" in inner 54. return func(*args, **kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/contrib/auth/views.py" in login 150. )(request) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/home/user_name/proj_folder/my_venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File … -
How to read response header from upstream server in nginx
I wanted to read the custom header and proxy the request to some gateway server. My configurations: location /route { proxy_set_header User $upstream_http_user; proxy_set_header Authorization ""; proxy_pass http://127.0.0.1:3000/postdata/; proxy_method POST; } upstream server code: response = Response() response['User'] = str(user.username) response['X-Accel-Redirect']='/route' return response -
postgresql - django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "host_name" (XX.XX.XX.XX) and accepting TCP/IP connections on port 5432? typical error message while trying to set up db server. But I just cannot fix it. my django db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_pwd', 'HOST': 'host_name', 'PORT': '5432', } } I added to pg_hba.conf host all all 0.0.0.0/0 md5 host all all ::/0 md5 I replaced in postgresql.conf: listen_addresses = 'localhost' to listen_addresses = '*' and did postgresql restart: /etc/init.d/postgresql stop /etc/init.d/postgresql start but still getting the same error. What interesting is: I can ping XX.XX.XX.XX from outside and it works. but I cannot telnet: telnet XX.XX.XX.XX Trying XX.XX.XX.XX... telnet: connect to address XX.XX.XX.XX: Connection refused telnet: Unable to connect to remote host If I telnet the port 22 from outside, it works: telnet XX.XX.XX.XX 22 Trying XX.XX.XX.XX... Connected to server_name. Escape character is '^]'. SSH-2.0-OpenSSH_6.7p1 Debian-5+deb8u3 If I telnet the port 5432 from inside the db server, I get this: telnet XX.XX.XX.XX 5432 Trying XX.XX.XX.XX... Connected to XX.XX.XX.XX. Escape character is '^]'. same port from outside: telnet XX.XX.XX.XX 5432 Trying XX.XX.XX.XX... telnet: connect to address XX.XX.XX.XX: Connection refused telnet: Unable to connect to remote host …