Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.)
I am really with Django and I am getting a little bit crazy with this issue. I created a new project and app in Django, runserver without problems, but if I ran : django-admin check Im gettin this error: ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to solved with differents solutions proposed but none of them worked (probably bad execution by me, idk). Really hope you can help me guys! Thanks in advance, Best. -
fetching data from django models
I am a newbie with Django. I created a table using Django models and inserted an object using the python shell. When I access the object using object id on Django template, I get the result as "{{obj.id}}-{{obj.content}}" rather than the actual data values. The views.py file from django.shortcuts import render from django.http import HttpResponse, Http404 from .models import Tweet # Create your views here. def home_view(request, *args, **kwargs): return HttpResponse("<h1>Hello World!<h1>") def tweet_detail_view(request, tweet_id, *args, **kwargs): try: obj = Tweet.objects.get(id = tweet_id) except: raise Http404 return HttpResponse("<h1>Hello {{obj.id}} - {{obj.content}}</h1>") The models.py file from django.db import models # Create your models here. class Tweet(models.Model): content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) The urls.py file from django.contrib import admin from django.urls import path from tweets import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view), path('tweet/<int:tweet_id>', views.tweet_detail_view), ] The Shell (base) ankita@ankita-HP-Laptop-15-bs0xx:~/dev/trydjango/tweetme$ ./manage.py shell Python 3.7.4 (default, Aug 13 2019, 20:35:49) Type 'copyright', 'credits' or 'license' for more information IPython 7.8.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from tweets.models import Tweet In [2]: obj = Tweet.objects.get(id = 1) In [3]: obj Out[3]: <Tweet: Tweet object (1)> In [4]: obj.content Out[4]: 'Hello World!' In [5]: … -
How to get selected value from drodown of parent template in to the view in Django where template inheritance is used
Just started learning Django where I faced this problem I want to create eCommerce site where users can select their location(Like State & Area) and accordingly the products will be displayed to do this I have already created two drop downs in the navbar.html which is extended by the base.html which is extended by the home.html. cart_template_tags.py: register = template.Library() @register.filter def load_city(request): locations = Locations.objects.filter() return locations @register.filter def load_areas(request): locations = Area.objects.filter(city__city_names="Pune") return locations navbar.html: {% load cart_template_tags %} <form method="GET" action="."> <ul class="navbar-nav nav-flex-icons"> <select id="city" class="form-control" name="city"> <option selected>city...</option> {% for cityVal in request.user|load_city %} <option value="{{ cityVal }}">{{ cityVal }}</option> {% endfor %} </select> <select id="area" class="form-control" name="area"> <option selected>area...</option> {% for areaVal in request.user|load_areas %} <option value="{{ areaVal }}">{{ areaVal }}</option> {% endfor %} </select> <button type="submit" class="btn btn-primary">Search</button> </form> I have displayed products using home view where I rendered home.html Views.py class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" how can I get the value which I have selected in drop down "city" & "area" in HomeView ? If you have any suggestion please suggest or if you know any opensource code where this functionality (Location wise product display) is … -
Django translation does not work in functions called from view
I used django and DRF in my site and add translations to it. In some cases translation does not work. Pseudo code is: View file from django.utils.translation import ugettext as _ class UpdateView(CustomUpdateAPIView): def patch(self, request, id): if conditon: utilities.check_status(request.user) else: raise CustomException(detail=_('Some message')) # works fine utilities file from django.utils.translation import ugettext as _ def check_status(user): if condition: raise CustomException(detail=_('Some other message')) # does not translate I add translation and compile messages. translation.get_language() is OK in check_status function and recognizes accept language of user correctly. But translation does not work for unknown reason. Do I need to add any thing to force translation in such functions? -
django_heroku not found when running local server, deployed site works fine
I've just deployed my site with heroku and it seems to be working fine. I tried going back to my regular localhost:8000 to make some changes without having to wait for the push every time, but it now gives me ModuleNotFoundError: No module named 'django_heroku' I have import django_heroku django_heroku.settings(locals()) in my settings.py and when running pip freeze I get django-heroku==0.3.1 gunicorn==20.0.4 psycopg2==2.8.5 Everything seems to be working fine, although when trying to pip install psycopg2 I run into another error error: command 'gcc' failed with exit status 1 My heroku app seems to be working fine, but I can't get the localhost:8000 to run again, is there something I can do here? -
Dynamic forms - Django - ckeditor
I am having trouble with my ckeditor in dynamic form. When I "copied" the row and make new one to add another element, all inputs works fine and I am able to add/write into them. But I ma not able to write into ckeditor, only in the first one. But when I try to send the form, it looks okay and even the fifth dynamic ckeditor is send but with zero content since I am not able to write in it. Strange think is that when I try to click for example bold in the other dynamically created ckeditor, the change is make in teh first one :D Can someone help me please? Or do you have the same issue? Here is my code in html: {{ formset.management_form }} {% for form in formset %} <li class="list-group-item form-row"> <h6 style="margin-bottom: 0rem;"> <div class="row"> <div class="col-xl-12 col-md-12 col-sm-12"> <button class="btn btn-danger remove-form-row" style="float: right;"><i class="feather icon-trash-2 mr-25"></i> Delete</button> </div> </div> <div class="row"> <div class="col-md-10 col-12"> <div class="form-label-group"> <div class="text-bold-500 font-medium-1 mb-1">Control / Test title <i class="feather icon-help-circle text-muted cursor-pointer" data-toggle="tooltip" data-placement="right" title="Enter name of control."></i></div> {{ form.controlname }} </div> </div> <div class="col-md-6 col-12"> <div class="form-label-group"> <div class="text-bold-500 font-medium-1 mb-1">Client contact name: … -
Django Rest Framework API not working as expected
I really don't understand why it is giving me the below error, it was working fine then it just decided it didn't want to work anymore. My fitness Model has a user field which is a foreign Key to the accounts model. any idea or suggestion would be appreciated. Thanks Error : ImproperlyConfigured at /api/fitness/shoulders/ Field name title is not valid for model Profile. accounts Models.py from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile**strong text**' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Fitness Models.py from django.db import models from accounts.models import Profile class FitnessPost(models.Model): title = models.CharField(max_length=100) description = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Profile, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title Fitness Serializers.py from rest_framework import serializers from fitness.models import FitnessPost class FitnessPostSerializer(serializers.ModelSerializer): class Meta: model = FitnessPost fields = [ 'title', 'description', 'timestamp', 'user', 'slug' ] Fitness Views.py from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from fitness.models import FitnessPost from … -
i have created two templates one inside the project and another inside the app and error is coming template does not exist
**views.py from django.shortcuts import render from django.urls import reverse_lazy from django.http import HttpResponse from django.views.generic import (View,TemplateView, ListView,DetailView, CreateView,DeleteView, UpdateView) from . import models Create your views here. Original Function View: # def index(request): return render(request,'index.html') # # Pretty simple right? class IndexView(TemplateView): # Just set this Class Object Attribute to the template page. # template_name = 'app_name/site.html' template_name = 'index.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['injectme'] = "Basic Injection!" return context class SchoolListView(ListView): # If you don't pass in this attribute, # Django will auto create a context name # for you with object_list! # Default would be 'school_list' # Example of making your own: # context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_details' model = models.School template_name = 'basic_app/school_detail.html' class SchoolCreateView(CreateView): fields = ("name","principal","location") model = models.School class SchoolUpdateView(UpdateView): fields = ("name","principal") model = models.School class SchoolDeleteView(DeleteView): model = models.School success_url = reverse_lazy("basic_app:list") class CBView(View): def get(self,request): return HttpResponse('Class Based Views are Cool!') urls.py of application from django.urls import path from . import views app_name = 'basic_app' urlpatterns = [ path('',views.SchoolListView.as_view(),name='list'), ] [list of files in project][1] List item urls.py of project from django.contrib import admin from django.urls import path, include from basic_app import views … -
"python manage.py makemigrations" Traceback errors after creating models.py in Django
All of these errors only started happening when i did the models.py, to the best of my knowledge i didn't write any of my code wrong. Previous "makemigrations" worked. It seems like a lot of the Traceback errors have nothing to do with the models.py though. (hopefully these are easy to read, sorry) The traceback error: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django /core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/core/management/init.py", line 377, in execute django.setup() File "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/home/alatimer/Environments/djangoproject/blog/models.py", line 6, in class Post(models.Model): File "/home/alatimer/Environments/djangoproject/blog/models.py", line 9, in Post date_posted = models.DateTimeField(defualt=timezone.now) File "/home/alatimer/Environments/DjangoTutorial_env/lib/python3.6/site-packages/django/db/models/fields/init.py", line 1107, in init super().init(verbose_name, name, **kwargs) TypeError: init() got an unexpected keyword argument 'defualt' models.py: from django.db import models from django.utils import timezone … -
Django 3 admin link is coming without css
The Admin link is missing css, returns 404 when doing view source. The .conf file is <VirtualHost *:80> ServerAdmin webmaster@example.com DocumentRoot /var/www/django/medicalai ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/django/medicalai <Directory /var/www/django/medicalai/static> Require all granted </Directory> <Directory /var/www/django/medicalai> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess medicalai python-path=/var/www/django/medicalai python-home=/var/www/django/venv WSGIProcessGroup medicalai WSGIScriptAlias / /var/www/django/medicalai/medicalai/wsgi.py WSGIPassAuthorization On </VirtualHost> The Static file contains. STATIC_DIR = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] The static folder and files are here. /var/www/django/medicalai/static/admin/css All the files and folders are downloaded by using python manage.py collectstatic. But there is no CSS when I open http://example.com/admin/login/?next=/admin/ Please help to point the mistake. -
Djano Rest Framework non-model serializer show selective fields
I want to selectively display fields in my serializer. I do not have any Django model (use external resources). This is my serializer. class EmployeeSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=100) result = serializers.ReadOnlyField() def validate(self, attrs): first_name = attrs.get('first_name') attrs['result'] = transform_only( filter_by_fn(first_name) ) return super().validate(attrs) class Meta: fields = ('result',) First_name is a query_param. Result is the only field I want to use in serializer to display. In validate method I download data for that field. My question is how can I display only some fields? Meta class seems to not working (probably because of lack of model). I want also avoid ugly solution like Response(data=serializer.data['result'], ... My ViewSet: class FilterByNameViewSet(viewsets.ViewSet): def list(self, request): serializer = Employee2Serializer(data=self.request.query_params) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=200) -
DRF ModelViewset like functionality with django-graphene
I use DRF for all my django projects, but I aim to move to graphql/django-graphene given graphql's flexibility. But I like very much what DRF gives me, minimal code for CRUD requirements over django models, on the other hand from what I have read of django-graphene, I can't just inherit a class and hope crud to work out of the box for even simple models. Is there any way to achieve the same minimal code for simple crud in django-graphene? When I researched, the single solution i found was hasura detailed on this blog. I want to validate that I am thinking right (that what I want is not in django-graphene) and if there are any solutions except hasura -
How to random model in django?
User on main.html can choose category from select and get the question. App list all filtered questions by category. How to random questions and show the only one question? I see, the all questions are qs in ShowFilterView, but how take questions and randomize them? views.py: def is_valid_queryparam(param): return param != '' and param is not None def filter(request): qs = Cards.objects.all() categories = Category.objects.all() category = request.GET.get('category') if is_valid_queryparam(category): qs = qs.filter(categories__name=category) return qs def MakeFilterView(request): qs = filter(request) context = { 'queryset': qs, 'categories': Category.objects.all() } return render(request, "cards/main.html", context) def ShowFilterView(request): qs = filter(request) context = { 'queryset': qs, 'categories': Category.objects.all(), } return render(request, "cards/result.html", context) models.py: class Question(models.Model): name = models.CharField('Вопрос', max_length=30) def __str__(self): return self.name class Category(models.Model): name = models.CharField('Категория', max_length=20) def __str__(self): return self.name class Cards(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) def __str__(self): return str(self.question) result.html: {% extends 'base.html' %} {% block content %} {% for cards in queryset %} {{ cards.question.name }}<br/> {% endfor %} {% endblock %} -
Python: issues with watchdog.observers.join()
I am currently working on a django project and trying to import models from a python source file I typed python manage.py shell < dummy_source.py in cmd and it resulted in an error: observer.join() ^ SyntaxError: invalid syntax However, when I just typed python dummy_source.py, it worked without any problems. I have gone online to find something useful but there are not any. I would love to know why does this happen, thanks in advance. Here is the content of dummy_source.py: import os, time, sys import subprocess as proc from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MyHandler(FileSystemEventHandler): def on_created(self, event): print("Created!") os.system('cmd /c "mkdir workspace"') print("Deleted!") os.system('cmd /c "rmdir /s /q workspace"') event_handler = MyHandler() observer = Observer() observer.schedule(event_handler, path = 'media/submited_files', recursive = False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() -
how can i ckeditor in form that i created?
i create form with input and text area fields. in models that i have: title = models.CharField(max_length=200) description = RichTextUploadingField(blank=True,null=True,config_name='default') but in the template that i used form tag,i can not see text area as editor: <form> <input type="text" name="title" required <textarea name="text" cols="50" rows="15" required></textarea> </form> -
Filtering wrong using a timestamp range in django views
When I want to filter my model using one exactly date I use the following code line, today = datetime.datetime.now().date() today_data = DevData.objects.filter(data_timestamp__date=today) And when I want to filter using a range of days, I use the following code line, last7days = datetime.datetime.now().date() - datetime.timedelta(days=7) last7days_data = DevData.objects.filter(data_timestamp__range=(last7days,today)) The problem is that when I use this second code, appears a warning and runs very very slow, RuntimeWarning: DateTimeField DevData.data_timestamp received a naive datetime (2020-05-31 00:00:00) while time zone support is active. How can I do it better? I found this post, but don't understand how to solve it. Can somebody help me please? -
how to set up authentication for reactjs and django?
while i was working on my final school project i had i problem adding the ckeditor to my recat app linked to my django project so i cheated, and created a form page with djnago template where it's easy to use the ckeditor (the main problem in react was with the image upload ), so now i had an other problem is authentication so i didn't know if i should use the djnago-knox token authentication and how to secure the page of the form created in django default template the two problems that i have are : - to secure the path so i can not access the page only if the user is logged in - and how to pass the id of the user in to form so the qeustion is what's the best autentication option to secure the frontend ( reactjs ) and the backend (the django template) -
Continuing a Project using Pycharm instead of Visual Studio
I am currently in the middle of a Django project and considering switching from Visual Studio Code to Pycharm but after activating the Virtual Env it is not showing any Project Interpreter. Also when I type in the terminal python manage.py runserver it is saying bash: python: command not found Is there a way to continue the project using pycharm or do I have to install everything from start? -
How would I be able to extract data from an API and display it in a webpage, using DJANGO?
I received a task that asks me to create a webpage and populate it with data from a given API. The API data is in a REST JSON format. Furthermore, I am using Django as a framework, so that I avoid any issues with cross-origin requests. I've been looking into the request module and have got as far as: import requests import pprint url = '' r = requests.get(url) pprint.pprint(r.json()['results'][1]) I am able to get the information printed in the terminal. However, I am confused about how I would implement this into an HTML page. I am new to working with APIs so any help would be appreciated. thank you -
Reactjs / Django : my login page background keeps showing in other pages
this is my login.css for the login form body { margin: 0; padding: 0; font-family: sans-serif; background: url(bg.png) no-repeat; background-size: cover; } .login { width: 250px; position: absolute; top: 50%; left: 76%; transform: translate(-50%, -50%); } .login h1 { float: left; font-size: 40px; border-bottom: 6px solid #54c7a4; margin-bottom: 50px; padding: 13px 0; } .champ { width: 100%; overflow: hidden; font-size: 80px; padding: 8px 0; margin: 8px 0; border-bottom: 1px solid #54c7a4; } .icon { width: 20px; float: left; text-align: center; } and I don't have a css file for my register.js but the login background keeps showing I have other pages but the background doesn't show into them i don't know what's the promblem ! any help please ? -
Fixing error "Badly formed hexadecimal UUID string" after converting existing id to uuid in Django (Django 3.0)
I created a table with an initial IntegerField primary key and later changed the id to a UUIDField. Now this raises a "Badly formed hexadecimal UUID string", I guess because a number such as "1" isn't a valid UUID value. Does anyone know a concise way to fix this in code when updating the models.py file for the django app? -
django admin filter show number of records in brackets
I have to show the related records in a filter, inside brackets. Example below: How do I create ShowCountInBrackets? class ModelAdmin(admin.ModelAdmin, ShowCountInBrackets): list_filter = ('client') The code below works, but its ugly. And only for a specific field. class ClientCountInFilter(admin.SimpleListFilter): title = _('Client') parameter_name = 'client' def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) for pk, name, count in qs.values_list('client__id','client__name').annotate(total=Count('client')).order_by('-total'): if count: yield (pk, f'{name} ({count})') def queryset(self, request, queryset): id_val = self.value() if id_val: return queryset.filter(client=id_val) class ModelAdmin(admin.ModelAdmin): list_filter = (ClientCountInFilter) -
Email template doesn't render html tag
I'm trying to override content for default password_reset_email.html with some html tag but it doesn't work. Here is my modification. For testing purpose, I'm just using p tag. But i doesn't work. I'm totally unaware what going wrong. Here is my process. urls.py path('accounts/', include('django.contrib.auth.urls')), and here is my html templates {% load i18n %} {% autoescape on %} {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} <p>Hello world</p> {% trans 'Your username, in case you’ve forgotten:' %} {{ user.get_username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The {{ site_name }} team{% endblocktrans %} {% endautoescape %} and here is output enter image description here -
Usage of Openlayers in Django
It's been few days i'm trying to make Openlayers work with my Django web site. I'm totally a noob in Web, so I might miss straightforward stuff that I'm not able to understand, yet. From what I understand, I need to load Openlayers, so for this in my index.html, I've added in the <head> this : <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script> Then in the <body> I've added the index.js where I would like to work with openlayers: <script src="{% static 'index.js'%}"></script> I've copy paste a simple example in the index.js and it's been working correctly. var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([2.333333, 48.866667]), zoom: 10 }) }); So I have a map centered on Paris. Now I would like to load a GeoJson file, thus I need to add a Layer containing the GeoJon. For this I've followed an example here. Here is my first problem I tried to import like this : import GeoJSON from 'ol/format/GeoJSON'; or like this import Style from ol.style.Style bit I got this error : Uncaught SyntaxError: Cannot use import statement outside a module The only solution I found was to new ol.style.Style(...) when … -
when i tried to execute my code in pycharm i got the following error?
[(venv) F:\projects\MULTI_TRAFFIC\MULTI_TRAFFIC\Code\Multi_Traffic_Scene_Perception>python manage.py runserver Performing system checks... Unhandled exception in thread started by .wrapper at 0x0000021B32A08950> Traceback (most recent call last): File "C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\django\db\backends\mysql\base.py", line 274, in get_new_connecti on ]1