Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement a global class in django
I am currently working on a networked multiplayer game using django and django channels for websockets. I currently have my project set up where players send data to the server which then processes that data in a "GameManager" class that processes all game logic and interactions between all players. This works perfectly fine in my dev environment, but when I tried setting up my project for production, my global "GameManager" class does not seem to retain it's data across multiple requests. I'm guessing that since I'm using gunicorn in my production environment, my django project is running amongst multiple processes that each have their own instance of my classes. My question is how can I implement some sort of global class in django to handle all the game logic that will be shared across all requests? I can't use sessions because I need this data to be shared by ALL connected clients, and I'm skeptical of using a solution such as redis because I would need to be reading/writing to it multiple times a second, so keeping it within python would help me keep things running smoothly. Any help would be greatly appreciated. -
how to use a forloop such that the if the "IF" statement in the loop is satisfied the loop ends in Django Templates
I have 2 Django models Review and Item that I am working with. I want to see if the user has already reviewed the item. If yes he sees the review score. if no he sees the button to review the item I have the below Review model class Review (models.Model): review_from = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_from') review_for = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='review_for') item = models.ForeignKey(OrderItem, related_name='items') Defining the variables in the view context (pseudocode) admin = User.objects.get(username="admin") admins_reviews = Review.objects.filter(review_from__username = "admin") Below is my template {% for item in buyers_items %} {% for review in buyers_review%} {% if review.item.id == item.id %} <button class="text-success">Your rating<br/><b>{{review.ratings}}/10</b></button> {% else %} <a href="{% url ... %}"> <button>Leave Review</button> </a> % endif %} {% endfor %} {% endfor %} If I do this I get a below error How can I overcome this problem. -
How to serve static if exist, otherwise pass to wsgi application?
I am converting a static website to Django with Apache mod_wsgi. How can I have Django serve .html files if they don't already exist in a static files location. For example, user requests www.mysite.com/test.html. If test.html exists in my static directory then serve it using Apache. If the file does not exist then pass the request to Django. I know of uWSGI and it has a parameter --check-static which will do what I'm asking (https://uwsgi-docs.readthedocs.io/en/latest/StaticFiles.html). However, it's not practical for me to use uWSGI for this application. Does anyone know if this is possible using mod_wsgi and how? -
Load JSON file in alphabetical order - Django
With this method: def postcodes(request): with open('core/stores.json') as f: data = json.load(f) return JsonResponse(data, safe=False) I load a local json file into this url: urlpatterns = [ path('stores/', views.postcodes, name='postcodes'), ] It renders flawlessly, now, my json file looks like this: [ { "name": "St_Albans", "postcode": "AL1 2RJ" }, { "name": "Hatfield", "postcode": "AL9 5JP" }, { "name": "Worthing", "postcode": "BN14 9GB" }, And so on... As You can see, this is in alphabetical order, if You take into account the postcodes. What I need, is to read this file, and render it in alphabetical order, but not as it is (by postcode), but by name. I don't think I can use the builtin Django loops or tags for this, since they work with models or stored data mostly. But I'm not completely sure. What could be a quicker approach to this, instead of saving everything into a database? I took a look into serializers but that's for django-rest-framework I'm using plain requests here. Any ideas? I'm not using any template right now, it is just rendered on browser as it is. -
The view core.views.postcodes didn't return an HttpResponse object. It returned None instead
I want to render a local json file I'm loading from a view in Django. I have this function on my views.py file: def postcodes(request): data = open('core/stores.json').read() jsonData = json.loads(data) On my urls.py: urlpatterns = [ path('stores/', views.postcodes, name='postcodes'), ] It throws me this error: Internal Server Error: /stores/ Traceback (most recent call last): File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 139, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view core.views.postcodes didn't return an HttpResponse object. It returned None instead. I think this comes from the fact that I'm using request as a parameter on my postcodes function. Any ideas on how can I load this json file on my view? I'm using Django 1.11 -
Passing context variable in generic.UpdateView
I have a template begining with: {% extends load_template %} the load_template takes values from this condition in my view if user == 'guest': load_template = 'damage/menus/menu.html' else: load_template = 'damage/menus/sidebarmenu.html' I use a generic.UpdateView for update (which returns an error , because load_template variable hasn't got a value) How can I pass value to this variable in this UpdateView? -
Django Group Permission Created view duplicates query
Using simple CreateView: class GroupCreateView(CreateView): model = Group fields = '__all__' template_name = 'group/add.html' success_url = reverse_lazy('group_list') It Creates duplicate query. All getting from permission. How to reduce query -
Django dropdown menu links
i currently have a dropdown menu in my code and i would like the bit that the user hovers over to be clickable as well, but currently the href is being used by javascript. This is for the archive drop-down menu and the calendar menu. Any help would be much appreciated and i am very new so pls dont hurt me HTML: {%load static%} <html> <head> <title>Athletics Program</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> </head> <body> <ul> <li><a href="{% url 'index' %}">Home</a></li> <li class="dropdown"> <a href="javascript:void(0)" class="dropbtn">Archive</a> <div class="dropdown-content"> <a href="{% url 'ArchiveHome' %}">Records</a> <li class="dropdown" a href="{% url 'ArchiveHome' %}"> <a href="javascript:void(0)" class="dropbtn">Calendar</a> <div class="dropdown-content"> <a href="">January</a> <a href="">Feburary</a> <a href="">March</a> <a href="">April</a> <a href="">May</a> <a href="">June</a> <a href="">July</a> <a href="">August</a> <a href="">September</a> <a href="">October</a> <a href="">November</a> <a href="">December</a> </div> </li> <div class="Login"> <li><a href="">Login</a></li> </div> </ul> <div class="twitter"> <a class="twitter-timeline" data-width="400" data-height="626" data- theme="dark" href="https://twitter.com/KWS_Sport?ref_src=twsrc%5Etfw">Tweets by KWS_Sport</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </div> <img src="{% static 'Logo.jpg' %}"" alt="Kingswood Logo" width="200" height="200" border= 1 class="imageOverBackground"> </body> CSS: body{ margin: 0px; background-image: url("background.png"); } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333333; width: 966px; } li { float: left; } li a, .dropbtn { display: inline-block; … -
with which tutorial to create a crowdfunding site like Kickstater step by step in django
I would like to launch a crowdfunding site for a small community like kikstarter on django, how can I do it? I have an intermediate level in web programming and python -
FileNotFoundError at /stores/ - Loading local json file into a Django view
I have this function: def postcodes(request): data = open('stores.json').read() jsonData = json.dumps(data) This is my directory structure: ├── core │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── stores.json │ ├── templates │ │ └── core │ │ ├── github.html │ │ ├── home.html │ │ ├── oxford.html │ │ ├── stores.html │ ├── tests.py │ ├── urls.py │ └── views.py The function is on my views.py file, and the file stores.json is on the very same directory. This is the traceback: Internal Server Error: /stores/ Traceback (most recent call last): File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kristian/tails/restful-apis-example/core/views.py", line 83, in postcodes data = open('stores.json').read() #opens the json file and saves the raw contents FileNotFoundError: [Errno 2] No such file or directory: 'stores.json' [25/Nov/2018 20:07:31] "GET /stores/ HTTP/1.1" 500 75613 I was thinking about declaring something like the BASE_DIR for static or templates, but I'm not sure about that approach. I've never loaded a local json file into Django, so, … -
Django - How to dynamically restrict category of blog post?
I'm working on a blog project. I want to set primary and secondary categories for the posts. For example, primary category: Music, Movie, Computer and secondary categories for each primary category like: Music - Dance, Rock, Country / Movie - Script, Teaser, Review / Computer - Hardware, Software / And when I create a new post I want to restrict secondary category choices according to the primary category I chose. (to be precise, in the post creation form, first, I want both primary and secondary categories to be shown in dropdown menus, and second, after I choose a primary category I want only the secondary category choices which belong to the primary category I chose to be shown in the dropdown menu for secondary category.) Currently my models.py: class PrimaryCategory(models.Model): title = models.CharField('Primary Category', max_length=50) class SecondaryCategory(models.Model): title = models.CharField('Secondary Category', max_length=50) primary = models.ForeignKey(PrimaryCategory,on_delete=models.CASCADE) class Post(models.Model): title = models.CharField(max_length=256) content = models.TextField() create_date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) primary_category = models.ForeignKey(PrimaryCategory, on_delete=models.CASCADE, null=True) secondary_category = models.ForeignKey(SecondaryCategory, on_delete=models.CASCADE, null=True) and I searched and I can maybe use ForeignKey.limit_choices_to in my ModelForms, but I'm stuck here. Could anybody kindly help writing my forms.py? currently I only have forms.py like: … -
python says apple is not equal to apple
I have an odd situation in my django code, where python refuses to accept that two strings are equal: def depticon(depta): print(f'depta is {depta}') print(f'Testing |{depta}| against |Ear, Nose, Throat|') if depta=="Ear, Nose, Throat": icon = "ear.png" print("Matched ENT") else: print("No match") icon = "health-sign.png" print(f'Icon is {icon}') return icon This is how it is called. Here, clinics is a queryset: specialties = [] specialtytext = [] specialtyicon = [] for clinic in clinics: if clinic.doctorid.dept not in specialties: dept = clinic.doctorid.department specialties.append(dept) specialtytext.append(depttext(dept)) specialtyicon.append(depticon(dept)) See the output: depta is Ear, Nose, Throat Testing |Ear, Nose, Throat| against |Ear, Nose, Throat| No match Icon is health-sign.png I put the | character around the string to check whether there are any special characters in the string. -
rawsql equivalent django queryset
I would like to write django queryset which is equivalent of below query with one hit in db. Right now I am using manager.raw() to execute. with annotate, I can generate the inner query. But I can't use that in the filter condition (when i checked queryset query, it looks like ex1). select * from table1 where (company_id, year) in ( select company_id, max(year) year from table1 where company_id=3 and total_employees is not null group by company_id); Ex1: 'SELECT table1.company_id, table1.total_employees FROM table1 WHERE table1.id = (SELECT U0.company_id AS Col1, MAX(U0.year) AS year FROM table1 U0 WHERE NOT (U0.total_employees IS NULL) GROUP BY U0.company_id ORDER BY NULL)' I appreciate your response. -
Using django with sqlite on aws lambda
I am trying to deploy my django app on aws lambda using zappa. However, when I try to login to the app I get attempt to write a readonly database. My understanding is that this is because sqlite is an embedded database and you can't use embedded databases on lambda because they require write-access which is not possible on lambda and just generally not a good idea to try and persist data on lambda. Is this correct? Is my only option to thus switch to using postgres or mysql or another server database? -
django throws 'function' object has no attribute 'objects', while picking data from models
I'm actually playing with manual signin forms and while I was trying to query data from database it threw me this error..... views.py ----section def signin(request): username = 'not logged in' notify = "" if request.method == "POST": form = signinForm(request.POST) if form.is_valid(): username = form.cleaned_data['user_name'] password = form.cleaned_data['password'] signup_data = signup.objects.all() # focus here for data in signup_data: name = data.user_name passw = data.password if name == username and passw == password: post = form.save(commit=False) post.save() request.session['user_name'] = username return redirect('/home') notify = "Incorrect User name or Password" return redirect("/home/signin") else: form = signupForm() signins=blog.objects.all() number=len(signins) return render_to_response('blogger/signin.html', {'form':form, 'signins': signins, 'number':number, 'notify': notify}, RequestContext(request)) -
What is the reason that celery should not run as root?
I see recommendations in the shell that I shouldn't run celery as root, that it is "absolutely not recommended!". Can someone explain this? -
Can't get XMLHttpRequest response with async:true
In Rich Text Editor I want to upload local images into server media folder. For this, I made a XMLHttpRequest. The request with a downloadable file is sent to the server, then a function on the server saves the file and returns its url. The returned url should be displayed on the Text Editor dialog box. At first I tried this code and everything worked fine with async:false parameter. In the dialog box appeared relative url of file and I could load it on the view page. The picture below shows successful image uplod. file_picker_callback: function(cb, value, meta) { if (meta.filetype == 'file') { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'MIME_type'); input.onchange = function () { var file = this.files[0]; var reader = new FileReader(); // FormData var fd = new FormData(); var files = file; fd.append("file",files); var location = ""; // AJAX jQuery.ajax({ url: "/fileupload/file/", type: "POST", data: fd, dataType: 'json', contentType: false, processData: false, async: false, success: function(response){ location = response.fileurl; } }); reader.onload = function(){ //call the callback and populate the Title field with the file name cb(location, { download : files.name }); }; reader.readAsDataURL(files); }; input.click(); } }, But then, in the console I get … -
unit test get_absolut_url django
I'm pretty new to django, and writing tests. I'm currently working on a project that has two models, Project and Technologies. The project models has a many to many relationship with the technologies model. I have a view that overrides the get_queryset method. On my coverage report this method is my only miss. I am looking for guidance on how to write a unit test for this method. Thank you for taking the time to answer my question. models.py from django.db import models from django.template.defaultfilters import slugify from django.urls import reverse class Technologies(models.Model): name = models.CharField(max_length=64, unique=True) slug = models.SlugField() def __str__(self): return self.slug def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Technologies, self).save(*args, **kwargs) class Project(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=128) repo = models.URLField() slug = models.SlugField() image = models.ImageField( upload_to='project_images', default='project_images/default_project.png') technologies = models.ManyToManyField(Technologies) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("projects:detail", kwargs={"slug": self.slug}) views.py from django.views.generic import DetailView, ListView from .models import Project class ProjectsListView(ListView): model = Project class ProjectDetailView(DetailView): model = Project class TechnologiesListView(ListView): model = Project allow_empty = False # If list is empty 404 def get_queryset(self): return Project.objects.filter(technologies__slug=self.kwargs['slug']) urls.py from django.urls import path from … -
URl redirection issue in Django 2
I'm new to Django and trying to build a web app with the following structure. I need your help to understand what Im doing wrong. The flow of the application is shadesProductUploader.urls will forward '' to authSection for login and after a successful login user should be redirected to mainSection 'home/'. Urls.py files are shadesProductUploader.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('authSection.urls')), ] authSection.urls from django.contrib import admin from django.urls import path, include from . import views app_name = 'authSection' urlpatterns = [ path('', views.login_view, name='login'), ] mainSection.urls from django.contrib import admin from django.urls import path,include from . import views app_name = 'mainSection' urlpatterns = [ path('home/', views.home), ] and the view.py in authSection def login_view(request): next = request.GET.get('next') form = userLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) login(request,user) if next: return redirect(next) context={'user':user} return redirect('home/') return render(request, 'login.html', {'form': form}) after a successful login I get this error. What Am I missing? Not sure why I see a Url of home/ home/ -
Reverse lookup 'QuerySet' object has no attribute
I have the following Models where I define a trucking company and their insurance company. Models.py: class Truckers(models.Model): DOT_Number = models.IntegerField(primary_key=True) Address = models.CharField( max_length=200) CaliIns_FK(models.Model): DOTNmb = models.ForeignKey(Truckers, on_delete=models.CASCADE) CoName = models.CharField(max_length=20) There are many truckers and not as many insurance companies. I am trying to get a list of every Trucker that has insurance. I tried the following as per django: truck = Truckers.objects.all() filtered = truck.caliinsfk_set.filter(truckers__isnull=True) and filtered = truck.caliins_fk_set.filter(truckers__isnull=True) getting error: AttributeError: 'QuerySet' object has no attribute 'caliinsfk_set' -
load 2 folder static in django
in my project,I have 2 folder static. when I go into web game, django can load static js, css in folder game\static but it can't load img. This is my directory structure: go to web game, the chess not show pieces: It load folder js and css but not load folder img in file chessboard.js: b.pieceTheme="static/img/chesspieces/wikipedia/{piece}.png" This is my static configuration in settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] I have a template that renders chess: {% load static %} <script src='{% static "js/chess.min.js" %}'></script> <script src='{% static "js/chessboard-0.3.0.min.js" %}'></script> <script src='{% static "js/main.js" %}'></script> -
Django update user data
Ребят help Как реализовать изменение данных user-профиля в Django Rest Framework? Ребят прям проблема никак не могу сделать серилайзер типа: class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate_new_password(self, value): validate_password(value) return value -
Stuck with django form validation
I'm trying to get validation running on a django form used to retrieve a list of objects in a ListView View. Despite having read django docs and many other questions here, I can't find out what's wrong in this simple test code: form.html <form action="list.html" method="get"> {{ form }} <input type="submit" value="Submit"> </form> list.html <ul> {% for area in object_list %} <li>{{ area.name }}</li> {% endfor %} </ul> forms.py from django import forms class SearchArea(forms.Form): area = forms.CharField(label='Area code', max_length=6) def clean_area(self): area = self.cleaned_data['area'].upper() if '2' in area: raise forms.ValidationError("Error!") return area views.py class HomePageView(FormView): template_name = 'form.html' form_class = SearchArea class AreaListView(ListView): template_name = 'list.html' model = AreaCentral def get_queryset(self): q = self.request.GET.get('area') return AreaCentral.objects.filter(area__istartswith=q) When I try to submit something like "2e" I would expect a validation error, instead the form is submitted. Moreover I can see in the GET parameters that 'area' is not even converted to uppercase ('2E' instead of '2e'). -
ModuleNotFoundError with Django, not recognizing app's name
I'm getting the same exception whenever I try to run a Django command (makemigrations, migrate, shell, runserver). I looked at other posts but nothing has helped. I changed around the naming of the app but that didn't work either. The exception traceback is: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f3c3ff9dc80> Traceback (most recent call last): File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/usr/projects/myproject/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'api' My apps.py is: from django.apps import AppConfig class ApiConfig(AppConfig): name = 'api' verbose_name = 'Project API' and in my __init__.py for the main project I have: default_app_config = 'api.apps.ApiConfig' and my INSTALLED_APPS is: INSTALLED_APPS = [ 'api', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Command "python setup.py egg_info" failed with error code 1 when trying to install unirest
I got this error after running the command pip install unirest to use the unirest in my views.py. I am trying to use the api of petrol price in my project in which run this command (geo) ABHISHEKs-MacBook-Air:map abksharma$ pip install unirest Collecting unirest Using cached https://files.pythonhosted.org/packages/92/da/2149cbd7a8c78f8b76b377379c1bda64ec36cc13315d55f6f7de6d094ac5/Unirest-1.1.7.tar.gz Collecting poster>=0.8.1 (from unirest) Using cached https://files.pythonhosted.org/packages/9f/dc/0683a458d21c3d561ab2f71b4fcdd812bf04e55c54e560b0854cea95610e/poster-0.8.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/setup.py", line 2, in <module> import poster File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/poster/__init__.py", line 29, in <module> import poster.streaminghttp File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/poster/streaminghttp.py", line 61 print "send:", repr(value) ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip- install-vf9ffv_s/poster/ views.py from django.shortcuts import render import requests import unirest def petrol(request): response = unirest.post("https://fuelprice.p.mashape.com/", headers={ "X-Mashape-Key": "eqPyWAd3Wrmsh52b6fvG3AQ5T2ygp1KZhDfjsng702Sd7DmWN7", "Content-Type": "application/json", "Accept": "application/json" }, params=("{\"fuel\":\"p\",\"state\":\"dl\"}") ) price = response.json() return render(request, 'petrol/petrol.html', {'price':price}) url.py from django.urls import path from .import views urlpatterns = [ path('', views.petrol, name='petrol') ]