Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL not matching url pattern in Django
I'm trying to learn Django, went through the official tutorial and giving it a try on my own. I've created a new app and can access the index page but I can't use pattern matching to go to any other page. Here is my monthlyreport/url.py from django.urls import path from . import views #app_name = 'monthlyreport' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ] and my monthlyreport/views from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic from .models import Report def index(request): report_list = Report.objects.all()[:5] template = loader.get_template('monthlyreport/index.html') context = { 'report_list': report_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) The debug for http://127.0.0.1:8000/monthlyreport/0 is showing Using the URLconf defined in maxhelp.urls, Django tried these URL patterns, in this order: monthlyreport [name='index'] monthlyreport <int:question_id>/ [name='detail'] polls/ admin/ accounts/ The current path, monthlyreport/0, didn’t match any of these. Again, using http://127.0.0.1:8000/monthlyreport/ to go to index works fine, but I cant match the integer. I would really appreciate any suggestions, I am very, very confused at this point. -
Django whitespace from textarea into a list of dictionary
I hope someone here can help me out of this. I have a request.POST from textarea, for example: <QueryDict: {'Animal':['Fish Dog Cat Bird']}> I want to convert to something like this: {'Animal': ['Fish', 'Dog', 'Cat', 'Bird']} Thanks in advanced -
How can I change my python path permanently?
I recently just installed Inkscape to my Windows 10 computer, and it changed my python path. C:\Users\Chinyere\Documents\Django Files\Commercial>python Python 3.8.9 (default, Apr 13 2021, 15:54:59) [GCC 10.2.0 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print(sys.path) ['', 'C:\\Program Files\\Inkscape\\lib\\python38.zip', 'C:\\Program Files\\Inkscape\\lib\\python3.8', 'C:\\Program Files\\Inkscape\\lib\\python3.8\\lib-dynload', 'C:\\Program Files\\Inkscape\\lib\\python3.8\\site-packages'] I can't run my Django files. When I try, it pops-up error C:\Users\Chinyere\Documents\Django Files\Commercial>python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( 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? Please, how can I change it to the default python path without uninstalling Inkscape. -
Submitting a new records via form to my django database
I am trying to create new objects in my database and if all goes well send the user to a table where all records are being posted, but for some reason the form is seems to be submitting successfully but no new records are being added to my database. Here are my codes: models.py: from django.db import models class clearance(models.Model): vessel_imo = models.ForeignKey(vessel, on_delete=models.PROTECT) vessel_name = models.CharField(max_length=30,blank=True,) email = models.EmailField(default='john@doe.com') location = models.CharField(default='PACCT',max_length=30,choices=LIST_OF_PORTS) clearance_file1 = models.FileField() status = models.CharField(max_length=20,choices=CLEARANCE_STATUS,default='PENDING') requestdate = models.DateTimeField(default=timezone.now,auto_created=True,editable=False) def __str__(self): return self.vessel_name class Meta: ordering = ['-id'] form.py: from django.forms import ModelForm from . models import clearance, vessel class ClearanceForm(ModelForm): class Meta: model = clearance fields = '__all__' views.py: def new(request): form = ClearanceForm(request.POST) if form.is_valid(): form.save() return render(request,'new.html',{'form':form}) new.html: {% extends 'dashboard.html' %} {% block title %} <h2> REQUEST FOR CLEARANCE</h2> {% endblock title %} {% block content %} <form action="pendings.html" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock content %} What I am trying to get is the user to add a new records in the database and be sent to the dashboard.html where he can see all records including the just added. -
how to break lines for a value from database
i want to break line between command and result : outputs.append(output) outputs.append(request.POST.get("cmds")) device.config = outputs device.save() i added the value 'outputs' in device.config and this is my template i use {{device.config|linebreaksbr}} but this is the result -
How do i integrate my create new post url ,with detail view and list view so that users can create new post on the same page like that of facebook
What am trying to accomplish is for users to be able to create post and add pictures as on Facebook, but somehow in Django am having a challenge with that, create post has to be on a separate URL as detail and list view has separate URLs how do I integrate all of the URL to be on one template, so that very post works on one page like that of Facebook. here is my views... class PostListView(ListView): model = Post template_name = 'feed/feed.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked return context class UserPostListView(LoginRequiredMixin, ListView): model = Post template_name = 'feed/feed.html' context_object_name = 'posts' paginate_by = 10 def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username.get_full_name')) liked = [i for i in Post.objects.filter(user_name=user) if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked return context def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username.get_full_name')) return Post.objects.filter(user_name=user).order_by('-date_posted') @login_required def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) user = request.user comments = post.comments.filter() is_liked = Like.objects.filter(user=user, post=post) new_comment = None if request.method == 'POST': comment_form = NewCommentForm(request.POST) if form.is_valid(): … -
Proper way of inputting questions in a quiz web application
I am trying to build a quiz web application in Django and React. Each time user takes a quiz, questions are randomly picked from a list of thousand questions. Without doing it manually, what could be the proper way of inputting the questions? -
Django How To initialize an Instance of Class Only Once using for all requests?
I'm just a beginner. I have a custom Package Module, so for now every time users request to the Server It takes like 30 seconds to initialize(load data for the Class) and then do the actual work. Is there any so I can only initialize only one Instance of this Module and using for all requests from users? I tried to follow a few ways but no hope Thanks in advance, By the way, I deployed it on Ec2 with Nginx Gunicorn. Django - execute code at start-up. Django: Run a script right after runserver -
Get a single value from user database django
im new on django, and i want to get a single value from a queryset, te query would be something like this: select last_task from User where user_id=1 I tried with values() and only() but it doesnt work. worker = request.user Worker.objects.filter(user=worker.id).values("last_board") values() return me a dictionary and i cant extract the single value from it to use. -
Django template language "If" statement with many "and"
Basically i want to add a class to a div based on whether some variables have content or not. This is the If statement: <div class="search__container {% if images == true and blogs != True and parks != True %} only-images {% elif blogs == true and images != True and parks != True %} only-blog {% elif parks == true and blogs != True and images != True %} only-parks {% elif parks == true and blogs == true and images != True %} only-parks-blogs {% elif parks == true and images == true and blogs != True %} only-parks-images {% elif images == true and blogs == true and parks != True %} only-images-blogs {% endif %}" > This way it's not adding any class under any circumstances. If instead i remove the == and replace the != with is not it'll always take the first if as True and add the class only-images -
Dúvida sobre Django Queryset
Gostaria de saber se alguém consegue me ajudar na seguinte questão: last = Jogos.objects.all().filter(concurso = 2248) Nesse código acima a variável fica com o valor <QuerySet [<Jogos: 2248>]> porém eu gostaria de imprimir não isso e sim os valores do concurso 2248, o que estou fazendo errado ? -
How to add missing Months in Django Python List of Dictionary
<QuerySet [{'month': datetime.datetime(2021, 4, 1, 0, 0, tzinfo=), 'total': 1}, {'month': datetime.datetime(2021, 6, 1, 0, 0, tzinfo=), 'total': 1}]> How to add Missing Month of May (5) in which 'total' is equal to Zero in above? -
How to pass 'pk' to class-based view
This is my urls.py: urlpatterns = [ path('<int:pk>/', views.PortfolioDetailView.as_view(), name='index'), ] And my views.py: class PortfolioDetailView(DetailView): queryset = Project.objects.get(pk=pk) template_name = 'portfolio/index.html' context_object_name = 'projects' I'm obviously missing something (and I'm sure it's a silly one) because I get error: queryset = Project.objects.get(pk=pk) NameError: name 'pk' is not defined What is it? -
ImportError at / cannot import name 'register_new_org_view' from 'users.views' (/home/ubuntu/xyz/users/views.py)
I am having trouble with my gunicorn, nginx deployed django application. Everything runs smoothly on my local development and python manage.py check does not throw any errors. However, as soon as I deploy my application to my server this error is thrown:ImportError at / cannot import name 'register_new_org_view' from 'users.views' (/home/ubuntu/xyz/users/views.py) I have defined the view and import it correctly... other views from other apps are working perfectly fine... what can be the reason? Thank you so much for your help! -
Django - ModuleNotFound
Currently trying to implement a script within a Django application, however I am getting a module not found error when trying to execute the Django app. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Steven\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line … -
DateField format in DjangoTemplate
I am using paginator to divide reviews on pages, my model has DateField created = models.DateField(auto_now_add=True) I am using ajax to do it without refreshing page. When i put it in my template like this {{review.created}} It displays in format like 06 June 2021 But with ajax, where i pass 'date':obj.created It displays in format 2021-06-06 How can i made it to display similiar in one of these formats? I prefer first format, but second will be acceptable too -
Issue installing and configuring GeoDjango
I am following the following tutorial with creating a Geo Location based web app. Although, I've ran in to a few challenges which I've been trying to figure out how to resolve. Reference to GeoDjango tutorial: https://realpython.com/location-based-app-with-geodjango-tutorial/ Per the instructions (on the link provided above) - I have included django.contrib.gis as apart of my Installed Apps. Although, Gunicorn is failing to start when this include is in place. So I'm guessing it will most likely be because I need to install other relevant libraries in order to get GeoDjango working. I did a little digging online and came across this link - https://docs.djangoproject.com/en/3.2/ref/contrib/gis/install/geolibs/ Which seems to references the libraries which need to be installed. I have managed to install GEOS and PROJ perfectly fine. Although, the final requirement is to install GDAL. So I found the relevant install command for GDAL pip3 install gdal but I am receiving the following error when installing this library within the SSH console. Running setup.py install for gdal ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3.6 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xjvcvnos/gdal_5ab038f0da3b44488d8b78e9cb9b461a/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xjvcvnos/gdal_5ab038f0da3b44488d8b78e9cb9b461a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code … -
testdriven.io django docker tutorial error on test CI section
Cannot get the CI section complete because pytest fails. looking at the logs of the test build it errors with a sqlite3 error when it's supposed to be connecting to the postgres container that's launched for the tests. need some help figuring out where the error might be. I made my gitlab project public and will include a link directly to the error. https://gitlab.com/hectormalvarez1/mgdusa/-/jobs/1322478542 -
Request.user has no attribute user when used in settings.py
request.user generates a AttributeError: 'WSGIRequest' object has no attribute 'user' error when I try to use it in my settings.py file. Am I doing something wrong? Settings.py: def show_toolbar(request): if DEBUG: return True #if not request.is_ajax() and request.user and request.user.UserSettings.debugger: # return True return False DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': 'acacia2.settings.show_toolbar', } -
How to solve decimal.InvalidOperation on the server?
Info: I have a project where frontend is on ReactJS, and backend is on Django. The problem: When customer placing an order, the server returns 500 InvalidOperation at /api/orders/ [<class 'decimal.InvalidOperation'>] Additional info: It works perfect on test server, but fails on live. The docker containers and back/front code are the same. Taken efforts: rows like round(Decimal((obj.total_price * 100)) / discount_revers - Decimal(obj.total_price), 2) i transform into round(((Decimal(obj.total_price) * Decimal(100))) / discount_revers - Decimal(obj.total_price), 2) and the error still the same. The Question: How to solve this? -
Django testing custom signal arguments with assertIsInstance: AssertionError: <class 'path.to.Foo'> is not an instance of <class 'path.to.Foo'>
I am using Django 3.2 I have written an app that raises custom events, and I am writing tests for the apps. Here is the relevant section of my code: class TestAppModel(TestCase): # .. set up instance variables etc. def test_liked_signal_emits_correct_data(self): self.signal_was_called = False self.sender = None self.instance = None self.event_type = None self.actor = None def handler(sender, instance, event_type, actor, **kwargs): self.signal_was_called = True self.sender = sender self.instance = instance self.event_type = event_type self.actor = actor item_liked.connect(handler) self.daddy.like(self.admin_user) # Check that the sender is a Foo self.assertIsInstance(self.sender, Foo) # <- Nonsensical error emitted here When I run the test, I get the error message: AssertionError: <class 'social.models.Foo'> is not an instance of <class 'social.models.Foo'> Which obviously, is a nonsensical error message that doesn't help me solve the problem. My question is why am I not able to check the instance type using assertIsInstance, and how do I check the class type in the signal receiver? -
How do i resolved user's post name which display email instead of their full name in a social media app am creating?
Am currently working on a social media up in Django but am facing a challenge with the post model app since it displays their email address, when they post a pic or a write feed post instead of their full name! My user model authenticate with email address rather than users name. I don't know if this is the actually course of the problem! How do i get users full name on their post instead? I still want to be able to authenticate users with email but their post should be displayed in their full name. Here my user's model class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email,username,last_name, password, **extra_fields): values = [email,username] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, first_name,last_name, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email,username, first_name,last_name, phone_number, password, **extra_fields) def create_superuser(self, email, username,phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email,username,phone_number, password, **extra_fields) class User(AbstractBaseUser, … -
DNS record look up with Python / Django [dnspython]
I am trying to get DNS records of particular domain. So, I found dnspython package where it could be easily done. It works fines when I run it from my computer. However, when I call it from Django views it shows the previous records (old records) which means it's not updating. Is it some kind of caching in OS level? Note that, I am also using Docker. Restarting docker and clearing cache in Django didn't help, still shows old records. Here's the sample code for checking records: import dns.resolver result = dns.resolver.resolve("domain.com", "TXT")[0].to_text() The code snippet above works and shows any update in TXT record, when I run it from my computer. However, in Django it stucks in old records and not updating. Thanks for any help. -
Im not able to install mysqlclient on macOS
Im trying to connect Django with mySql, but I'm running into an error. I already have mySql installed, and I've already try reinstalling openssl, but I'm still getting the same error. Im on macOs 11.4 and I'm using python 3.9.2 alongside Django 3.2.3. Im getting the following error message when typing on terminal pip3 install mysqlclient: Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-record-6ggb6_as/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/mysqlclient cwd: /private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/ Complete output (44 lines): mysql_config --version ['8.0.25'] mysql_config --libs ['-L/opt/homebrew/Cellar/mysql/8.0.25_1/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/opt/homebrew/Cellar/mysql/8.0.25_1/include/mysql'] ext_options: library_dirs: ['/opt/homebrew/Cellar/mysql/8.0.25_1/lib'] libraries: ['mysqlclient', 'zstd', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/opt/homebrew/Cellar/mysql/8.0.25_1/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] running install running build running build_py creating build creating build/lib.macosx-10.9-universal2-3.9 creating build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb creating … -
How to assign multiple classes to the django form widget's parameter - "attrs"?
This is my simple forms.py: class SearchForm(forms.Form): search = forms.CharField( label="", max_length=100, widget=forms.TextInput( attrs={ "class": "form-control me-2", "type": "search", "aria-label": "Search", } ) ) form.html: <form class="d-flex" method="GET" action="."> {% csrf_token %} {{ form.as_p}} <!-- <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> --> <button class="btn btn-outline-success" type="submit">Search</button> </form> I need my input tag have two bootstrap classes "form-control" and "me-2", but separating them with whitespace in widget's attrs dictionary seems doesn't work. Any suggestions?