Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count consecutive rows with same value for a column in a database using django?
My App consists of a notification module. If the notifications are consecutively arrived from a same user, I would like to show "n notifications from john doe". eg: The database rows are as: id | user | notif | ------------------------------------ 1 john doe liked your pic 2 john doe commented on your pic 3 james liked your pic 4 james commented on your pic 5 john doe pinged you 6 john doe showed interest 7 john doe is busy The above notifications are to be shown as: 2 notifications from john doe 2 notification from james 3 notofications from john doe How would I count these consecutive rows with same value in a column using django orm? Notification.objects.all().values('user', 'notif_count').group_consecutive_by('user').as(notif_count=Sum()) Something like that. Please help. -
How to run behave in django project
i have a feature app in my django project. and some feature files in it like feature/some.feature feature/environment.py feature/steps/some.py And my environment file contains environment.py class FeatureContext(object): """ Used to pass along data between test steps """ def __init__(self): self.scenario_context = {} # Data Specific to a scenario self.http_response = None def before_feature(context, feature): context.response = FeatureContext() def after_feature(context, feature): context.response = None when i run behave i am getting some errors django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured.<br> You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Django @login_required redirects to home page
I have an issue with the below code. When I login below and try to submit the create.html template it redirects me to Home page (via home function in views and record is not saved in database). When i remove @login_required and directly navigate to /products/create , the record is saved down in database. I am confused why this is happening. Any assistance will be appreciated I removed (@login_required) and directly navigated to /products/create and it works perfectly. However whenever I login and then use /products/create the record is not saved in database Create.html {%extends 'base.html'%} {%block content%} {%if error%} {{error}} {%endif%} <h2> Create </h2> {% csrf_token %} <form action="create" method="POST" enctype="multipart/form-data"> {% csrf_token %} Title: <br/> <input type="text" name = "title"/> <br/><br/> Body: <br/> <input type="textbox" name = "body"/> <br/><br/> URL: <br/> <input type="text" name = "url"/> <br/><br/> <input type="submit" class = "btn btn-primary" value = "Add Product"/> </form> {%endblock%} Main url.py from django.contrib import admin from django.urls import path,include from products import views urlpatterns = [ path('admin/', admin.site.urls),path('accounts/',include('accounts.urls')),path('products/',include('products.urls')), path('',views.home,name='home'),] Sub project url.py from django.urls import path,include from . import views urlpatterns = [ path('create',views.create,name='create'),] views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.models import … -
Django above version 2.1.5: how to set urls.py to allow get method to work?
I want to reuse the same template "createchapter.html". In other words, I wan to link to "createchapter/?step=1.html", "createchapter/?step=2.html","createchapter/?step=3.html". I am using Django 2.1.5, so there are few resources or Q&A to learn. In urls.py urlpatterns = [ (.....) url(r'^createbook/$',viewsSentence.createbook), url(r'^createchapter/<int:step>$',viewsSentence.createchapter), ] In views.py @csrf_exempt @csrf_protect def createchapter(request,path): if request is not None: if request.GET.get('step') is None: context1 = { 'books': book.objects.order_by('titleOrigin'), 'step': 1, } #useless: return HttpResponse('/?step=1',context1) redirect("createchapter.html",context1,step=1) elif request.GET.get('step') == 2: context2 = { 'step': 2, } redirect("createchapter.html", context2,step=2) In createchapter.html {% if step == 1 %} <form> {% csrf_token %} <div class="form-group"> <i class="fas fa-forward"></i> <label for="select-books">Step 1: select a book</label> <select class="form-control" id="select-books"> {% for book in books %} <option value="{{ book.id }}">{{ book.titleOrigin }}</option> {% endfor %} </select> </div> </form> <div class="d-flex justify-content-center"> <i class="fas fa-arrow-alt-circle-right"><a id="createchapter-step2">Step 2</a></i> </div> {% elif step == 2%} <div class="form-group"> <i class="fas fa-forward"></i> <label>Step 2: set numbers of chapters</label> </div> {% endif %} The error message is : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/createchapter/?step=1/ -
Does Wagtail Cms support Google login and user login add session to
Is there is any way to add user login/google login and session in wagtail cms? tried adding projects during. how to implement security for wagtail. -
Django Debug Error Page Hide Meta, Override Error Page
I want to override default Error Page to hide META Block in any way. Meta Block contains all sensitive Info. which i don't want to be in Views for any user. -
CheckboxSelectMultiple doesn't pre-check boxes with inital value set to queryset
I am working on a kid's email program that will populate checkboxes with the appropriate mail recipients after 'reply all' is clicked. When I create the template for the reply email, I need to generate the choices dynamically as well as as the pre-checked boxes. Everything works except that the boxes don't get checked. I've read a lot of related questions here but none populating directly from a queryset. I don't understand how/where to set "initial". To be sure that my filter is not causing the problem, I have set both the queryset and the initial to the same value, expecting all of the boxes to be checked, and none are. Thanks for any help. forms.py: class EmailForm(forms.Form): recipients = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple) email_views.py: def email_compose_show(request, reply_type, email_id): if reply_type == 'reply-all': msg = Mail.objects.get(id=email_id) qs=CustomUser.objects.filter(id__in=get_users(request.user.id)).exclude(id=request.user.id)'''' form = EmailForm(initial={'message': msg.message, 'subject': msg.subject}) recipients = forms.ModelMultipleChoiceField( label="Recipients", widget=forms.widgets.CheckboxSelectMultiple, queryset=qs, initial=qs ) form.fields['recipients'] = recipients template: {% for x,y in form.fields.recipients.choices %} <label for="id_recipients_{{forloop.counter0}}"> <input type="checkbox" name="recipients" id="id_recipients_{{forloop.counter0}}" value="{{ x }}"> {{ y }} </label> {% endfor %} -
i want solveError in Django
I still haven't solved this fall. I don't know what this error means. Please fix this error. Problem:enter image description here path('/polls', views.polls, name='polls'), \src\fistsite\urls.py", line 7, in module AttributeError: module 'polls.views' has no attribute 'polls' Source Code urls.py-fistsite from django.contrib import admin from django.urls import path, include from polls import views urlpatterns = [ path('', views.index, name='index'), path('/polls', views.polls, name='polls'), path('/admin', views.admin, name='admin') ] urls.py-polls from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/result/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] views.py-polls from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from polls.models import Question, Choice # Create your views here. def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] context = {'latest_question_list':latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice.set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html',{ 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/result.html', {'question': question}) -
Display ForeignKey filed as a table in django Admin
I'm working on a project using Python(3.7) and Django(2.1) in which I have a model call Category which has a filed as parent of type ForeignKey to itself as self. It's displaying in the Django admin as a drop down, as there will be hundreds of PARENT categories, so we can't use a dropdown in such a situation, what I want to display a big table with a search option to select a category as parent. Here's my Category model: From models.py: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() description = models.TextField(max_length=1000, default='') parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) And From admin.py: @admin.register(Category) class CatAdmin(admin.ModelAdmin): filter = ('parent',) class Media: css = { 'all': ('assets/css/custom.css',), } so, how can I achieve my required scenario in Django admin? Thanks in advance! -
How can I import variables out of views.py in Django?
I am a complete beginner to Django and relatively new to Python, although I'm comfortable with the basic syntax of the language. I've made a post form in Django that takes my input and assigns it to a variable in my views.py file after filtering it, like so: def index(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] form = NameForm() return render(request, './index.html', {'form': form}) 'name' is my variable being stored from my NameForm() form, which was made and imported from a separate form file. My issue begins when I need the 'name' variable to be imported into another .py file. The first and obvious method would be to import views into my other file, but this doesn't work. For some reason I don't know, being a Django newbie, importing a views.py file works perfectly unless you have to run that individual .py file, then it gives the error: "ImportError: cannot import name 'views'" The obvious response to this would be asking if I'm referencing the wrong directory, which I know I'm not, since the urls.py file works. I also know nothing is inherently wrong with my views file since it routes my urls properly. … -
Correct way to make combinations using Django ORM
I have two models: class Route(models.Model): rlist = ForeignKey(RList) from = ForeignKey(Place) to = ForeignKey(Place) class ProxyRoute(models.Model): rlist = ForeignKey(RList) to = ForeignKey(Place) What is the correct way to create list of Route models including all avaliable combinations from route.from to proxy.to. For example if I have Route from Home to School and ProxyRoute to Cinema and FriendsHome I need to create new Route instances from Home to Cinema and from Home to FriendsHome. How can I make with least number of ORM querys. Is it possible with bulk_create? Thanks! -
Resolving circular dependencies in a python/django application
I have a model that calls a file parser (to parse a file) and that file parser calls the model to save the object. Currently, the code looks something like this: # models.py class Source(models.Model): ... def parse_file(self): from ingest.parser import FileParser ... # ingest.py class FileParser() def save(self): from models import Source ... This 'works' fine, however, doing the import within the save method adds about 0.2s the first time I have to use it, as it's initializing the import. Is there a better way to do the above? -
django mail queue emails not sending with celery
I'm using Django Mail Queue with Django 2.x The application is hosted on Heroku and using redis backend for Celery The settings.py file contains ####################### # Email settings ####################### EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = int(os.getenv('EMAIL_PORT', 587)) EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = eval(os.getenv('EMAIL_USE_TLS', "False")) EMAIL_USE_SSL = eval(os.getenv('EMAIL_USE_SSL', "False")) DEFAULT_FROM_EMAIL = os.getenv('EMAIL_DEFAULT_FROM_EMAIL') SERVER_EMAIL = os.getenv('EMAIL_SERVER_EMAIL') DEFAULT_TO_EMAIL = os.getenv('EMAIL_DEFAULT_TO_EMAIL') ################## # CELERY STUFF ################## BROKER_URL = os.getenv('REDIS_URL', 'redis://localhost:6379') CELERY_RESULT_BACKEND = os.getenv('REDIS_URL', 'redis://localhost:6379') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' ####################### # Django mail queue ####################### MAILQUEUE_CELERY = True MAILQUEUE_QUEUE_UP = False and sending email like new_message = MailerMessage() new_message.subject = subject new_message.to_address = to new_message.from_address = from_email new_message.content = text_content new_message.html_content = html_content new_message.app = 'Koober' new_message.save() On sending the email, it is saved in the database and is shown on the Admin page but is not sent. Setting MAILQUEUE_CELERY = False and MAILQUEUE_QUEUE_UP = False is sending email successfully. But this is resulting in application failure in case of an exception. That's why I want to use Celery to send email in the background. -
1 I want to add database values by HTML Forms
I want to add database values by HTML Forms html form views.py forms.py models.py I am unable to save the data -
How to Show RNN predicted output to Django Web Page?
I am implementing a Django Web App to show the predicted results of a Recurrent Neural Network written in keras using Python(.h5). I doesn't know how model is working.But doesn't found any helpful material which can guid me. please help me get out of this problem. -
Python Apache WSGI error: No such file or directory: mod_wsgi (pid=27967): <>. Python interpreter may not be able to be initialized correctly
Hi I am trying to run python application with Apache setup using WSGI module. I am trying to resolve the error in "error.log" file. here is the output of the "error.log" file [Thu Jan 10 01:54:16.221336 2019] [mpm_event:notice] [pid 27964:tid 140499783105472] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Thu Jan 10 01:54:16.221429 2019] [core:notice] [pid 27964:tid 140499783105472] AH00094: Command line: '/usr/sbin/apache2' [Thu Jan 10 01:54:16.229132 2019] [wsgi:warn] [pid 27967:tid 140499783105472] (2)No such file or directory: mod_wsgi (pid=27967): Unable to stat Python home /var/www/Project_TickerScan/Tscan_ec2_production/Tscan_ec2_production/tscan_ec2_venv/. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fc8a7a9bbc0 (most recent call first): [Thu Jan 10 01:54:17.222581 2019] [core:notice] [pid 27964:tid 140499783105472] AH00051: child pid 27967 exit signal Aborted (6), possible coredump in /etc/apache2 [Thu Jan 10 01:54:17.223598 2019] [wsgi:warn] [pid 28028:tid 140499783105472] (2)No such file or directory: mod_wsgi (pid=28028): Unable to stat Python home /var/www/Project_TickerScan/Tscan_ec2_production/Tscan_ec2_production/tscan_ec2_venv/. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable … -
Django - Form Not Updating
I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in admin from the current logged in user. The data populates in the admin however new listings keep repeating every time the user submits a form. I need the the data to update only. Screenshot attached. How do I execute this correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Forgive me because I'm new to Django. Any help i gladly appreciated, Cheers user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) # cc_number = models.CharField(max_length=100) # cc_expiration = models.CharField(max_length=100) # cc_cvv = models.CharField(max_length=100) # objects = ListingManager() … -
django set cookie and delete cookie
I am setting a cookie in django without response. when user logs in i trigger an api to authenticate its data and then i am trying to save its user_id in cookie in a class and then in another class am trying to delete the cookie means user is logged out. class APIloginView(View): def get(self): r = requests.post(url,parameters) if 'user_id' not in request.COOKIES: request.COOKIES['user_id']='2133212332' print(request.COOKIES.get('user_id')) return HttpResponse(r) but when i try to access in value in another class it is showing me none class logout(View): def get(self): print(request.COOKIES.get('user_id')) pass Where am i doing wrong?and i know deleting a session like del request.session['user_id'],how to delete a particular cookie? -
sorl-thumbnail with memcached - 404 errors when trying to access thumbnail
I'm using django on a shared webhost, so all the memcached stuff is automatically configured and meant to work without issue in django. I have strings returned to a template which specify a URL to an image. They are not an ImageField, just a text string. My code in the template is : {% for instance in prods %} {% thumbnail instance.image_url "300x300" crop="smart" as im %} <img src="{{ im.url }} " > {% endthumbnail %} {% endfor %} This generates a URL like /static/media/cache/8f/cb/8fcbe5bd955ad8d999652c15eeda0959.jpg I have my media_dir and media_urls to be within /static, so this is correct. However, whenever I try to access this image url directly, I get a 404 error, and the image does not display in the page. Browsing the cache directory does reveal thumbnails generated from my images, none being used by my page currently. Searching my entire system for 8fcbe5bd955ad8d999652c15eeda0959.jpg returns nothing. How can I trouble shoot this? -
Django on docker running on cloud9
I'm setting up django application on cloud9. I click Run button to execute docker-compose, and then click Preview Running Application but browser says your access is denied. I'm not sure where I have to check to address the cause of this problem. What is the cause of this problem and what should I do to solve it? The application works on my local PC. Here is the part of my docker-compose.yaml. version: "3" services: django: build: context: ../app container_name: django working_dir: /app ports: - "5000:5000" privileged: true links: - mysqld - redis volumes: - app_static:/app/static - app_media:/app/media env_file: - django.env command: /usr/local/bin/uwsgi --ini /app/uwsgi.ini --touch-reload=/app/uwsgi.ini nginx: build: context: ../nginx container_name: nginx ports: - "8080:80" volumes: - /var/log/nginx - app_media:/app/media:ro - app_static:/app/static:ro links: - django -
I have different models in my project, but I want the same base.html template file for all of my modules. Is there a way I can set that up?
I am making a website for my church. I am using the django framework and I want to have a common base.html file througout all my apps/models. Is there a way to make that happen? I have tried using ../../ notation to get to a file that is in my main directory, but that raises the following error ... Exception Type: TemplateSyntaxError at / Exception Value: The relative path ''../../../sure_foundation_baptist /index.html'' points outside the file hierarchy that template 'main/index.html' is in. main/templates/main/index.html {% extends '../../../sure_foundation_baptist/base.html' %} {% block content %} ... {% endblock %} sure_foundation_baptist/base.html ... {% block body %} {% endblock %} I expected it to extend the file correctly, but the actual output is the previous error -
django include template without reloading tag
I have a base template in which I added some code which uses some tag sets. {% load staticfiles thumbnail load_permissions %} I decided to modularize this by separating some HTML code into a separate file and including it like so: {% include './sidepanel.html' %} the problem is that this sidepanel.html file uses some of the tags of the base file. Now I'm getting a TemplateSyntaxError complaining about a non loaded tag. Do I have to load them in both files or is there a more correct/elegant approach? -
Django change color of the tab in chrome
I ahve an app that monitors a few processes and alerts if some are failing. It does so by changing the background color of the body. However, due to lack of screen real estate the browser is often covered and I only have the top part visible, showing the tabs and maybe the address bar. So, I thought it would be neat if I could change the tab color as an alert. Chrome has the tabs above the address bar I can modify the title of the head... <head class="{{mode}}"> <title>ProcessMonitor</title> </head> but changing the background color here doesnt seem to do anything head.alert { background-color: #FFD6C6; font-family:'Source Sans Pro', sans-serif; } Is it possible to change the color of that tab somehow or does chrome just not support that? -
not able to login to admin: custom user model
I can authenticate using the command line >>> from django.contrib.auth import authenticate >>> user = authenticate(username='shiva@gmail.com',password='123456') >>> user <Employee: shiva@gmail.com> >>> but I am not able login using the url : http://localhost:8000/admin/login/?next=/admin/ model from django.db import models from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser, PermissionsMixin) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Employee(AbstractBaseUser,PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField(default=None) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = MyUserManager() REQUIRED_FIELDS = ['date_of_birth'] -
Django sitemap set custom paginate size?
So I'm using Django (1.11)'s sitemap framework and I need to add about 3.6m records into a sitemap. Django's built-in index sitemap automatically creates a paginated version of the sitemap. I believe each paginated sitemap page contains up to 500,000 records. That is too big and takes too long to load. Is there some way to set a custom number of records contained within each paginated sitemap page?