Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx 104: Connection reset by peer while proxying upgraded connection
nginx: *106 recv() failed (104: Connection reset by peer) while proxying upgraded connection, For my chat on django 1.11, I use django-channels, duphne, nginx and nginx to fill in the log with this error. Because of this I can not keep track of who has the socket open. duphne start command: daphne -b 0.0.0.0 -p 8001 .asgi:channel_layer help me to fix this please server { listen 80; server_name <server_name>; access_log /path/to/log/access-nginx.log; error_log /path/to/log/error-nginx.log; client_max_body_size 20M; location / { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /static { root /static/path; } location /media { root /media/path; } } -
Django - Save variable to CharField
I want to save a variable to CharField in my models.py. Here is some code: models.py class Profile(models.Model): user = models.OneToOneField(User, related_name='user') oceny = models.CharField(max_length=150, default='') updated = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username Here is my variable oceny = lib.oceny_skon and the result of it: [1, 4, 5.75, 2] How can I save this to oceny field ? Thanks for help ! -
Unresolved Reference in view.py when calling from model.py in Django
Im just trying to learn Django and i've just been following youtube tutorials but i've encountered a problem when i was making a basic web app. Here's the code from views.py from django.http import HttpResponse from .models import machine def equipment_index(request): all_machines = machine.objects.all() html='' for machine in all_machines: url='/equipment/' + str(machine.id) + '/' html+='<a href="'+url+'">'+machine.name+'</a><br>' return HttpResponse(html) def detail(request, machine_id): return HttpResponse("<h2>Details for machine id: "+ str(machine_id)+"</h2>") And this is the code from models.py from django.db import models # Create your models here. class machine(models.Model): brand = models.CharField(max_length=20) name = models.CharField(max_length=50) acquisition_cost = models.DecimalField(max_digits=12, decimal_places=2) details = models.CharField(max_length=2000) TYPE_CODES = ( ('AC', 'Air Compressor'), ('BL', 'Backhoe Loader'), ('BR', 'Breaker'), ('BD', 'Bulldozer'), ('OT', 'Other'), ) type = models.CharField(max_length=2, choices=TYPE_CODES) def __str__(self): return self.name + ' - ' + self.brand There is an 'Unresolved Reference' under 'machine' in machine.objects.all() I followed everything in the tutorial videos exactly but it still has an error -
Enable search in modelviewset django
How do I enable search in this modelviewset? class AuthorViewSet(viewsets.ModelViewSet): queryset = models.Author.objects.all() serializer_class = serializers.AuthorSerializer permission_classes = [CreatePutDeleteAdminOnly] pagination_class = StandardResultsSetPagination filter_backends = (SearchFilter, DjangoFilterBackend, OrderingFilter) ordering = ('-pk',) search_fields = ('title',) I want 127.0.0.1:8000/api/v1/category/?search=j to return only the categories that start with j. -
django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
when I used command "python manage.py makemigrations"(the same with typing "python manage.py runserver"),it threw this error.And then I checked the authority of the users. The code and result are as fllows. mysql> select host,user from mysql.user; +-----------+---------------+ | host | user | +-----------+---------------+ | % | root | | % | zhuxin | | localhost | mysql.session | | localhost | mysql.sys | | localhost | root | | localhost | zhuxin | +-----------+---------------+ mysql> show grants for 'zhuxin'@'%'; +---------------------------------------------------------------+ | Grants for zhuxin@% | +---------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'zhuxin'@'%' WITH GRANT OPTION | | GRANT ALL PRIVILEGES ON `blogdb`.* TO 'zhuxin'@'%' | +---------------------------------------------------------------+ mysql> show grants for 'root'@'%'; +--------------------------------------------------+ | Grants for root@% | +--------------------------------------------------+ | GRANT USAGE ON *.* TO 'root'@'%' | | GRANT ALL PRIVILEGES ON `blogdb`.* TO 'root'@'%' | +--------------------------------------------------+ I have tried everything to solve it, but for no use. -
History Of Django Naming
Why Django web framework described as “developed in a newsroom”. Is it because the project was started at Lawrence Journal-World newspaper in 2003? and then why it is named as Django (name of guitarist)? -
Django & Socket Server: Can I add socket server instance to "memory"?
I'm working with: Django 1.11 Python Sockets I have a Socket server like this: class SocketServer(threading.Thread): def __init__(self, ip="127.0.0.1", port=5000, _buffer=1024): super(RoomSocketServer, self).__init__() self.IP = ip self.PORT = port self.RECV_BUFFER = _buffer # Advisable to keep it as an exponent of 2 self.CONNECTION_LIST = [] # list of socket clients self.MESSAGE_QUEUES = {} # List of message queue by socket self.OUTPUTS = [] self.SERVER = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # this has no effect, why ? self.SERVER.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.SERVER.bind((self.IP, self.PORT)) self.SERVER.listen(10) # Add server socket to the list of readable connections self.CONNECTION_LIST.append(self.SERVER) self.ROOM = Room.objects.create(port=port, ip=ip, type_room=type_room) def read_sockets(self, read_sockets): ''' ... ''' def write_sockets(self, write_sockets): ''' ... ''' def error_sockets(self, error_sockets): ''' ... ''' def run(self): while 1: # Get the list sockets which are ready to be read through select read_sockets, write_sockets, error_sockets = select.select(self.CONNECTION_LIST, self.OUTPUTS, []) # Read sockets self.read_sockets(read_sockets) self.write_sockets(write_sockets) self.error_sockets(error_sockets) self.SERVER.close() I can run this SocketServer like this anywhere on Django (custom_command, a view, celery...): from socket_server import SocketServer socket_server = SocketServer() socket_server.start() # And the code continues while the socket server is running # I would like to save socket_server instance anywhere to access # Later from anywhere or trigger a signal to finish it … -
How to set python3 in Django?
I would like to know how to setup Django with Python3.X All of my Django Projects was in python2.X taken by system default.. I knew in Django 2.0 onwards, Django will going to support only Python3 Environment. so i decided to test my Django Apps in Python3.. is there a way to change or define Python3 Environment in Django Apps? -
uwsgi can't load app when set up nginx+django service on centos
centos7, python3.6.3,django1.11, uwsgi2.0.15 when i run command 'uwsgi --ini djcode_uwsgi.ini', no app is loaded,the message is as below: [uWSGI] getting INI configuration from djcode_uwsgi.ini > open("/usr/lib64/uwsgi/python3_plugin.so"): No such file or directory > [core/utils.c line 3686] !!! UNABLE to load uWSGI plugin: > /usr/lib64/uwsgi/python3_plugin.so: cannot open shared object file: No > such file or directory !!! > *** Starting uWSGI 2.0.15 (64bit) on [Sat Oct 7 16:47:06 2017] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-11) on 19 May > 2017 14:33:49 os: Linux-3.10.0-514.26.2.el7.x86_64 #1 SMP Tue Jul 4 > 15:04:05 UTC 2017 nodename: izuf64a9gck8o1inxenp1cz machine: x86_64 > clock source: unix pcre jit disabled detected number of CPU cores: 1 > current working directory: /home/djcode detected binary path: > /usr/sbin/uwsgi uWSGI running as root, you can use > --uid/--gid/--chroot options > *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** chdir() to /home/djcode your processes number limit is 3889 your memory page size is 4096 bytes detected max file descriptor number: > 65535 lock engine: pthread robust mutexes thunder lock: disabled (you > can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address > :8001 fd 3 your server socket listen backlog is … -
ImportError: No module named 'social_django'
Everytim I am running teh application from the Github Repository, I am getting the following error: Traceback (most recent call last): File "C:/Users/lenovo-pc/Desktop/Django-Social-Authentication-master/socialauth/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python35\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python35\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python35\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Python35\lib\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 956, in _find_and_load_unlocked ImportError: No module named 'social_django' I want to know what is this: social_django all about? I have intsall many libraries, but non of then have satisfied this error: python-social-auth[django] social-auth-app-django But nothing happens. Please let me know what I should do. -
django form data not saved in database
I have a form to make POST data to database. I'm using Django 1.11 views.py class BusinessCreate(CreateView): model = Business fields = '__all__' @method_decorator(login_required) def dispatch(self, *args, **kwargs): messages.success(self.request, 'dispatch') return super(BusinessCreate, self).dispatch(*args, **kwargs) def form_valid(self, form): messages.success(self.request, 'valid') form.instance.user = self.request.user # set user_id field to session user form.save() def get_success_url(self): messages.success(self.request, 'Business Added Successfully') return reverse('business:list') template <form class="card" method="POST"> {% csrf_token %} {{ form.non_field_errors }} {{ form.non_field_errors }} {% render_field form.name class='form-control' placeholder='Business Title' %} {{ form.name.errors }} {% render_field form.business_type class='form-control' %} {{ form.business_type.errors }} <button class="btn">Add Business</button> </form> When I submit the form, it doesn't save and also does not return any error. The messages in three methods in views.py are to check which method is called and it always prints dispatch since the only dispatch is called. I used debug_toolbar to check for debug whether request is POST or GET or none of the two and it show. -
Manipulating data passing from database to template (Django)
I'm still pretty new to Django, so I really hope I can explain what I need to do. I have a form where users input information about a character and then it's stored in the database and displayed for them on a page. I know it's easy to recall and display this data with template variable call (i.e. {{character.gender}}), however, I am trying to use the inputted data to create other variables based on the data BEFORE it goes into the template. I've done this in visual basic before and essentially used an if statement to create a new variable to store the information before passing it back out, but I can't figure out how to do this with django/python. For example, if the user provided the following information: Name = "Jill" Age = 23 Gender = "Female" I'd want to be able to do something like: if gender = "female": gender_identifier = 'she' if age < 30: youth = "is still very young" and then be able to do something like this in a template: {{character.name}} is {{character.age}} years old and {{gender_identifier}} {{youth}}! to output "Jill is 23 years old and she is still very young!" What I"m struggling … -
How do i show an active link in a django navigation bar dropdown list?
I have a navbar menu with a list of links which i want to show the active link when the user is on the page, so far i have managed to do this with links that dont have dropdowns like this. But I cannot seem to get it right with the dropdown links in such a way that if the user is on a page on the dropdown link the parent link on the navbar gets highlighted.like shown below Any help would be greatly appreciated. -
Identify type of logged in user
I have a custom user setup like this: class CustomUser(AbstractUser): pass class Employee(CustomUser): user = models.OneToOneField(settings.AUTH_USER_MODEL) # other fields In settings.py, I then add the following key: AUTH_USER_MODEL = 'myapp.CustomUser' I want to identify who logged in redirect them to appropriate views or urls. In my account activation view, after the logging them in I redirect them to their appropriate page like this if hasattr(user, 'employee'): return redirect('edit_employee', slug=user.employee.slug) else: return redirect('index') But this doesn't feel that right as I need to use this in other places like showing a different profile page link in the templates. How do I better identify the regular user and employee in views and templates? -
Javascript search filter on user generated table from Django
I'm trying to create a dynamic search engine with javascript from a user generated table that is created with a form that adds a song to the table. I want to search the list that's already created. It's not doing anything when I type in anything and no errors in the DOM. Can some someone tell me where i went wrong? Here's my HTML: {% extends "base.html" %} {% load static %} {% block title %}My Song List{% endblock %} {% block content %} <input type="text" name="search" placeholder="Search by Title" class="animated-search-form" id="myInput onkeyup="search();"> <div class="translucent-form-overlay"> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Add Song" /> </form> </div> <div id="list-container"> <h1 style="text-decoration:underline">Sorted Alphabetically by Song Title</h1> <h5> <table id="myList"> {% for song in song_list %} //song_list is the model <tr> <td>Title: {{song.title}}</td> <td>Artist: {{song.artist}}</td> <td>Year: {{song.year}}</td> <td>Genre: {{song.genre}}</td></tr> {% endfor %} </table> </h5> </div> {% endblock %} And here's my javascript: function myFunction() { // Declare variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myList"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < … -
Form Validation using Django Templates
I created a form inside my template, my problem is to get data without using forms module. class DentalRecordCreateView(CreateView): template_name = 'patient/dental_create.html' model = DentalRecord fields = '__all__' success_url = '/' def post(self, request, *args, **kwargs): pt = self.kwargs['pk'] #get id from previous insert form form = self.form_class(request.POST) #this is where pycharm is pointing the problem tooth = [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28, 48, 47, 46, 45, 44, 43, 42, 41, 31, 32, 33, 34, 35, 36, 37, 38] tooth.reverse() mytooth = {} if form.is_valid(): dental = self.form.save(commit=False) for t in tooth: mytooth["{0}".format(t)] = request.POST.getlist('tooth_' + str(t),False) # returns value each textbox from form tooth. Value for tooth status [decayed, etc.] mytooth2 = " ".join(mytooth[str(t)]) dental.status = mytooth2 dental.position = t messages.success(request, pt) # display values return redirect('index') else: messages.error(request, "Error") The error says that 'NoneType' object is not callable I find the I find the class based views confusing, does anyone have a good tutorial on how to use it for CRUD operations? Thanks -
Django: DeleteView for bulk delete
I am using django-actions for implementing custom actions in generic ListView. Following are the methods to perform specific tasks: actions.py from django.http import HttpResponseRedirect from django.utils.translation import gettext as _ def archive_stores(view, queryset): queryset.update(archive=True) return HttpResponseRedirect('.') def unarchive_stores(view, queryset): queryset.update(archive=False) return HttpResponseRedirect('.') def delete_stores(view, queryset): queryset.delete() return HttpResponseRedirect('.') archive_stores.short_description = _('Archive') unarchive_stores.short_description = _('Unarchive') delete_stores.short_description = _('Delete') Now the above works fine and using the actions menu I can perform all the 3 tasks. I am stuck in figuring out the following: For Archive and Unarchive how to show success and error messages. For Delete, how to use the my existing DeleteView as it already has confirmation page etc. And most importantly, how to pass the queryset to DeleteView so that it can perform bulk delete. Thanks. -
Filter Django Form Field
I have two form fields I need to filter on and not sure how to. For example, in my forms.py file, I create two fields as such: field_1 = forms.CharField(label='', widget=forms.TextInput(attrs={ 'class': "input-field", 'id': "field-1", 'type': "text", })) field_2 = forms.CharField(label='', widget=forms.TextInput(attrs={ 'class': "input-field", 'id': "field-2", 'type': "text", })) In my HTML, I'm trying to filter by Id, but not sure I can do what I want to: {% for inputfield in fields %} {% if inputfield.id == "field-2" %} {{ inputfield }} {% endfor %} {% endfor %} The filter on inputfield.id does not work. Is there a way to filter so that I present only the field I want? -
Django: Creating XML files dynamically from database, to be served for AJAX request
I am trying to serve the contents from a database table (new contents will be added to the table with time) to an HTML table. New contents need to be appended as new rows to the HTML table. Can you help me with the creation of XML files dynamically and where it should be stored in the server? -
Django: Best Practice/Advice on handling external IDs for Multiple Multi-directional External APIs
So this is more of a conceptual question, and I am really looking for someone to just help point me in the right direction. I am building a middleware platform where I will be pull data in from inbound channels, manipulating it, and then pushing it out the other door to outbound channels. I will need to store the external id for each of these records, but the kicker is, records will be pulled from multiple sources, and then pushed to multiple sources. A single record in my system will need to be tied to any number of external ids. a quick model to work with: class record(models.Model): #id Name = models.CharField(max_length=255, help_text="") Description = models.CharField(max_length=255, help_text="") category_id = model.ForeignKey(category) class category(models.Model): #id name = models.CharField(max_length=255, help_text="") description = models.CharField(max_length=255, help_text="") class channel(models.Model): #id name = models.CharField(max_length=255, help_text="") inbound = models.BooleanField() outbound = models.BooleanField() Obviously, I cannot add a new field to every model every time I add a new integration, that would be soooo 90s. The obvious would be to create another model to simply store the channel and record id with the unique id, and maybe this is the answer. class external_ref(models.Model): model_name = models.CharfieldField() internal_id = models.IntegerField() … -
How to run a Django Project on a Personal Run Server
I've been wanting to run my own server for a while and I figured that running one for my django website would be a good start. What do you recommend I use for this? I've been trying to use a Ubuntu Virtual Machine to run it on one of my old laptops that I don't really use anymore until I can buy a dedicated server. Should I run it from a Virtual Machine? If so, would Ubuntu be best? That appears to be the case, but I want to be sure before I invest in anything. I want to be able to access the website from other computers, just like any other website. Am I going about this wrong? If so, what can you suggest me? -
Elastic Beanstalk with python 3.4 still using python 2.7
I just spin up some environment using EB with python 3.4 and Django but it keeps failing, looks like the error occurs when installing using pip install -r requirements.txt this are the events from the web console: Time Type Details 2017-10-06 20:22:39 UTC-0600 WARN Environment health has transitioned from Pending to Degraded. Command failed on all instances. Initialization completed 69 seconds ago and took 14 minutes. 2017-10-06 20:22:20 UTC-0600 ERROR Create environment operation is complete, but with errors. For more information, see troubleshooting documentation. 2017-10-06 20:21:17 UTC-0600 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2017-10-06 20:21:17 UTC-0600 ERROR [Instance: i-0b46caf0e3099458c] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 541, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2017-10-06 20:21:14 UTC-0600 ERROR Your requirements.txt is invalid. Snapshot your logs for details. I followed this tutorial: django-elastic-beanstalk-django and deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk on both I'm stuck at the same step -
Routers urls with django rest framework 3.6 and django 1.11
I have a django 1.7 with djangorestframework 3.3.2 site, and I'm migrating to django 1.11 with DRF 3.6. All things are working fine except routers with urls. My Router: router = routers.DefaultRouter() router.register(r'options', MicrositeViewSet) My urls: urlpatterns = [ # '', url(r'^api/v1/', include(router.urls)), ] My viewsets: from django.shortcuts import get_object_or_404 from rest_framework import viewsets, mixins from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.response import Response from rest_framework.permissions import IsAdminUser from microsites.permissions import AccountPermission from microsites.models import Microsite from microsites.serializers import SelfManagedMicrositeSerializer, MicrositeTestProfileSerializer class MicrositeViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ A viewset for viewing and editing microsites. """ authentication_classes = (SessionAuthentication,) permission_classes = (AccountPermission,) serializer_class = SelfManagedMicrositeSerializer queryset = Microsite.objects.all() def list(self, request, *args, **kwargs): microsite = request.microsite account = request.account queryset = Microsite.objects.filter(account=account) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = self.get_queryset() microsite = get_object_or_404(queryset, api_key=pk) self.check_object_permissions(self.request, microsite) microsite.pull() microsite.set_request_user(request.user) serializer = self.get_serializer( microsite, metadata=request.GET.get('metadata', False), categories=request.GET.get('categories', False), ) return Response(serializer.data) def update(self, request, pk=None, *args, **kwargs): partial = kwargs.pop('partial', False) queryset = self.get_queryset() microsite = get_object_or_404(queryset, api_key=pk) serializer = self.get_serializer(microsite, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return Response(serializer.data) This code exactly as it is works with django 1.7 and DRF 3.2, but in django 1.11 and DRF 3.6 does … -
user authentication across domains in Django
Say I have a site, with name = NAME, all ending with .com structured as: NAMEjobs, NAMEblog, NAMEnews, .... so on and so forth under an umbrella domain NAME****. And I wanted to build apps for each of these domains how would I share authentication (for a signed in user) across these? I looked at django shared-session but not sure if there's a better route to go. I'd prefer to not roll my own solution. -
How to send Data with jQuery to Django view and render the Django template?
I have some data in javascript and want to send it to a Django view function. After that I want to render a Django template using HttpResponse, but how it works? First I had send some data to a Django view with jQuery.ajax() and used the response data, now I want to send data within a second jQuery.ajax() - after a button was clicked - to a different Django view function and finally render a simple template, like how it works, if I click a simple link on a website. I have cut the snippet as far as possible for the sake of clarity $(matchfield).on('click', function(event) { event.preventDefault(); var field = $(this).val(); $.ajax({ method: "POST", url: "/view-function/", data: { "field": field }, dataType: "json", context: this, success: function (data) { if(data.message === 1) { points = 100 $('#submit').on('click', function(event) { event.preventDefault(); $.ajax({ url: "/another-view/", method: "POST", data: {"points": points}, success:function(response){ $(document).html(response) } }) }) } } }); }); If the #submit Button was clicked, The status code of the Response is 200 and Chrome Dev Tools shows the complete excepted new html page in Preview(without css style), but nothing happens on the current page. I used return HttpResponse(template.render(context, request)) I …