Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Determining the number of connected clients in django channels 2
for a webrtc project, I need to transform the server code from https://codelabs.developers.google.com/codelabs/webrtc-web/#6 to a django channels 2 version. In the code, as you can see, the server sends/emits some events based on the number of clients connected. here is the code: 'use strict'; var os = require('os'); var nodeStatic = require('node-static'); var http = require('http'); var socketIO = require('socket.io'); var fileServer = new(nodeStatic.Server)(); var app = http.createServer(function(req, res) { fileServer.serve(req, res); }).listen(8080); var io = socketIO.listen(app); io.sockets.on('connection', function(socket) { // convenience function to log server messages on the client function log() { var array = ['Message from server:']; array.push.apply(array, arguments); socket.emit('log', array); } socket.on('message', function(message) { log('Client said: ', message); // for a real app, would be room-only (not broadcast) socket.broadcast.emit('message', message); }); socket.on('create or join', function(room) { log('Received request to create or join room ' + room); var clientsInRoom = io.sockets.adapter.rooms[room]; var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0; log('Room ' + room + ' now has ' + numClients + ' client(s)'); if (numClients === 0) { socket.join(room); log('Client ID ' + socket.id + ' created room ' + room); socket.emit('created', room, socket.id); } else if (numClients === 1) { log('Client ID ' + socket.id + ' … -
gunicorn keeps rebooting it's worker when Django is starting Python project
I am running a web-based project with a data science focussed backend which is hosted on a Microsoft Azure cloud server. Large deep learning models need to be loaded and initialized when Django starts the project. I am running the project through an nginx server which communicates to the Django server through gunicorn. If I run the project on the same Azure cluster through Django alone (not using nginx or gunicorn) it initializes and starts just fine. However, when I run it on nginx through gunicorn, one of the workers keeps rebooting as the project is starting up (it takes maybe ~2 mins to initialize. Here is the output from the gunicorn command when I try to start the Django project: user@host:/home/libor/libor_transition/libor_transition_api$ sudo gunicorn --pythonpath="$(pwd)" --log-level=DEBUG -t 1000 libor_transition_api.wsgi:appli> [2019-07-29 08:43:44 +0000] [33808] [DEBUG] Current configuration: config: None bind: ['127.0.0.1:8000'] backlog: 2048 workers: 1 worker_class: sync threads: 1 worker_connections: 1000 max_requests: 0 max_requests_jitter: 0 timeout: 1000 graceful_timeout: 30 keepalive: 2 limit_request_line: 4094 limit_request_fields: 100 limit_request_field_size: 8190 reload: False reload_engine: auto reload_extra_files: [] spew: False check_config: False preload_app: False sendfile: None reuse_port: False chdir: /home/libor/libor_transition/libor_transition_api daemon: False raw_env: [] pidfile: None worker_tmp_dir: None user: 0 group: 0 umask: 0 initgroups: False … -
How to set a timedelta in between two model datefields
i'm strugling some time already trying to set a timedelta in two fields of my model, then display de difference between then. i've tried Stack and a lot of others tutorials and not quite shure if a should make a function on my models or my views, or a basic variable on the views i've tried all of them here is my code: MODELS.PY from django.db import models from datetime import datetime from datetime import timedelta class To_do (models.Model): task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(blank=False) end = models.DateField(blank=False) def __str__(self): return self.task VIEWS.PY class DetailView(DetailView): template_name = 'details.html' model = To_do def get_queryset(self): return To_do.objects.all() def get_delta(self): d1 = To_do.start d2 = To_do.end tdelta = d1-d2 return tdelta i want to display the difference between the star and end and after that, and after that setup an alarm if get less than three days. appreciate your help. -
User authentication using django and MYSQL
i am trying to authenticate the user using MYSQL (running on XAMPP). however the table in the database has been created but when i manually add a user and password in database and then try to authenticate then it show invalid credentials. the above thing has been succesfully done using sqlite3 Objectives to be achieved :- A) User authentication using MYSQL B)Everytime the user log-in, In database the name and datetime of the user login should be reflected. Here's code:- models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # Create your models here. class Login(AbstractUser): username = models.CharField(max_length=50,blank=False) password = models.CharField(max_length=32) def __str__(self): return self.username Views.py from django.shortcuts import render from first_app.forms import CmdForm #view after login from django.http import HttpResponse, HttpResponseRedirect #some imports from django.urls import reverse import csv from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages #from django.contrib.sessions import serializers # Create your views here. def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: messages.error(request,'Please provide valid credentials') return render (request,"first_app/login.html", context) else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): … -
IF statement not working with list difference
Trying to get the result of the difference between two list, using below code, but doesn't seemed to work, Please help list1 = ['one', 'two', 'three'] list2 = ['one', 'two', 'three', 'four'] list3 = list(set(list1) - set(list2)) if not list3: #if not empty, print list3 print(list3) else: # if empty print none print("None") -
I keep getting a 404 error when django is looking for static files
I keep getting a 404 error when django is looking for static files. settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') STATIC_URL = '/static_cdn/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) project tree structure of app - business -- migrations --- .... -- static --- business ---- main.css ---- scripts.js -- templates --- business ---- base.html ---- home.html -- templatetags --- ... -- __init__.py -- admin.py -- apps.py -- models.py -- tests.py -- urls.py -- views.py Error [29/Jul/2019 13:09:45] "GET / HTTP/1.1" 200 12670 [29/Jul/2019 13:09:45] "GET /static_cdn/business/main.css HTTP/1.1" 404 77 [29/Jul/2019 13:09:45] "GET /static_cdn/business/scripts.js HTTP/1.1" 404 77 I also link to static files like {% static 'business/main.css' %} and I do have {% load static %} at the top of my document. Why isn't django able to find the static files? The error says it is looking in the correct place but it is returning 404 error. If you need anything else, you can look at my code -
Overwriting nested serializer's create method throws TypeError: create() got multiple values for keyword argument
I want to send data to my API. My data structure is nested. So I am trying to overwrite the create method following the docs and SO. When sending data it gives me the following error: TypeError: create() got multiple values for keyword argument 'graph' My data structure looks like this: { "project": "project1", "name": "Graph1", "description": "Graph belongs to Projekt1", "nodes": [ { "id": 2, "name": "Node1 of Graph 1", "graph": 3 } ] } Her is what I am trying in my serializer (which is pretty standard I assume): class GraphSerializer(serializers.ModelSerializer): nodes = NodeSerializer(many=True) class Meta: model = Graph fields = ('project', 'name', 'description', 'nodes', ) def create(self, validated_data): nodes_data = validated_data.pop('nodes') graph = Graph.objects.create(**validated_data) print(graph) for node_data in nodes_data: Node.objects.create(graph=graph,**node_data) return graph The error is in the for loop. When I debug though and print graphit give me back just one Graph (Graph1). So I don't understand why I should get a multiple values error. Here is more info if needed: Node serializer class NodeSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = Node fields = ('id', 'name', 'graph', ) My models class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) def __str__(self): … -
allowing spaces and numbers in Django fields
I want to allow spaces and numbers in the field, I changed the form forms.CharField to forms.RegexField and it didnt work. I found similar questions: Here, Here and other questions, but none of them works good. alphanumeric_underscore = RegexValidator(r'^[0-9a-zA-Z]*$') list_of_templates = get_template_database_names() existing_database = forms.ModelChoiceField( queryset=TemplateDatabase.objects.all(), label='Name des Templates') new_database = forms.CharField(label='Name von Datenbank ' 'auf Basis des Templates', max_length=255, validators=[alphanumeric_underscore]) I can use numbers in the name, but it cannot begin or end with numbers. but by using space its not working -
django 2.2.3-Django 404 error ('Page not found') after runserver
My project is named 'tweetme', and when I runserver I get this error. Using the URLconf defined in tweetme.urls, Django tried these URL patterns, in this order: ^admin/ ^static/(?P<path>.*)$ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py file: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)) I expect to shows: the install worked successfully! Congratulation but its shows me: Page not found at/ -
Return data based on model flag for OnetoOne Nested Serializer
I am using a nested serializer for onetoone mapping for a model offer. But i want the nested serializer to only return data if the fllag in the model instance of nested serializer is set to true. I guess to_representation will not work here as it will receive an object instance rather than queryset. Model : class Offers(models.Model) : brand = models.CharField(max_length=100,blank=True,null=True) hospital = models.OneToOneField('hospital.Providers',to_field='hospital_id',on_delete=models.SET_NULL, related_name='hospital_offer',blank=True,null=True) validity = models.PositiveIntegerField(default=0) terms = models.CharField(max_length=500,blank=True,null=True) discount = models.PositiveIntegerField(default=0) logo = models.CharField(max_length=100,blank=True,null=True) active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) Serializer : class ProviderOffersSerializer(serializers.ModelSerializer) : class Meta : model = Offers fields = ('brand','id') class ProviderSerializer(serializers.ModelSerializer): hospital_offer = ProviderOffersSerializer(read_only=True) network = NetworkSerializer(read_only=True) class Meta: model = Providers fields = ('hospital_id','hospital_name','hospital_offer','pincode','network') Now ProviderSerializer should return data for offer only if active is True. Any help will be appreciated. -
Django. When adding an image, create a folder corresponding to the object id
I created a model, it has a line for the image: photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) In the example, if I add an image, a folder is created with the date of adding I wish that when add an image, create a folder with the "id" of the object. Please tell me the solutions! Thanks and sorry for my english! -
Please Help me to fix this issue
I'm learning python Django. I have been trying to create a custom user model and it is working but the issue I have is that whenever I visit any user's profile through the Django admin I get this error Exception Value: 'date_joined' cannot be specified for UserProfile model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class UserAdminModel. Here is how my model is looking like. class UserProfile(AbstractBaseUser, PermissionsMixin): """ A model for authors and readers.""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) REQUIRED_FIELDS = ['email', 'password'] USERNAME_FIELD = 'username' objects = UserProfileManager() def __str__(self): return self.username also my serialiser looks like this class UserProfileSerializer(ModelSerializer): """ Serializers user profile model. """ def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'username', 'email', 'is_staff', 'password') extra_kwargs = { "is_staff": { "read_only": True }, } -
Django CMS multi-line field
Is it possible to make multi-line field on this page, because it's really uncomfortable when you have to scroll to see the whole thing. -
PyCharm not recognizing models
I am writing unit tests for my project but when I run tests file it says apps.products.models.Category.DoesNotExist: Category matching query does not exist. and it does not recognize in tests.py file. Though I have already included installed apps in the settings PROJECT_APPS = [ 'apps.core', 'apps.products ', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'django_filters', ] + PROJECT_APPS I am importing like this from apps.products.models import Category and that model is not detected I have init file in my directory. Any help please) -
How to override the field value for modelformset in CreateView?
I use different qwerysets for modelformset of the same model. The first filter for grouping values from queryset I define in forms.py class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Framework") class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Programming language") The next step is to filter out the values that are already bound to the user being edited. To do this, in get_context_data I get a list of all the technologies that the user already has. employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) get_context_data def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() context['tech_group'] = Techgroup.objects.all() return context How do I now apply a filter to context['formset_framework'] that excludes technologies that the user already has? Smt like context['formset_framework'] = SkillFrameworkFormSet().field['technology'] not in employee_current_technology <-- ??? -
how to process submit on django-tables2 with a class View with FilterView mixin
I have a django-tables2 FilterView. The filter is templated in a form: {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} I have added a checkbox field to each row, and I have the table in a form: <form action="table_selection" method="get" class="form form-inline"> {% csrf_token %} {% render_table table 'django_tables2/bootstrap.html' %} <button class="btn btn-primary red" type="submit" >Submit Rows</button> </form> When I submit, I get logging messages like: GET /three_pl/threepl_fulfilments_filter/table_selection?csrfmiddlewaretoken=... &select_row=198&select_row=158&select_row=159 so the select_rows are very interesting. But I am lost with the class view, I can't grapple with how to process the form submission. This is my view: class FilteredThreePLFulfimentsView(SingleTableMixin,FilterView): table_class = ThreePL_order_fulfilmentsTable model = ThreePL_order_fulfilments template_name = "three_pl/ThreePLFulfilmentsFilter.html" #three_pl/templates/three_pl/ThreePLFulfilmentsFilter.html filterset_class = ThreePLFulfilmentsFilter -
how can i modified field is recorded, in django.form or django.model
I want to record the model field when they are be modified, who modifid them; the olg field and the new field. I do it in them ModelForm.clean, to find which field be modified, and record them. class SynthesisStepForm(BootstrapModelForm): class Meta: model = SynthesisStep fields = ('title', 'version', 'condition', 'yield_rate', 'testing', 'stype') widgets = { 'testing': forms.Textarea(attrs={'rows': '4', 'cols': '100', 'style': 'width:auto;'}), 'condition': forms.Textarea(attrs={'rows': '4', 'cols': '100', 'style': 'width:auto;'}) } def clean(self): """ :return: """ update_fields = ('title', 'version', 'condition', 'yield_rate', 'testing', 'stype') cleaned_data = super(BootstrapModelForm, self).clean() update_note = supervisory_update_fields(self, cleaned_data, update_fields) self._update_note = update_note return cleaned_data def supervisory_update_fields(form_obj, cleaned_data, update_fields): """ :param form_obj: :param cleaned_data: :param update_fields: :return: """ update_note = '' if form_obj.instance.pk: # new instance only changed_data = form_obj.changed_data for data in changed_data: if data in update_fields: try: old_field = eval('form_obj.instance.{0}'.format(data)) new_field = cleaned_data[data] if old_field != new_field: update_note = update_note + '{2} is modified , from "{0}" to "{1}"\n'.format(old_field, new_field, data) except Exception as e: pass return update_note I want to take it more efficiency,and can ues it in model.save and form.save -
How to add new user in admin page in django?
I am trying to add user in admin page in django. Whenever I register in my site form it adds itself but whenever I try to add it in admin page, it gave me the error message. NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s6856_x1" C:\Users\Bilal\Envs\trial\lib\site-packages\djongo\sql2mongo\query.py in parse handler = self.FUNC_MAP[sm_type] -
Nested object dipslayed in main object django
I have problem with nested objects in Django. I would like not return to main response nested objects. Actually I have reponse: [ { "display_name": "Link1", "link": "http://facebook.com", "sub_links": [ { "display_name": "Link3", "link": "http://vk.com" }, { "display_name": "Link2", "link": "http://google.com" } ] }, { "display_name": "Link2", "link": "http://google.com", "sub_links": [] }, { "display_name": "Link3", "link": "http://vk.com", "sub_links": [] } ] and I would like receive: [ { "display_name": "Link1", "link": "http://facebook.com", "sub_links": [ { "display_name": "Link3", "link": "http://vk.com" }, { "display_name": "Link2", "link": "http://google.com" } ] } ] My viewset: class LinksViewSet(ReadOnlyModelViewSet): queryset = Links.objects.all() serializer_class = LinksSerializer permission_classes = (AllowAny, ) pagination_class = None My serializer: class SubLinksSerializer(serializers.ModelSerializer): class Meta: model = Links fields = ('display_name', 'link', ) class LinksSerializer(serializers.ModelSerializer): sub_links = SubLinksSerializer(many=True, read_only=True) class Meta: model = Links fields = ('display_name', 'link', 'sub_links') I really don't know how should I do it. What is more I tried find solution in documentation Django. -
Django view testing: Should status code be tested separately from template used?
I've created a test for one of my views. The function: Asserts if the status code is 200 Asserts if the template was used Best practice wise, should these tests be kept separate? I'm concerned that I'm violating SRP (Single Responsibility Principle) by giving this function multiple assertions. The code works as is, this is merely an opinion question (sorry if this question should be somewhere else). def test_contacts_GET(self): response = self.client.get(self.contacts_url) request = self.client.get(self.contacts_url) self.assertEqual(request.status_code, 200) self.assertTemplateUsed(response, 'crm/contacts.html') All tests are passing as is. Thank you in advance for your time. -
Url for custom method in django apiview
I am new in Django and I am bit confused in Django apiview for custom method. In ApiView, How can I create a custom method and How to call from axios. For example Here is my View class TimeSheetAPIView(APIView): @action(methods=['get'], detail=False) def getbytsdate(self, request): return Response({"timesheet":"hello from getbydate"}) def get(self,request,pk=None): if pk: timesheet=get_object_or_404(TimeSheet.objects.all(),pk=pk) serializer = TimeSheetSerializer(timesheet) return Response({serializer.data}) timesheet=TimeSheet.objects.all() serializer = TimeSheetSerializer(timesheet,many=True) return Response({"timesheet":serializer.data}) Here is my URL=> url(r'^timesheets_ts/(?P<pk>\d+)/$', TimeSheetAPIView.as_view()), url(r'^timesheets_ts/', TimeSheetAPIView.as_view()), Normally my url would be like=> api/timesheet_ts/ this one will get all of my records. So my question is how can I setup URL for getbytsdate or getbyname or other some kind of custom get method? and how can I call? I tried like this way=> url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', TimeSheetAPIView.as_view()), and I called like that api/timesheets_ts/getbytsdate/?tsdate='test' Its not work. So please can u explain for the custom method in apiview and url setting? -
Delete file when file download is complete on Python x Django
I can download the file with the following code(Python x Django). file = open(file_path, 'w') file.write(text) file.close() if os.path.exists(file_path): with open(file_path, 'rb') as fsock: filename = urllib.parse.quote(filename) response = HttpResponse() response['content_type'] = 'text/plain' response['Content-Disposition'] = "attachment; filename='{}'; filename*=UTF-8''{}".format(filename,filename) response.write(fsock.read()) return response The file to download is generated before downloading. At this time, is it possible to implement deletion of files when downloading is complete? -
"Hashes did not match" during deploying cookiecutter django with wagtail
I have been trying to deploy my Django/Wagtail project that is created with Cookiecutter Django using docker to a Digital Ocean droplet that I created using the command docker-machine create.The problem is that all the static files have the error Hashes did not match even after I use ./manage.py collectstatic I've tried to google it but cannot find any reference regarding this error. django_1 | INFO 2019-07-28 10:24:52,920 etag 8 140528735497544 css/project.css: Hashes did not match django_1 | INFO 2019-07-28 10:24:52,925 etag 8 140528735497544 images/favicons/favicon.ico: Hashes did not match django_1 | INFO 2019-07-28 10:24:52,929 etag 8 140528735497544 js/project.js: Hashes did not match django_1 | INFO 2019-07-28 10:24:52,932 etag 8 140528735497544 sass/project.css.map: Hashes did not match django_1 | INFO 2019-07-28 10:24:52,936 etag 8 140528735497544 sass/project.css: Hashes did not match Below is my static setting in base.py # STATIC # ------------------------------------------------------------------------------ STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] -
Limit the amount of logins Django server
I need limit traffic to Django server, but I don't know about that problem. I need be provided some keyword to to solve that problem. Thanks -
How can I generate QR code in django project?
Can anyone guide me to generate QR code in django project? I want to generate Qr code by taking data from postgres database and display it in the template?