Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
test form is vaild with valid data without posting data django
I want to ask a question, is there any possible to test form is valid with post data, which means it can generate dictionary of data automatically according to form. because I have a lot of form to test. I dont want to write data = {'A':'a', 'B':'b'}, too complicated. -
File Watcher cant find *.sass file in static folder
I have a django project and I'm using PyCharm. I wanted to add sass in my project. I have added new sass wather in File Watchers but it cant found any files in folder "static". In any other folder all is good but when I'm trying to do this in static folder nothing works. How to fix it? -
Splitting a django model using property and setters
In trying to split a model in an already working application, I used property and setters to prevent making potentially hundreds of updates within the code base. Model setup: class A(models.Model): name = models.CharField() type = models.CharField() spec = models.SmallIntergerField() @property def salary(self): self.b.salary @salary.setter def salary(self, value): self.b.salary = value self.b.save() class B(models.Model): a = models.OneToOneField(A) salary = model.IntergerField() height = model.IntergerField() Model usage model_a = A(salary=129980, height=6.00, type="several types") model_a.save() Again I"m using property and setters to avoid changing queries in old migration files and several other places where the query occur in the code. Question: Does using property / setters in this way trigger inadvertently lot of queries when model A properties are called? i.e. are there cons to this? Is there a better way this could be done? Using: Django 1.11 -
ValidationError in django Views
I'm new at django and I want to raise a ValidationError in the form, but I don't know how to do it. Right now. Most important of all I need to verify if the first 3 digits of the idItem correspond to the Category and SubCategory id. I have my Models code like this: class Categoria(models.Model): idCategoria = models.IntegerField(primary_key=True) nombreCategoria = models.CharField(max_length=200) desCategoria = models.CharField(max_length=200, blank=True) def _str_(self): return str(self.idCategoria._str_()+" --> "+self.nombreCategoria) class SubCategoria(models.Model): id = models.IntegerField(primary_key=True) idCategoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) idSubCategoria = models.IntegerField() nombreSubCategoria = models.CharField(max_length=200) desSubCategoria = models.CharField(max_length=200, blank=True) def __str__(self): return str(self.nombreSubCategoria) class Item(models.Model): idItem = models.IntegerField(primary_key=True) idSubCategoria = models.ForeignKey(SubCategoria,on_delete=models.CASCADE) idAutor = models.ForeignKey(Autor,on_delete=models.CASCADE) nombreItem = models.CharField(max_length=50) descrpcionItem = models.TextField(max_length=100) imagenUrl = models.ImageField(upload_to='itemImages', blank=True) nombreImagen = models.CharField(max_length=10, blank=True) fechaPublicacion = models.DateField(auto_now=False, auto_now_add=False, blank=True) And my view: def itemCreate(request): if request.method == 'POST': form = itemForm(request.POST, request.FILES) subcategoria = request.POST.get('idSubCategoria') message = ERROR_MESSAGE subcateg = SubCategoria.objects.get(idSubCategoria=subcategoria) cat = subcateg.idCategoria.idCategoria id = request.POST.get('idItem') if id[0] == str(cat) and id[1:3] == str(subcategoria): print("hi") form.save() else: raise forms.ValidationError(message) return redirect('sgb:itemListar') else: form = itemForm() return render(request, 'itemCrear.html', {'form': form}) Thanks in advance -
How to set Django channels self.scope["user"] with Javascript (React)
I am using the following technologies: Django Channels 2.1.2, ReactJS + reconnecting-websocket package For consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): me = self.scope['user'] print(str(self.scope['user'])) For routinig.py application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^chat/(?P<user_id>[0-9]+)/$", ChatConsumer), ] ) ) ) }) For ReactJS, I'm connecting with the socket with import ReconnectingWebSocket from 'reconnecting-websocket' ... const rws = new ReconnectingWebSocket('ws://127.0.0.1:8000/chat/30/') But Django is not picking up any user in scope? For React, I'm storing user and token in cookies. I believe it's a ReactJS fault but can somebody please help me out? Thanks! -
Is it possible to apply Djnago wagtail to my existing Django project?
I recently found wagtail, which is a very cool Django CMS library. I tried to use it following its documentation, but its installing documentation is based on starting-over Django project. I'm using ReactJS for frontend and Django as API backend. I was wondering if it's possible for me to apply wagtail to my existing Django project. -
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? -
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? -
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))) …