Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Optimizing Django app in Google App Engine
I am facing slow page load time (list page in Django admin) for a simple Django app, deployed on Google App Engine, with postgres Cloud SQL. There are fewer than 20 records. SQL time is negligible, even with 30 queries. Majority of the time is shown as domLoading I assume that domLoading is probably referring to the initial loading of the case/ page, which took 3 seconds. Most of the solutions online refer to tweaking apache/nginx settings. But since I am using Google App Engine (PaaS), I cannot directly control webserver settings. gcloud app deploy is supposed to handle the load-balancing and code versioning. How do I improve the basic load time of Django App on GAE? Both GAE and Cloud SQL are hosted in the same region. PS: I did find some answers like Optimizing my Django app on Google App Engine, but they refer to optimizing SQL queries, which is not the case here. -
Amazon s3 alternative for django app on heroku [on hold]
Is there an alternative to amazon s3 for storing and serving media files (images) for django app deployed in heroku? Can we use google drive for this purpose? -
add multiple forms to page on button click
I am working on developing a permitting app using django. This is my first django project so bear with me here... we have a default utility permit that contains some basic info like property owner and address. Then from that you can attach a sewer, or water or row or any combination of related tables to the permit. Basically I am looking for a way to return a page with the default utility permit then have a series of links or buttons to add more forms to that page. I made some model forms for each of the models and can display them individually on the page forms.py class UtilityPermitForm(forms.ModelForm): class Meta: model = UtilityPermit fields = ['...'] class SewerPermitForm(forms.ModelForm): class Meta: model = SewerPermit fields = ['...'] class WaterPermitForm(forms.ModelForm): class Meta: model = WaterPermit fields = ['...'] I successfully added them to a list and could iterate through and get them to add views.py class BuildForms(View): permits = [] utility_form = UtilityPermitForm sewer_form = SewerPermitForm water_form = WaterPermitForm permits.append(utility_form) permits.append(sewer_form) permits.append(water_form) template_name = 'engineering/UtilityPermitForm2.html' def get(self, request, *args, **kwargs): out_permits = [] for form in self.permits: out_permits.append(form()) return render(request, self.template_name, {'form': out_permits}) def post(self, request, *args, **kwargs): if request.GET.get('testButton'): … -
Set checkbox disabled if already opted by user
I designed a seat layout with checkbox code looks something like this <div class="asiento"> <input type="checkbox" value="1" id="asiento1" name="check" > <label for="asiento1">1</label> </div> <div class="asiento"> <input type="checkbox" value="2" id="asiento2" name="check" /> <label for="asiento2">2</label> </div> <div class="asiento"> <input type="checkbox" value="3" id="asiento3" name="check" /> <label for="asiento3">3</label> </div> <div class="asiento"> <input type="checkbox" value="4" id="asiento4" name="check" /> <label for="asiento4">4</label> </div> <div class="asiento"> <input type="checkbox" value="5" id="asiento5" name="check" /> <label for="asiento5">5</label> </div> I tried to fetch data from Database using loop and i am getting output like this ['1', '2'] ['5'] can i do something to remove [ ] maybe use JQuery or JS to disable the checkbox that are already selected by other users, this is the loop that i used to get value {% for seat in seat %} {{seat.useat}} {% endfor %} -
Django fetching static files in absolute path instead of relative path
I'm trying to fetch a css file from my static folder (as declared in STATIC_URL=/static/) which path is $app/src/static/css/about.css to my html file located in $app/templates/about.css. I'll show the code below The thing that works but is not advisable by Django docs is I changed the STATIC_URL = 'static/' but this is not a good practice... However this way the static variable in html is static/... and it works. In about.html: link rel="stylesheet" href="{% static 'css/about.css' %}" And I don't know if this is needed but in urls.py is the following: urlpatterns = [ .. ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Expected result in href is =static/css/about.css What happens: href = /static/css/about.css Also I'm sorry for formating errors, I'm new to posting here -
How to save a Model Form with a foreign key of User to django models
I am trying to save user API keys to a Django Model with a foreign key of User such that each set of unique API keys has a unique User associated with them in the database. I am using the built in Django User Model and I have created my own Model Form in forms.py. I have tried including user in the Model form and Meta class to no avail. I have tried passing the keys and password as parameters to the model and form before saving. I have tried using instances of the form with commit set to False before adding the User to form.user. I've tried looking up the latest Django documentation but its fragmented and hard to follow. I'm purposefully leaving out imports unnecessary to this problem. This is my Models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class UserApiDetails(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None) key = models.CharField(max_length=32) password = models.CharField(max_length=32) def __str__(self): out = "key: " + str(self.key) + '\n' + "Password: " + str(self.password) def keys_exist(self): if UserApiDetails.objects.filter(pk=User.pk).exists(): return True else: return False This is my forms.py: from django import forms from .models import UserApiDetails … -
Django user with limited permissions can see all default models in Rest Framework
I'm using Django 2.2 with djangorestframework-3.9.2 and djangorestframework_simplejwt-4.1.3. Using the admin interface I've defined some users as super users, and some with limited permissions to only view a few endpoints. However, when I log in with the limited user, the user can view everything, and it can even edit and delete entries everywhere. The user is required to log in to access the api, but once authenticated the individual permissions don't seem to work. In my settings I have the following: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', ), } Is there anything else I explicitly have to set to block access to views? An example of how my views are defined follows: class CustomersViewSet(viewsets.ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer along with the serializer and model: class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' class Customer(models.Model): identifier = models.CharField(max_length=255, unique=True) entryDate = models.DateTimeField(default=timezone.now, blank=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True ) def save(self, *args, **kwargs): user = get_request().user self.user = user super(Customer, self).save(*args, **kwargs) def __str__(self): return self.identifier Finally, the views are added in urls.py: router.register('api/customers', CustomersViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api/', include('rest_framework.urls', namespace='rest_framework')), … -
How can i display database data on a Django form?
I created a page where the user submits an order. The order is submitted to the SQLite DB and has the following fields: Time - Status - Rate. Once the order is submitted, i would like my django template to show it below an 'Active orders' tab. I don't know how to do it in terms of code, but i figured out that i need to create a query to db where all the user's `orders are fetched (maybe fetching the orders where ID = user's id?). How would i be able to perform such a operation in Django? In my views? Here is the template's view: def myview(request): item = get_object_or_404(market, item=item) if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): send = form.save() send.save() messages.success(request, f"Success") else: form = MyForm() return render(request, "main/mytemplate.html", context={"form":form}) And part of the template: <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form1 %} <button name="button1" type="submit" class="btn btn-primary">BUY</button> </form> <h3> ACTIVE ORDERS </h3> <p> Here should go the orders... </p> -
DRF: Nested serializer return in extra dictfield
I have the following object returned from a request which I want to serializer and return. 'data': [ { 'more_data': [ { 'name': 'more_data', 'value': 'test' }, ] 'data_attributes': [ { 'name': 'Package 1', 'attribute': '1', 'type': 'Test' }, ], } ] I want to return the data in the following format, basically nesting the data_attributes inside an extras DictField. { "data": [ { "name": "Package 1", "extras": { "data_attributes": [ { 'name': 'Package 1', 'attribute': '1', 'type': 'Test' } ] } } ] } I'm not sure how to write a nested serializer for this? -
django logout and redirection
i am using django authentification to make a oneToone relation with the user table. I try to use decorator @login_required to the next page after the login. when i logout and click on the back button of firefox, i always go to the previous page even if @login_required is apply. but when i refresh it redirect me on the login page. Is it a cache problem? how can i solve it? I want to do it like how the administration works def logout(request): from django.contrib.auth import logout from django.shortcuts import redirect logout(request) request.session.flush() return redirect('/') from django.contrib.auth.decorators import login_required @login_required(login_url='/') def administration(request): do something return something -
Wagtail CMS: RichTextField | URL embeds cannot be found
I have started using Django and Wagtail as an alternative to PHP solutions. I installed Wagtail following the docs and a small tutorial to get started. I have no custom settings in my settings/base.py concerning the WAGTAILEMBEDS_FINDERS. The only changes I made so far to the Home Page: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): templates = "home/home_page.html" banner_title = models.CharField(max_length=100, blank=False, null=True) banner_imgname = models.CharField(max_length=100, blank=False, null=True) body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel("banner_title"), FieldPanel("banner_imgname"), FieldPanel('body', classname="full"), ] And this is the simple home_page template: {% extends "base.html" %} {% load static %} {% load wagtailcore_tags %} {% block body_class %}template-homepage{% endblock %} {% block content %} {{ self.banner_title }} {{ self.imgname_title }} {{ page.body|richtext }} {% endblock %} All simple outputs of text from a CharField and RichTextField work fine, but the embed feature, which I -unfortunately - need the most (blog sharing all kinds of embed stuff), does not work properly. I tried Soundcloud, Deviantart, Vimeo, Instagram. Only YouTube embeds. (To confirm there are no other restrictions for the chosen links I embedded them in an editor of a WP installation (sorry :-)). I … -
Fields in custom serializers.Serializer
Why class Meta: fields = ('name') not working fields not working? I see all object, not only name. It is problem class ProjectsSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(required=True, allow_blank=False, max_length=100) isActive = serializers.BooleanField() def create(self, validated_data): return Project.objects.create(**validated_data) def update(self, instance, validated_data): instance.id = validated_data.get('id', instance.id) instance.name = validated_data.get('name', instance.name) instance.isActive = validated_data.get('isActive', instance.isActive) return instance class ProjectsCreateSerializer(ProjectsSerializer):enter code here class Meta: fields = ('name') I expect the output of fields in ProjectsCreateSerializer to be {"name": ""} but the actual output is {"name": "","isActive": false} -
Get a list of all active session keys using default session engine?
Using Django's default session engine, not the database-driven one, is it possible to get a list of all active session keys? -
should ihave to install django every time i want to access my project?
please help how to acces the django project when i quit the command prompt it just dissappears and cannot locate it yet.should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command -
django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace
I have a Django projects with two apps, "projects" and "codebox", they were running fine, then at some point I got the following error: django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace If I remove the link to my admin panel from my template this error goes away, but then I can't get to my admin panel: <a href="{% url "admin:index" %}">Admin</a> I was working in the urls.py files when this error occurred, have I changed something that is inadvertently having an impact on the admin link? Here is my top level urls.py file: from django.contrib import admin from django.urls import include, path, re_path urlpatterns = [ # path('', include('projects.urls')), path('projects/', include('projects.urls')), re_path('^accounts/', include('django.contrib.auth.urls')), re_path('^logged_out/', include('projects.urls')), path('codebox/', include('codebox.urls')), ] Here is my urls.py for "projects": from django.urls import path, include from . import views app_name = 'projects' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('insight/', views.InsightView.as_view(), name='insight'), path('logged_out/', views.LoggedoutView.as_view(), name='loggedout'), path('insight/subgen/', views.SubgenView.as_view(), name='subgen'), ] And here is urls.py for my second app, codebox: from django.urls import path, include from . import views app_name = 'codebox' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('form/', views.CreateView, name="form"), ] -
Config nested location NGINX
I have a basic issue about Nginx hope you guys help me: Now I config my location in Nginx: server { location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I want to change it into nested location: http://exp.com/api instead of the current: http://exp.com/ I tried but it's not success: server { location / { location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } } -
In Django Admin, can I display a listing of an unrelated record set alongside an admin form?
My use case is to implement something like a messaging form, allowing an administrator to write a message, then send it to group that they will filter from a list of users, from the User model. This is similar to the messaging to usergroups functionality in Joomla! so it's not too weird a use case. So my admin page for the "Message" model would need to contain the Message creation form and a second recordset of site Users, which could be filtered down to those who the administrator wishes to contact. Is this kind of thing possible in Django Admin, or do I need to dip into heavily customising an admin page? -
Django only create model for testing
I want to test a custom field. How can I create a (dummy) model just for testing? e.g.: myapp/tests/test_fields.py import pytest from django.db import models from ..fields import Percentage100Field class DummyModel(models.Model): percentage = Percentage100Field() @pytest.mark.django_db def test_percentage_100_field(): d = DummyModel.objects.create(percentage=19) -
Django ORM strange behavior; model's data retrieves just by '.values()' and not by direct access
I faced with strange behavior of django orm and cannot solve this problem. Below are interpreter output for some commands. All fields are filled right in the database and all goes fine with using '.values()' Can someone explain me that's wrong and how to fix it? >>> Models.objects.filter(id=55)[0].id 0 >>> Models.objects.filter(id=55).first().id 0 >>> Models.objects.filter(id=55).values()[0]['id'] 55 -
ChartJS graph flickering on mouseover
I'm having a ChartJS graph refresh every half-second, in order to keep up with any changes on the API. The problem I'm having is that the chart flickers and resizes on mouseover. This video captures it pretty well. I'm aware that this issue has been addressed on SO before (e.g., here and here), but the solution proposed there - to make sure to .destroy() the graph before redrawing/refreshing it - isn't solving it for me. Here's the relevant section of my code: function refresh_graph() { {% block jquery %} var chart_endpoint = "{% url 'scenario_chart_data' scenariomarket.id %}" var defaultData = [] var labels = [] $.ajax({ method: "GET", url: chart_endpoint, success: function(data){ defaultData = data.current_prices var mostLikelyIndex = indexOfMax(defaultData) labels = data.descriptions var mostLikely = labels[mostLikelyIndex] document.getElementById('mostLikely').innerHTML = mostLikely; var ctx = document.getElementById('myChart').getContext('2d'); if(myChart){ myChart.destroy(); } var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets : [{ label: 'Market price', data: defaultData, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 2 }] }, options: { elements: { line: { tension: 0 } }, legend: { display: false, }, scales: { yAxes: [{ ticks: { suggestedMin: 0, suggestedMax: 1 } }] }, animation: { … -
How to give permission to specific users in django?
I'm creating a website in which i have to give permission to my company members to view a specific page from where they can create there profile and many things, when they apply for it by clicking on (i am company member) and submit there documents and i will verify them . And i want the normal user(customers) to view the website as it is. I thought that i will create a role for my company members and I'll assign them that role from the admin panel when the apply. Is this process of giving permission is right? Or is there any best method of giving permission to the user? Any suggestions , step by step answers and tutorial link will be very helpful. -
Is it right that django migrations are running the filter of django tables2 module before running the migrations?
I have a semi large software. At one point I included tables2 into that project and started to work with it. I the filter.py file I included some basic Model filtering. Now if I delete my database and try to run a fresh migrations I get the error, that this table is not avaible. I builded a try catch around and it's working since it does not run the code snipped before the migration. class PracticephaseProjectFilter(django_filters.FilterSet): omni = django_filters.CharFilter(method=omni_search, label="Suche") practice_phase = django_filters.ModelChoiceFilter(queryset=PracticePhase.objects.filter(pk__in=get_pp_for_specialpermit())) class Meta: model = PracticePhaseProject fields = ['practice_phase'] def __init__(self, *args, **kwargs): super(PracticephaseProjectFilter, self).__init__(*args, **kwargs) def get_pp_for_specialpermit(): pp = [] today = date.today() # check if SS or WS required if 4 <= today.month <= 9: # current SS, project will be sought for WS this year pp_str = [str(today.year)[-2:] + "s", str(today.year - 1)[-2:] + "w"] # we are in WS, check correct year for SS elif today.month > 9: pp_str = [str(today.year)[-2:] + "w", str(today.year)[-2:] + "s"] # we are allready in the year of next SS else: pp_str = [str(today.year - 1)[-2:] + "s", str(today.year - 1)[-2:] + "w"] try: for _pp in PracticePhase.objects.filter(semester__name__in=pp_str): pp.append(_pp.pk) except: pass return pp Now if I remove the … -
ModuleNotFoundError: No module named 'oscar.app' in Django Oscar
I just installed Oscar module for my website and all tables are stored in database, but now i am using this module on my urls.py file but it's giving me an error ModuleNotFoundError: No module named 'oscar.app' Please help me to solve this issue... Here is my urls.py file.... from django.conf.urls import include, url from django.urls import path, re_path from django.contrib import admin from oscar.app import application urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', admin.site.urls), (r'', include(application.urls)), # path('', include("frobshop.urls")), ] -
Create a python file on Server
We got a wierd problem I habent found a solution for on stackoverflow. I realised that when ever i need to create a .py file the server is getting an Internal Server - Error 500. When i test everything local on my windows 10 it works fine and creates the files and is running without an error. Now on my Windows Server i get always an error 500 but the files will be created. HTTP Error 500.0 - Internal Server Error d:\django\virtualenv0\scripts\python.exe - The FastCGI process exited unexpectedly I already added permission to all the python files to be able to create a new file. I never had such an error and i dont know why. lines = f1.readlines() with open("alpha/alpha/settings_inspectdbF.py", 'w+') as f2: for line in lines: f2.write(line) Is there a way to get more information to this error or not? DEBUG = TRUE is already active but i dont get a yellow error page. Can I ignore that error or does anyone have any idea? Thanks -
How to send data from React form to Django backend server without getting the Unsupported media type error?
React newbie here, I am trying to create a simple form in React for my backend based on Django, and I keep getting the error 415 Unsupported Media Type. My backend is not getting the data sent at all. What am I doing wrong here? import React, {Component} from 'react'; import ReactDOM from "react-dom"; class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { console.log(this.state.value); fetch("http://192.168.0.133:8000/createrfq/", { method: "POST", cache: "no-cache", headers: { "content_type": "application/json" }, body: JSON.stringify(this.state.value), }) .then(response => response.json()) } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange}/> </label> <input type="submit" value="Submit"/> </form> ); } } export default NameForm