Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Apache with mod_wsgi and django
Can't start server using Apache + Django OS: MacOS Catalina Apache: 2.4.43 Python: 3.8 Django: 3.0.7 Used by Apache from Brew. mod_wsgi installed via pip. The application is created through the standard command django-admin startproject project_temp The application starts when the command is called python manage.py runserver At start for mod_wsgi - everything is OK mod_wsgi-express start-server When I start Apache, the server is not accessible. Checked at "localhost: 80". Tell me, what do I need to do to start the server? Httpd settings: ServerRoot "/usr/local/opt/httpd" LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so LoadModule authn_file_module lib/httpd/modules/mod_authn_file.so LoadModule authn_core_module lib/httpd/modules/mod_authn_core.so LoadModule authz_host_module lib/httpd/modules/mod_authz_host.so LoadModule authz_groupfile_module lib/httpd/modules/mod_authz_groupfile.so LoadModule authz_user_module lib/httpd/modules/mod_authz_user.so LoadModule authz_core_module lib/httpd/modules/mod_authz_core.so LoadModule access_compat_module lib/httpd/modules/mod_access_compat.so LoadModule auth_basic_module lib/httpd/modules/mod_auth_basic.so LoadModule reqtimeout_module lib/httpd/modules/mod_reqtimeout.so LoadModule filter_module lib/httpd/modules/mod_filter.so LoadModule mime_module lib/httpd/modules/mod_mime.so LoadModule log_config_module lib/httpd/modules/mod_log_config.so LoadModule env_module lib/httpd/modules/mod_env.so LoadModule headers_module lib/httpd/modules/mod_headers.so LoadModule setenvif_module lib/httpd/modules/mod_setenvif.so LoadModule version_module lib/httpd/modules/mod_version.so LoadModule unixd_module lib/httpd/modules/mod_unixd.so LoadModule status_module lib/httpd/modules/mod_status.so LoadModule autoindex_module lib/httpd/modules/mod_autoindex.so LoadModule alias_module lib/httpd/modules/mod_alias.so LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so LoadModule wsgi_module /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-darwin.so <Directory /> AllowOverride All </Directory> <Files ".ht*"> Require all denied </Files> <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" … -
Jquery ajax not working properly with my django
Here I am trying to add category with ajax but it is not working properly. In the admin it saves the data in format ['name'] and after saving modal doesn't hides also. script <script type="text/javascript"> $(document).on('submit','#=category-form',function(e) { e.preventDefault(); var form = $(this); $.ajax({ url: form.attr("action"), data: { name:$('#name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, type: 'POST', dataType: 'json', success:function(){ $("#myModal").modal("hide"); } }); }); </script> views class AddgoryCateView(View): def post(self, request): name = request.POST.get('name') category = Category.objects.create(name=name) data = {'category': category} return JsonResponse(data) PROBLEM2 : After modal hides creating the data in the database I want to display this data in the html page without refresh. Here the the categories comes from the database. I want to display the newly created category in the option without refresh after saving the data. <label class="text-primary">Categories</label> &nbsp;<small><i class="ic-add" data-toggle="modal" data-target="#myModal"></i></small> <select class="form-control" name="categories" multiple="multiple" id="id-categories"> {% for category in categories %} <option value="{{category.pk}}">{{category.name}}</option> {% endfor %} </select> -
Django manager queries don't work in a sequence of queries
Here's the problem: I've implemented a custom manager for a model with just one custom query named get_by_tag and it's working fine if I use it this way: UsageStatistic.objects.get_by_tag('some-tag-name').filter(user=user_id) But when I change the order of queries, in this way: UsageStatistic.objects.filter(user=user_id).get_by_tag('some-tag-name') it doesn't work! and raise this error: AttributeError: 'QuerySet' object has no attribute 'get_by_tag' Am I missing something?! P.S: FYI the custom manager is somethin like this: class MyCustomManager(models.Manager): def get_by_tag(self, tag_name): posts = Post.objects.filter(tags__pk=tag_name) return super().get_queryset().filter(post__pk__in=posts) -
Why does my preview script does not work?
here is the template i am using i tried to log the date also but it doesn't log {{ form|crispy }} <button type="submit" value="Submit"class="btn btn-primary">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(){ var date = $("#id_Date"); $("#preview-date").val(date.val()) }) </script> </body> </html> -
Django forms are not being processed with POST request
I have written the most basic Django application to understand forms as below. When I enter the required data into the fields and press Submit, the code after "if request.method == 'POST'" is ignored. I am redirected to the appropriate page and an entry with the first name "John" and last name "Smith" is created in my database. As you can see in the code below, this object should only be created if the request method is not POST. I know that I have set the request method to POST because that is what is shown on my CMD so what is happening?? Here is my template 'index.html': <!DOCTYPE html> <html> <head> <title>Welcome to the site</title> </head> <body> <form action="thanks/" method='POST'> {% csrf_token %} {{ form.as_p }} <input type="submit" vlaue="Submit"> </form> </body> </html> Here is my views.py file: from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import NewObjectForm from .models import Object # Create your views here. def index(request): if request.method == 'POST': form=NewObjectForm(request.POST) if form.is_valid(): first_name=form.cleaned_data['first_name'] last_name=form.cleaned_data['last_name'] a=Object.create(first_name=first_name,last_name=last_name) a.save() return HttpResponseRedirect('/thanks/') else: new=Object.create(first_name="Not",last_name="Valid") new.save() else: #Code which is run if the request.method is not equal to 'POST' form=NewObjectForm() newer=Object.objects.create(first_name="John",last_name="Smith") newer.save() return render(request,'formapp/index.html',{'form':form}) def end(request): return render(request,'formapp/thanks.html') -
How to hide html button if queryset doesn't have next blog post in Django?
I would like to hide the Next button in my blog if there is no next blog post available. Is there some kind of built-in method to check has_next has_previous or do I need to create some logic in my view and extend the template with let's say {% if Foo %} show button {% endif %} ? views.py def render_post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] post = get_object_or_404(Post, id=id) next_post_id = int(id) + 1 previous_post_id = int(id) - 1 PostView.objects.get(post=post) context = { 'post': post, 'id': id, 'next_post_id': next_post_id, 'previous_post_id': previous_post_id, 'most_recent': most_recent, 'category_count': category_count, } return render(request, 'post.html', context) html <div id="button-wrapper"> <button class="buttons" type="submit"><a href="/post/{{previous_post_id}}">Previous</a></button> <button class="buttons" type="submit"><a href="/post/{{next_post_id}}">Next</a></button> </div> -
Management command does not show up when installed as third party
I am the author of django-persistent-settings. I have realized something odd. The app has various management commands. When I do python setup.py --help in django-persistent-settings project, the management commands do show up: [persistent_settings] delvar getvar setvar These commands are also tested in the library. However, these commands do not show up when I install it to a project. I wonder why that is. I have read the related section of the docs but could not have found a warning, subsection or something alike regarding my problem. I have also checked the source code of some other projects having custom management commands such as django-simple-history or django-rest-framework. They do more or less the same thing. Is there maybe something I don't know? An issue I haven't seen but encountered somehow? Reanimating the Unexpected Behavior Make sure Django 2 is installed and create a dummy project. django-admin --version # django 2.2.12 or something similar django-admin createproject foo cd foo virtualenv .venv source .venv/bin/activate pip install "django<3" django-persistent-settings Open up foo/settings.py and add it INSTALLED_APPS: INSTALLED_APPS = [ # ... "persistent_settings" ] List commands: python setup.py --help And the commands do not show up. Environment Python 3.8 Django 2.2.12 -
(DJANGO) I want to logout directly without a question "are you sure you want to logout", im using google api for authentication
Sign Out Are you sure you want to sign out? this is the message it is showing when ever I logout using googleapi how to bypass it automatically to homepage? -
how to deactivate compressor in django-redis?
I am using django-redis in django and want to turn off compressor. there are several options to set various types of compressors like zlib, lzma, etc. but not no compressor. -
UserPassesTestMixin test function with many to many relation doesn work
Im making website with shopping lists. One of the features will be possibilities of share your list to someone. The problem is I cant figure out how to make test_func in UserPassesTestMixin work with it. views: class ListDetailUpdateView(LoginRequiredMixin,UserPassesTestMixin, CreateView): model = ShoppingItem template_name = 'xlist_app/ListDetailUpdateView.html' context_object_name = 'products' fields = ['name', 'count'] ... def test_func(self): shop_list_id= self.request.resolver_match.kwargs['pk'] shop_list = ShoppingList.objects.get(id=shop_list_id) if self.request.user == shop_list.owner or self.request.user == shop_list.owners: return True return False models: class ShoppingList(models.Model): list_name = models.CharField(max_length=50, null=False) date_created = models.DateTimeField(auto_now=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='shopping_lists', null = True, blank=True) owners = models.ManyToManyField(User) As you can see, I have field 'owner' that store who created this list and 'owners' that stores users to whom the list is shared. I need help with this part: self.request.user == shop_list.owners How to make it work or why it doesnt work? (When i share list from other account to myself the "403 Forbidden" pops out) -
how to use one forloops in different div layouts in django
example of section I wanted to list out blog posts in a section having different div layouts. How to do this with using only one for loop. Or is there any way suggest me how to do? -
Can't Update ImagesField() by Form in Django
I can't update Images field , with eidt data . All can run except it I tried to update the image of the product but the web only changed the text data columns, with the file having no changes. views.py def update_book(request, book_id): book_id = int(book_id) try: book_sel = Book.objects.get(id = book_id) except Book.DoesNotExist: return redirect('index') book_form = BookCreate(request.POST or None, instance = book_sel) if book_form.is_valid(): book_form.save() return redirect('index') return render(request, 'upload_form.html', {'upload_form':book_form}) this my html {% extends 'library.html' %} {% block content %} <h1 class="display-3" style="background-color:#000000;color:#FFFF99;">Update Books</h1> <form method='POST' enctype="multipart/form-data"> {% csrf_token %} <table class='w-50 table table-light' style="border-radius:10px;background-color:#FFFF99;"> {% for field in upload_form %} <tr> <th>{{field.label}}</th> <td>{{ field }}</td> </tr> {% endfor %} </table> <button type="submit" class="btn btn-lg btn-warning">Submit</button> </form> {% endblock %} -
how to make card-text and horizontal list group items editable in a bootstrap card?
Using bootstrap card-text and horizontal list group I was able to show information in a bootstrap card, but I want them to be editable like bootstrap 4 form. So, how I will be able to do that? I have provided the code that is showing information in a bootstrap 4 card. <div class="personal"> <div class="card"> <div class="card-body"> <h5 class="card-title">Personal</h5> <p class="card-text">Your Personal Inforation</p> <ul class="list-group list-group-horizontal"> <li class="list-group-item">Mobile Phone</li> <li class="list-group-item">{{employee.phone_number}}</li> </ul> <ul class="list-group list-group-horizontal"> <li class="list-group-item">Birth Date</li> <li class="list-group-item">{{employee.birth_date}}</li> </ul> <ul class="list-group list-group-horizontal"> <li class="list-group-item">Age</li> <li class="list-group-item">age</li> </ul> <ul class="list-group list-group-horizontal"> <li class="list-group-item">Address</li> <li class="list-group-item">{{employee.address}}</li> </ul> <ul class="list-group list-group-horizontal"> <li class="list-group-item">Gender</li> <li class="list-group-item">{{employee.gender}}</li> </ul> </div> </div> </div> -
Set the groups in Django template
I want to register users by using template, i want also, in the moment of registration, set the group(default groups permission provided by Django) of every new user created, I set the group of user in the template but when i look to the group of user in the database i I found it empty. class ProfileUserManager(BaseUserManager): def create_user(self, username, password,**extra_fields): user = self.model(username=username, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, username, password,**extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', 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(username,password,**extra_fields) class ProfileUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) username = models.CharField(max_length=255,unique=True) first_name=models.CharField(max_length=255) last_name= models.CharField(max_length=255) departement= models.CharField(max_length=255) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = ProfileUserManager() def __str__(self): return self.username forms.py class FormAddAccount(UserCreationForm): class Meta(UserCreationForm.Meta): model = get_user_model() fields = ('email', 'password1', 'password2', 'is_staff','username','groups','first_name','last_name','departement') -
Django Admin: Inline of a filed's field
I have the following model definition: class Person(models.Model): ... class Children(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) I want to preview a person's children inline in the Membership admin view -
What are the tricks about importing modules?
I am working on a django project. In views.py I invoked a function from custom.py . The problem is it is working nicely. But I didn't write something like: from .custom import * or import custom In a sentence, there is not the the word 'custom' anywhere in views.py. Why it's working? Is there any other way to import module that i don't know about? What is it? Or any kind of django trick? addition: The custom.py also did not import views.py custom.py has imported models.py If possible, kindly answer only what I asked for. I will be thankful. Avoid keeping unnecessary advice like 'your file name should be myfunction.py instead of custom.py -
How to store & retrieve data in Django sessions?
I have the following lines in settings: INSTALLED_APPS = [ ... ... 'django.contrib.sessions', ] MIDDLEWARE = [ ... ... 'django.contrib.sessions.middleware.SessionMiddleware', ] I tried the following code in my .py files: To set the data: request.session['data'] = setData To get the data: getData = request.session['data'] But I get the following error: "name request is not defined" How to fix this error? Thanks. -
Django, unable to seek/forward the audio files
I am using Django Rest API + React JS. The audio files stored in Django is played by HTML audio tag in frontend. I am able to play and adjust volume from the default audio player but unable to seek or forward and rewind. How can I solve this ? Any idea or directions will be highly appreciated. I tried another audio player in React , react-h5-audio player but faced similer experience. I hope I need better server configuration for file field handling. I uploaded the audio files as audio=models.Filefield(upload_to='audio') in Django -
Django makemessages i18n MemoryError
I am trying to run the makemessages command on server with Django, but every time get a MemoryError message after some five minutes. Can you have an idea what is going wrong? Here is my traceback: Traceback (most recent call last): File "/home/wingard/webapps/django_movies/movies/manage.py", line 21, in <module> main() File "/home/wingard/webapps/django_movies/movies/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/commands/makemessages.py", line 384, in handle potfiles = self.build_potfiles() File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/commands/makemessages.py", line 426, in build_potfiles self.process_files(file_list) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/commands/makemessages.py", line 519, in process_files self.process_locale_dir(locale_dir, files) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/commands/makemessages.py", line 538, in process_locale_dir build_file.preprocess() File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/core/management/commands/makemessages.py", line 113, in preprocess content = templatize(src_data, origin=self.path[2:]) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/utils/translation/__init__.py", line 249, in templatize return templatize(src, **kwargs) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/utils/translation/template.py", line 226, in templatize out.write(blankout(t.contents, 'X')) File "/home/wingard/webapps/django_movies/lib/python3.8/Django-2.2.12- py3.8.egg/django/utils/translation/template.py", line 17, in blankout return dot_re.sub(char, src) MemoryError And my command: export PYTHONPATH=/home/wingard/webapps/django_movies:/home/wingard/webapps/django_movies/movies:/home/wingard/lib/python3.8:/home/wingard/webapps/django_movies/lib/python3.8; /usr/local/bin/python3.8 /home/wingard/webapps/django_movies/movies/manage.py makemessages -l en -
Celery doesn't work when i import a module. Before importing it works fine
My celery task is to update the mongodb database. I've created a handler for it which i'm importing to celery.py. Celery seems to work fine but when i try to import the handler module it throws an error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet celery.py: from __future__ import absolute_import, unicode_literals from django.conf import settings import os from celery import Celery # from handlers.ordercount import OrderCount # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'di_idealsteel.settings') app = Celery('di_idealsteel') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) @app.task(bind=True) def add(self,number,customer_id): ordercount = OrderCount() opencount = ordercount.open_enquiries(number,customer_id) When i try to import 5th line it throws this error Traceback (most recent call last): File "c:\users\ashish\envs\idealvenv\lib\site-packages\celery\app\trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "c:\users\ashish\envs\idealvenv\lib\site-packages\celery\app\trace.py", line 437, in __protected_call__ return self.run(*args, **kwargs) File "C:\Users\Ashish\Desktop\Internship\di_idealsteel\di_idealsteel\celery.py", line 32, in add from handlers.ordercount import OrderCount File "C:\Users\Ashish\Desktop\Internship\di_idealsteel\handlers\ordercount.py", line 4, in <module> from handlers.user_handler import UserHandler File "C:\Users\Ashish\Desktop\Internship\di_idealsteel\handlers\user_handler.py", line 12, in <module> from app.models import (AuthUser,Customers,CustomerUsers,UserHistory,CustomerUsersHistory) File "C:\Users\Ashish\Desktop\Internship\di_idealsteel\app\models.py", line 10, in <module> from … -
Django - Search field
I am working on creating a real estate web app. I want to know which is the best implementation to set up my location search field. I have the Places API up and running (autocompleting with location suggestions), but I am a bit lost now, on how I can retrieve the the information and return filter properties based on the user's preferred location. Should I go with custom SQL query? (I am using posgres) 2)Is there any established way to do that with google places/map API or any other? I tried to make it with Django's built in icontains method but my search field returns something like: {London, UK, } which means many words separated with comma and icontains does not work that way. Happy for any suggestion. -
How to clone millions of copy of a database model in django
I have a custom User model in django. Some other models are related to that user model like UserDetails, Prlofile etc. Now I need on around 100k users in my database for a testing purpose. I just wanna create users by changing tehir email address which is in User model. What is the best way to create suchc a large number of objects and save it to database also with corresponding related models. -
Django Rest API - django-rest-auth
I have installed django-rest-auth package in pipenv. But getting this error -
Accessing Many-To-Many Data From Another Many-To-Many Relationship
Users can buy individual modules or packages of many modules. On a users profile page they can see a table of all Modules they have bought, and another table of the packages they have bought. The table that displays the packages they have bought also displays all the modules within the package. class User(models.Model): individual_modules = models.ManyToManyField(Module, blank=True) package = models.ManyToManyField(Package, blank=True) # individual modules class Module(models.Model): task_type = models.CharField(max_length=200) topic = models.CharField(max_length=200) # packages of many modules class ModulePackage(models.Model): name = models.CharField(max_length=200) individual_modules = models.ManyToManyField(BaseModule, blank=True) I am able to access a Users Modules {% for module in user.student.individual_modules.all %}, and can access a Users Packages {% for module in user.student.module_packages.all %}, but I cannot figure out how to print all of the Modules which are contained in a Package which the User has bought. Im guessing Id have to get this data within view.py and pass it to the template, but am unable to figure out how. Example: USERS MODULES Module 5 - Crime Module 8 - TV Shows USERS PACKAGES - PACKAGE 1 Module 1 - Movies Module 2 - Cartoons Module 3 - Drama PS - My relationships seem very sloppy and if you can think … -
Facing problem with linking to another page,help needed
i been trying to create a Login and a Register page in a django project.i have almost created both the pages except for...i can't link to Login page from Register page and vice versa.I have created a button in the Register page called 'Login' down below the registration form to link it back to Login page if the user already has an account.i have written below code for the button i made: <button> <a href="register/">Login</a> </buttton> and my Register and Login page urls are: localhost:8000/register/ localhost:8000/login/ But if i press the button, it takes the user to localhost:8000/register/login/ What i want is to take the user to: localhost:8000/login/ How can i do that?And whats the problem going on?