Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Visual Studio Code Is Not Able To Launch Django Project From Debugger
I am using Visual Studio Code as my IDE for building web applications using Python's Django web development framework. I am developing on a 2018 MacBook Pro. I am able to launch my web applications by launching them in the terminal using: python3 manage.py runserver However, I want to be able to launch my application through the debugger. To try and do this, I navigated to the debug section, created the launch.json file, and changed my configuration in the drop down to Python: Django. Here is are my configurations from the file. { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true }, When I try to run the debugger using the green play arrow, I get the following exception: Exception has occurred: ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "/Users/justinoconnor/Desktop/Rapid Prototyping/Projects/hello_django/manage.py", line 14, in ) from exc Launching the VS Code debugger with this configuration should be the same as running python manage.py runserver --noreload --nothreading, but it is not working. I'm thinking it is because on the MacBook I have … -
Django: User Mentions
I'd like to implement user mentions in Django. The documentation I found was one package that doesn't support the newer Django releases and Martor which seems to heavy. I simply would like to type '@' and then the system should provide a type-ahead overview with the users available and then use a callback so I can trigger a notification. Thanks, Sebastian -
error to save history chess into db sqlite django
I use django 2.1 and combine its with nodejs. the game is ok but when game end, I want to save history into db of django. But it's not run. I'm not sure where is issue static\main.js winner = checkLogout !== username ? username : checkLogout; history= game.history(); socket.emit('endgame', {'gameId':gameId,'player1':player1, 'player2':player2, 'winner': winner, 'history': history.toString(), note : checkLogout }); nodejs\index.js var http = require('http').createServer().listen(4000); var io = require('socket.io')(http); var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; var xhttp = new XMLHttpRequest(); var host = 'localhost'; var port = '8000'; io.on('connection', function (socket) { socket.on('endgame', function(msg){ var url = 'http://' + host +':' + port + '/save_game/'; xhttp.onreadystatechange = function() { if(this.readyState === 4 && this.status === 200) { if(xhttp.responseText === "error") console.log("error saving game"); else if(xhttp.responseText === "success") console.log("the message was posted successfully"); } }; xhttp.open('POST', url, true); xhttp.send(JSON.stringify(msg)); }); }); game\views.py import json from django.shortcuts import render from django.contrib.auth.decorators import login_required from game.models import Game from django.http import HttpResponse, HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt @login_required def index(request): return render(request, 'index.html') @csrf_exempt def save_game(request): if request.method == 'POST': msg_obj = json.loads(request.body.decode('utf-8')) try: msg = Game.objects.create(gameId=msg_obj['gameId'], player1=msg_obj['player1'], player2=msg_obj['player2'], winner = msg_obj['winner'], history = msg_obj['history']) msg.save() except: print("error saving game") return HttpResponse("error") return HttpResponse("success") else: return … -
Django Performance, Deployment and Architecture Query
We are building a huge business management website. Each business will have 1000's of customers and they will use our business management website to manage their business. We are targeting atleast 100 business to sign on the first year . This will increase as it goes. In short we will have 1000's of business with 1000's of customers in long run. It will be a massive database and huge traffic like big websites. We are developing this in Django - React framework. Question :- In this scenario what do you think is the best deployment strategy 1) Deploy one instance (say Amazon EB instance) for every business and use Django OAuth. -ve is deployments, maintenance and upgrade 2) Deploy one large instance with auto scaling and hope it's able to handle the traffic. 3) Any other options I'm kinda leaning towards 1) , But unable to decide as we have not developed such a massive website. So seeking some expert advice from people who have developed such. -
django directory structure the "django way"? (/root/project/app or /root/project & root/app)?
I have a pretty simple question here: I'm starting out with Django but i'm needing to know which one of the following is more proper (the django way): Having the app under the django_project like this: /root/project/app Or Having the Django_project and the django_app under the same /root/ directory in parallel? Thaks all! -
Django Rest Framework urls router only recognized one path
I have the following urls.py: from django.urls import path, include from rest_framework import routers from TasksManagerApp import views APP_NAME ='TasksManagerApp' router = routers.DefaultRouter() router.register(r'tasks', views.TaskViewSet) router.register(r'task_templates', views.TaskTemplateViewSet) router.register(r'task_lifecycle_nodes', views.TaskLifecycleNodeViewSet) router.register(r'task_lifecycle_events', views.TaskLifecycleEventViewSet) urlpatterns = [ path('', include(router.urls)), ] For some reazon, DRF only recognizes one of the paths registered by the router: task_templates. All other paths are not recognized and rise a 404 error: Using the URLconf defined in Attractora.urls, Django tried these URL patterns, in this order: es/ api-token-auth/ es/ admin/ es/ api-auth/ es/ rosetta/ es/ tasks_manager/ ^task_templates/$ [name='tasktemplate-list'] es/ tasks_manager/ ^task_templates\.(?P<format>[a-z0-9]+)/?$ [name='tasktemplate-list'] es/ tasks_manager/ ^task_templates/(?P<pk>[^/.]+)/$ [name='tasktemplate-detail'] es/ tasks_manager/ ^task_templates/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='tasktemplate-detail'] es/ tasks_manager/ ^$ [name='api-root'] es/ tasks_manager/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^media/(?P<path>.*)$ The current path, es/tasks_manager/tasks, didn't match any of these. I don't know why the router chose that one, it is not the first one to be registered, and all other paths are correctly registered too. I have no idea where to look. -
Is django-admin part of python or django installation?
I am just starting out on using the django framework. One thing that bugs me is the django-admin utility. Is it part of the python installation or is it part of the django installation through pip? The way I've been doing my projects is Make a virtual Environment. Create a django project in the environment through django-admin. and then I just install the django framework using pip inside the environment. My question arises because inside the virtual environment, I used django-admin to create the project before installing the framework. -
django-channel to make a notifications push
Well guys, i'm trying to do a notification push in django with django-channel, and yeah it works with websockets and i have never used that before, and i need a mentor to do it. I have been reading documentations around, but i still dont get it To be specific i trying to send notifications to the user when someone else replies his comment or give him a like. i have my appweb deployed in heroku, if someone is interested in help me please don't doubt to get in touch. where i knew django-channel and before of that i was thinking to make it with django Api Rest: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django -
How do I add a class to the admin page in django python?
I am currently making a small site in django. When I tried to add a button to the admin page using this code: from django.contrib import admin # Register your models here. from .models import profile class profileAdmin(admin.Modeladmin): class Meta: model = profile admin.site.register(profile, profileAdmin) That is the code to add the button to the admin page. from django.db import models # Create your models here. class profile(models.Model): name = models.CharField(max_length=50) desc = models.TextField(default = 'default user description') job = models.CharField(max_length=20) def _unicode_(self): return self.name That is the code for the button. I also know that the profile app which contains this button and admin page has been added to the install apps and is functioning. When I try to makemigrations I am prompted with this error. AttributeError: module 'django.contrib.admin' has no attribute 'Modeladmin' -
How does twitch.tv fullscreen on ios?
I've been searching for a way to fullscreen in browser on ios, and have only been able to find people saying there's no way unless they save your app to the homescreen. However, twitch.tv prevents (what seems to be) a true fullscreen, in browser, without issues. Can someone explain this to me? Is it possible to activate fullscreen from any website? If it matters, I have a django app embedded in an iframe on my website, that's what I would want to make fullscreen. -
Complications from storing and running Javascript functions from a Django database
In a project, I am storing user defined Javascript functions in my Django database, and running them using Js2Py. Something like this: class MyModel(models.Model): function = models.TextField() def run_function(self, value): try: # Compiling compiled_function = js2py.eval_js(self.function) # Running with value compiled_function(value) except: pass I noticed that if I store function(value) { console.log("hello"); } in my function field, and call run_function(), the word hello gets printed out in my console in the local server. So I was wondering about a few things: Provided I always run the function within a try block, what are the possible security issues that may arise? Since it can print in my console, is that by itself not a security issue? Is there any way to make this thing secure? I really have to build a system where my users are storing simple self-defined functions in the database, and my system needs to run them. What is the possible solutions to this problem? -
Prevent or escape forward slash ('/') in Django on user input?
How can I prevent a user from entering an item with a forward slash (/) in user input or escape it after entry? If a user attempts to enter Do 1/2 the work up front into a Django form field for a generic CreateView, how can I handle, sanitize, or prevent this? -
How can I handle forward slashes '/' in title when routing in Django templates?
My urls.py and template.html look as follows: urls.py path('item/<str:title>/', views.ItemDetail.as_view(), name="item_detail'), template.html <h3>Title: <a href="{% url 'item_detail' object.title %}">object.title</a></h3> Right now, I do not prevent users from creating objects with a forward slash in them. That is probably a separate question After a user creates an item with a forward slash, let's say 'Do 1/2 the work up front', how can I route to that item using that title? Right now I do not know how to handle the forward slash / and I'm getting the error: Reverse for 'item_detail' with arguments '('Do 1/2 the work up front',)' not found. 1 pattern(s) tried: ['item\/(?P[^/]+)$'] I looked into striptags but that was not what I needed. -
Add to database cache from django_crontab
everyone! I added settings for django_crontab INSTALLED_APPS = [ .... 'django_crontab', .... ] and setting for cron CRONJOBS = [ ('* * * * *', 'app.cron.task'), ] add task method to app.cron from .views import add_to_cache_table() def task(): add_to_cache_table() and created method add_to_cache_table() in app.views: from django.core.cache import cache def add_to_cache_table(): cache.add('key', 'value') But, when I'm trying to get value form cache by that key, I get None. Can i use database cache in cron and write to it? Thanks! -
Django - how to pass filtered querysets to Detailview
I have Client, servers, users models. In the Client Detailview i would like to display the servers and users that belong to that company. How do I filter that? models.py class Client(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Server(models.Model): company = models.ForeignKey(Client, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class User(models.Model): company = models.ForeignKey(Client, verbose_name="Company", on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return self.first_name + ' ' + self.last_name views.py class clientdetails(LoginRequiredMixin, DetailView): template_name = 'myapp/clientdetails.html' def get_queryset(self): return Client.objects.all() def get_context_data(self, **kwargs): context = super(clientdetails, self).get_context_data(**kwargs) context['servers'] = Server.objects.filter(** servers belonging to that client **) context['users'] = User.objects.filter(** servers belonging to that client **) return context How do I achieve this? -
HTTP forward from generic CreateView in Django?
I have a CreateView for a patient object (simplified): from django.views.generic.edit import CreateView import models class PatientCreate(CreateView): model = models.Patient fields = ['name', 'country', ..] # template_name is "patient_form.html" from CreateView (I have overridden form_valid and get_context_data to set a few things by default, see for example here, but I think that's irrelevant.) If a patient by the same name already exists, I'd like to simply HTTP forward to the detail page for that patient instead of creating a new one. How do I do that? I'm using Django 1.11. -
Can't login in admin page after accessing my website pages
I created a superuser in my admin section. After that I can log in admin page. But Whenever I try accessing some myapp pages then and then I again want to access the admin page It shows this error"Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." I tried it multiple times. And I can create a new superuser by same name I created last time. Here is two screenshot: Login Error creating superuser How to solve this issue? -
Try to run neural style transfer using tensorflow on django got value error
Picture of error message views.py def neural_style_transfer(request): get_image_flag = True photo_content_number = request.session.get('photo_content', None) photo_style_number = request.session.get('photo_style', None) current_path = str(os.getcwd()) if photo_content_number: photo_content = Photo.objects.get(id=photo_content_number) photo_content_url = photo_content.picture.url photo_content_url = current_path + photo_content_url if photo_style_number: photo_style = Photo.objects.get(id=photo_style_number) photo_style_url = photo_style.picture.url photo_style_url = current_path + photo_style_url if request.method == 'POST': action = request.POST['action'] if action == "Switch": temp = request.session.get('photo_content', None) request.session['photo_content'] = request.session.get('photo_style', None) request.session['photo_style'] = temp photo_content, photo_style = photo_style, photo_content photo_content_url, photo_style_url = photo_style_url, photo_content_url return redirect('/neural_style_transfer') elif action == "Reset": photo_content_number = 0 photo_style_number = 0 photo_content = None photo_content_url = None photo_style = None photo_style_url = None return redirect('/neural_style_transfer') elif action == "Process": load_model() photo_generated = Photo() photo_generated.save() photo_generated.uploader = request.user.username photo_generated_abs_url = current_path + "/media/pictures/" + str(photo_generated.id) + "_output.png" photo_generated_url = "/pictures/" + str(photo_generated.id) + "_output.png" work_flag = True nst.transfer(photo_content_url, photo_style_url, photo_generated_abs_url) photo_generated.picture = photo_generated_url photo_generated.save() return render(request, 'neural_style_transfer.html', locals()) def load_vgg_model(path): vgg = scipy.io.loadmat(path) vgg_layers = vgg['layers'] def _weights(layer, expected_layer_name): wb = vgg_layers[0][layer][0][0][2] W = wb[0][0] b = wb[0][1] layer_name = vgg_layers[0][layer][0][0][0][0] assert layer_name == expected_layer_name return W, b return W, b def _relu(conv2d_layer): return tf.nn.relu(conv2d_layer) def _conv2d(prev_layer, layer, layer_name): W, b = _weights(layer, layer_name) W = tf.constant(W) b = tf.constant(np.reshape(b, (b.size))) … -
django: how to display choices in form's ChoiceField depending on the current user's data
I have the following form with 4 fields: from django import forms from django.apps import apps from .models import Task CustomUser = apps.get_model('users', 'CustomUser') students = CustomUser.objects.filter(status='student') students_choices = [(student.username, student) for student in students] class AddTaskForm(forms.ModelForm): class Meta: model = Task fields = ('title', 'description', 'deadline', 'student') widgets = { 'deadline': forms.SelectDateWidget(), } student = forms.ChoiceField(choices=students_choices) The "student" field will display the choices with all users with status "student". But what if I want the queryset to be: students = CustomUser.objects.filter(status='student', username__in=user.students.split()) How can I get user here? -
Direct assignment to the reverse side of a many-to-many set is prohibited. Use products.set() instead. Django REST Framework
I get the following error when I POST a new product with a category (the product information is formatted like this:) { "product_code": "testcode", "name": "testname", "quantity": 22, "price": 22, "categories": [{ "name": "Test category", "products": [], "categories": [] }] } the error Direct assignment to the reverse side of a many-to-many set is prohibited. Use products.set() instead. and when I use product.categories.set(**category) I get the following error set() got an unexpected keyword argument 'name' My models.py file from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) categoriesId = models.ForeignKey('self', related_name='categories',on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): product_code = models.CharField(max_length=255) name = models.CharField(max_length=255) price = models.IntegerField() quantity = models.IntegerField() categories = models.ManyToManyField(Category, related_name='products') my serializers.py file from rest_framework import serializers from products_and_categories.models import Product, Category from django.db import models class CategorySerializer(serializers.ModelSerializer): def to_representation(self, obj): if 'categories' not in self.fields: self.fields['categories'] = CategorySerializer(obj, many=True) return super(CategorySerializer, self).to_representation(obj) class Meta: model = Category fields = ("name", 'products', 'categories') class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Product fields = ("product_code", "name", "quantity", "price", 'categories') def create(self, validated_data): category_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) for category in category_data: product.categories.create(**category) return product Any idea what's going on ? -
consume Django Python service via WSO2 API manager
I'm using WSO2-2.5.0 and i want to know if WSO2 API Manager is compatible with Python based restful services or not. I have several webservices developed in Python. On Python service, I don't receive request body from WSO2. Actually the services are working fine and can communicate with them via REST Console. I debugged WSO2, it receives and sends payload to backend. I need to know how I can consume payload in Python services just like my Java services. -
Python - Django - modify fields in serializer
i have the following setup: I have a basic blog and article relation, where i get all blogs and its associated articles: class BlogSerializer(serializers.ModelSerializer): articles = ArticleSerializer(many=True, read_only=True) class Meta: model = Blog fields = ('id', 'name', 'articles') depth = 0 class BlogViewSet(ViewSetMixin, GenericAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer Now i want to keep things as the are, BUT: When the list view is called (e.g. api/blogs), only the ids of the articles should be shipped, so i extended my viewset to: class BlogViewSet(ViewSetMixin, GenericAPIView, ..): queryset = Blog.objects.all() serializer_class = BlogSerializer def get_serializer(self, *args, **kwargs): # pseudo code if self.context['request'].action == 'list': serializer = super(BlogViewSet, self).get_serializer(*args, *kwargs) serializer.fields['articles'] = serializers.PrimaryKeyRelatedField(many=True, read_only=True) serializer.is_valid() return serializer i just wanted to override the corresponding articles field with a PrimaryKeyRelatedField, so only id´s get shipped. But i get empty results(no blogs and articles at all) and i have no idea why... any ideas or suggestions? thanks and greetings! -
How to make django to recognize two urls?
I am totally new in Django and web programming and I do not even know how to ask this question precisely enough. Excuse me then if I am asking for something obvious. I am trying to put in the same folder app two different urls in one urls.py file. I noticed that Django does not recognize them and always open the first one. This is my app urls.py file: from django.conf.urls import url from second_app import views urlpatterns = [ url(r'^$', views.help, name='help'), url(r'^$', views.index, name='index'), ] This is my prooject urls.py file: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', include('second_app.urls')), url(r'^help/', include('second_app.urls')) ] and here is my views.py that is common for both pages: from django.shortcuts import render from django.http import HttpResponse def help(request): help_dict = {'help_insert':'HELP PAGE'} return render(request, 'second_app/help.html', context=help_dict) def index(request): my_dict = {'insert_me':'INDEX'} return render(request, 'second_app/index.html', context=my_dict) And now, when I am trying to request http://127.0.0.1:8000/help, everything works fine I can see the "HELP PAGE" but when I reqest http://127.0.0.1:8000/index nothing changes. How can I fix it? Thanks in advance! -
create() argument after ** must be a mapping, not list, Django REST Framework (implementing my own create method error)
when I am implementing this code-example on the documentation (I had to implement the create method myself because I have nested objects and inserting them is not supported by default) def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user https://www.django-rest-framework.org/api-guide/serializers/#writing-create-methods-for-nested-representations I'm getting this error create() argument after ** must be a mapping, not list My implementation of the example on my project is the following : def create(self, validated_data): product_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) Product.objects.create(product=product, **product_data) return product the whole serializers.py file from rest_framework import serializers from products_and_categories.models import Product, Category from django.db import models class CategorySerializer(serializers.ModelSerializer): def to_representation(self, obj): if 'categories' not in self.fields: self.fields['categories'] = CategorySerializer(obj, many=True) return super(CategorySerializer, self).to_representation(obj) class Meta: model = Category fields = ("name", 'products', 'categories') class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Product fields = ("product_code", "name", "quantity", "price", 'categories') def create(self, validated_data): product_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) Product.objects.create(product=product, **product_data) return product my models.py file: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) categoriesId = models.ForeignKey('self', related_name='categories',on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): product_code = models.CharField(max_length=255) name = models.CharField(max_length=255) price = models.IntegerField() quantity = models.IntegerField() categories = models.ManyToManyField(Category, related_name='products') can anybody … -
Django ORM GroupBy Date Ranges
I need some help on creating a Queryset in Django. If not possible, I'd go with simple iterations in python to get my results, but I'd like to get my hands on these advanced queries and understanding this one would be a great start. Don't know if that would be possible, but thanks in advance. Say we have this simplified situation: class Sell(models.Model): sku = models.ForeignKey('Product', on_delete=models.CASCADE) value = models.FloatField() amount = models.FloatField() date = models.DateField(auto_created=True, blank=True) class Promo(model.Model) name = models.CharField(max_length=100) date_start = models.DateField() date_end = models.DateField() And to use examples, let's say we have: Sell - SKU001 - 40,00 - 2units - 05/1/2018 Sell - SKU004 - 20,00 - 2units - 12/1/2018 Sell - SKU003 - 10,00 - 2units - 05/3/2018 Sell - SKU004 - 20,00 - 1units - 17/3/2018 Sell - SKU005 - 30,00 - 1units - 25/3/2018 And for the Promo Instances: Promo - NewYear - date_start 01/01/2018 - date_end 01/03/2018 Promo - FunMarchSales - date_start 01/03/2018 - date_end 01/04/2018 My Django Query should get the date_ranges from Promo and use them to GroupBy the sells returning the earnings. Something like this: New Year - 120,00 FunMarchSales - 70,00