Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
【Django×Google App Engine】No module named 'MySQLdb' when deploying
I'm setting GitHub source ↓ https://github.com/priyankavergadia/Django-Dialogflow-GoogleVisionAPI But I have trouble in [Deploy the app to the App Engine standard environment] phase. At a glance Deploying have been done well.But I'm trying to access webservice, so [502 Bad Gateway] appears. At local environment(running python manage.py runserver), this program works well. Please give me some advices. My environment: ・Windows10 ・Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 ・django 2.2.4 ・MySQL second generation 5.7 mysql django I serched and tried. 1. install mysqlclient and uninstall PyMySQL 2. rewrite [import ~]part in various pattern... description in Django setting.py below # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # Install PyMySQL as mysqlclient/MySQLdb to use Django's mysqlclient adapter # See https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers # for more information import MySQLdb as sql# noqa: 402 # [START db_setup] if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/michatbot-250809:us-central1:polls-instance2', 'USER': 'test', 'PASSWORD': '', 'NAME': 'polls', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: … -
django soft deleted objects appear in filters
I implemented soft deletion by adding a BooleanFeild "deleted" to my models, overriding the delete method for CASCADING deletion and updating deleted field and changing objects with a custom manager which filters deleted objs. the problem is when I'm filtering other models on relations, the deleted rows affect the result. here's an example of my implementation: models: class Model_B(models.Model): # somefields... class Model_A(models.Model): label = models.CharField(max_length=30) deleted = models.BooleanField(default=False) model_bs = models.ManyToManyField(Model_B, through='RelationModel') # managers # return filterd objects by deleted=False objects = BaseManager() # return actually all objects including deleted ones allobjects = AllManager() def delete(self, *args, **kwargs): # first we set deleted flag of Zone to True self.deleted = True self.relationmodel_set.update(deleted=True) # save zone self.save() class RelationModel(models.Model): model_a = models.ForeignKey(Model_A, models.CASCADE) model_b = models.ForeignKey(Model_B, models.CASCADE) deleted = models.BooleanField(default=False) # managers # return filterd objects by deleted=False objects = BaseManager() # return actually all objects including deleted ones allobjects = AllManager() manager: class BaseManager(models.Manager): """ this manager will filter deleted """ use_for_related_fields = True def get_queryset(self): return super().get_queryset().filter(deleted=False) class AllManager(models.Manager): """ all """ def get_queryset(self): return super().get_queryset() query: Model_B.objects.filter(model_a__isnull=False) this returns Model_B objects which has a relations to deleted Model_A objects too. I tried: Model_b.objects.filter(model_a__isnull=False, model_a__deleted=False) this one returns … -
How to dump an object that is a child of a class (knowing that class casting is impossible in Python)?
I have a 3 models: Entity, Person which is a child of Entity, and Agenda: class Entity(models.Model): is_physical = models.BooleanField(default=True) class Person(Entity): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) agendas = models.ManyToManyField('Agenda') def simple_desc(self): return str(self.user) if self.user is not None else '? no user ?' class Agenda(models.Model): owner = models.ForeignKey(Entity, blank=True, null=True, on_delete=models.CASCADE, related_name='owner') You (almost) can't do simpler! Now I would like to list all the owners of all the agendas starting with agendas like: for agenda in Agenda.objects.all(): print(agenda.owner.simple_desc()) Because owner is an Entity, it doesn't know about simple_desc() (which is in its child Person). It's impossible to cast the owner into a Person. How would you do? Note aside: Right now, all owner are Person, but in a near futur, I'll create Company(Entity) which could also be owner of an Agenda, so I need to keep my models like this, don't suggest to change this organization this is not a valid solution. It's important, I have a more complex query, to make my loop with Agenda (and not Person) -
Django annotate sum subquery
How to sum a field of a subquery ( with OuterRef ) and annotate it on outer model? note that I have a common my_special_queryset_annotator that alter queryset by adding some annotations, ... so i dont want to use direct Sum('books__sections__page') let assume following models class Library(models.Model): votes=models.IntegerField() class Book(models.Model): library=models.ForiegnKey(Library) class Section(models.Model): book=models.ForiegnKey(Book) pages=models.IntegerField() # this works, but when want to use `my_special_queryset_annotator` # we could not do this simple annotation Library.annotate( all_pages=Sum('books__sections__pages'), ) # when want to sum on a Subquery, its must constructed like below but it dont work Library.objects.annotate( all_pages=SUM( # <-- problem Subquery( my_special_queryset_annotator( Section.objects.filter(book__libraray_id=OuterRef('id')) ).values('altered_pages') ) ) ) -
ModuleNotFoundError: No module named view, models
Tenho o seguinte problema tenho duas app Quero que um model de uma dessas apps passe informação para outra app exemplo Projeto: APP1.models APP2.view View da APP2 from projeto.app1.models import ObjetoX objeto_x = ObjetoX(parm=1) Ao fazer isso surge o seguinte erro: ModuleNotFoundError: No module named 'projeto.app1' -
Managing Urls while clicking on User profile
I'm managing to send emails to users that are present in my table and then showing success message on the same page. I'm successfully sending email to users(taking their id and then their email to send). While creating urls, I need to mention id as well which redirects me to another page. But what I want is to be redirected on the same page. Here's the table which contains the users: After clicking Send Mail, I'm taking the userid then email with this and then sendig mail. Taking userid: <a href="{% url 'profiles:sendMails' id=p.id %}"></button><span class="badge badge-success">Send Mail</span></a> Here's my views.py code on this button: def sendMails(request, id=None): query_user = get_object_or_404(NewUser, id=id) user_email = query_user.user admin_email = request.user.email result = send_emails(request, admin_email, user_email) context = { 'code': result } return render(request,'requested_users.html', context) And urls.py: path('dashboard/requested_users/<id>', views.sendMails, name='sendMails'), What I want to be on same page even after sending mail(such that the urls will be): path('dashboard/requested_users/', views.sendMails, name='sendMails'), But if I'm not providing the id in the urls, it's giving me the error: Reverse for 'sendMails' with keyword arguments '{'id': 1}' not found. I know I've asked a long question, but I'm really stuck into this. Thank you in advance. -
Error while upgrading django cms to 3.5 migration of "cms.0018_pagenode" stops saying Cannot resolve keyword 'title_set' into field
I am trying to upgrade an existing project from django-cms 3.4 to 3.5. I have Django 1.8 and while migrating at some point it stops giving an error : django.core.exceptions.FieldError: Cannot resolve keyword 'title_set' into field. in the documentation for 3.5 they have this sentence: Never-published pages can no longer have a ‘pending’ publishing state. A data migration, cms/migrations/0018_pagenode.py, removes this. my problem seems to be related to this. Can somebody helm me with that? I don't get it. Applying cms.0017_pagetype... OK Applying cms.0018_pagenode...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 147, in apply_migration state = migration.apply(state, schema_editor) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/migrations/operations/special.py", line 181, in database_forwards self.code(from_state.apps, schema_editor) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/cms/migrations/0018_pagenode.py", line 38, in unpublish_never_published_pages publisher_public__isnull=True, File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 679, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/project_folder/.venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 697, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) … -
telling the cmd what version of python im using
IM trying to make a website with django and im following a tutorial that is telling me i need to tell my cmd prompt what version of python im using. this is the video https://www.youtube.com/watch?v=FNQxxpM1yOs at the 10:46 mark he says to put C:/Python35/ python manage.py runserver. I am putting thi but it is not working. I am using version 3.7 so i replaced 35 with 37 but it is still not working. can someone please helps with this. -
Is raise ImproperlyConfigured is missing in django library
django library path: django\views\generic\detail.py class : SingleObjectTemplateResponseMixin why raise ImproperlyConfigured is not mentioned in 2nd last line of the code? class SingleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_field = None template_name_suffix = '_detail' def get_template_names(self): """ Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return the following list: * the value of ``template_name`` on the view (if provided) * the contents of the ``template_name_field`` field on the object instance that the view is operating upon (if available) * ``<app_label>/<model_name><template_name_suffix>.html`` """ try: names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. names = [] # If self.template_name_field is set, grab the value of the field # of that name from the object; this is the most specific template # name, if given. if self.object and self.template_name_field: name = getattr(self.object, self.template_name_field, None) if name: names.insert(0, name) # The least-specific option is the default <app>/<model>_detail.html; # only use this if the object in question is a model. if isinstance(self.object, models.Model): object_meta = self.object._meta names.append("%s/%s%s.html" % ( object_meta.app_label, object_meta.model_name, self.template_name_suffix )) elif getattr(self, 'model', None) is not None and issubclass(self.model, models.Model): names.append("%s/%s%s.html" % … -
How do i fix this issue with django start project?
after i installed django i wrote the start project command to verify django is working or not. i.e, django-admin startproject mysite cd mysite python manage.py runserver after that i got a ip address(http://127.0.0.1:8000/) but when i link to this http://127.0.0.1:8000/, it is showing unable to connect. what should i do now? -
Django POST method returns 500 server error on EC2 server
I am trying to build a web app using Django Rest framework. When I run the app on localhost 127.0.0.0/8000 it works fine. But when I deploy it on an EC2 server the POST methods return 500 server error. Here is one of the post methods in the views.py - class customer_location(APIView): def post(self, request, *args, **kwargs): customer_id = json.loads(request.body).get('customer_id') queryset = customers.objects.filter(cid= customer_id) serialize = customer_details(queryset, many=True) return Response(serialize.data, status=status.HTTP_200_OK) The urls.py is like this - from django.conf.urls import include, url from django.urls import path from rest_framework import routers from . import views urlpatterns = [ url(r'^customer_location/$', views. customer_location.as_view(), name='customer_location'), ] The DEBUG mode is set to False and the EC2 instance IP address is added in the ALLOWED_HOSTS. The GET methods are working fine but the POST methods give error. How to solve this ? -
Queryset with different datasets based on obj type
I want to implement in my application something similar to instagram's local notifications. The main problem is that local notifications can be different types. For example: 1) Simple one: "user started following you" (this is pretty straightforward) 2) More complicated: "user and +7 other liked your photo X" The first step of solution is to GROUP all notifications by targeted_user, event_type and user_who_triggered_event. For the first case it's okay as we will have all information. For the second case we will lack some information as Count of similar notifications. Also what if I need some additional information about those +7 user's who also liked photo X? class Notification(TimeStampedModel): OPEN_QUEST = 'open_quest' OPEN_PHOTO = 'open_photo' ACTION_CHOICES = ( (OPEN_PROFILE, _('Open profile')), (OPEN_PHOTO, _('Open photo')), ) LIKED_PHOTO = 'liked_photo' NEW_FOLLOWER = 'new_follower' EVENT_CHOICES = ( (LIKED_PHOTO, _('Liked photo')), (NEW_FOLLOWER, _('New follower')) ) action = models.CharField( max_length=255, choices=ACTION_CHOICES, ) event = models.CharField( max_length=255, choices=EVENT_CHOICES, ) title = models.CharField( max_length=255, ) body = models.TextField() class Meta: db_table = 'notifications' For this example I have 2 notifications in data base. Also I have ReceivedNotification model with FK to user and FK to notification and also data field(JSONField) to store actual information which particular user will … -
django ,model migrate: TypeError: an integer is required (got type str)
I am writing a apps and run makemigrations and migrate multiple time when i add new field. And now i have added a new foreignKey Field in models and then i run the command: python3 manage.py makemigrations after this, i run this command python3 manage.py migrate but it throws me following error TypeError: an integer is required (got type str) and later again i run this command pythion3 manage.py migrate --fake and i have successfully migrated and got another problem, when i go to django admin templates and click on my models to add data, it throws me this error: OperationalError at /admin/booking/seats/ no such column: booking_seats.seat_for_id I am not getting whats wrong with it, can anyone help me to fix this? for your reference, see my models: class Seats(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) seat_no = models.IntegerField( choices=SeatChoices.choices(), ) availability = models.IntegerField( choices=SeatAvailability.choices(), default=SeatAvailability.AVAILABLE ) seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) def __str__(self): return str(self.seat_no) class Show(models.Model): alias = models.UUIDField( primary_key=True, default=uuid4, editable=False ) show_schedule = models.IntegerField( choices=ShowSchedule.choices(), ) movie = models.CharField(max_length=50) def __str__(self): return str(self.show_schedule) I just added this new field seat_for = models.ForeignKey('booking.show', on_delete=models.CASCADE) then i facing the problem Can anyone help me in this case? -
Chartjs in Django, special characters in label not supported?
I have some values passed to Chart.js but I found neither / nor - is supported. If the labels are harded coded as UK-aaa or N/A, it works fine. If it is passed as a varible which the project requires, UK or N (letters before the special characters will not recognized and no chart shows. Is there a workround on Javascript other than removing special characters in labels? Thanks. var C3 = document.getElementById(canv3.getAttribute('id')); if (C3.getContext) { if (C3.getContext) { new Chart(document.getElementById(canv3.getAttribute('id')), { type: 'bar', data: { labels: [{{res.21}},{{res.22}},{{res.23}}], //this is not supported if same value as below passed. //labels: ['UK-aaa','N/A','N/A'], //this is supported datasets: [ { backgroundColor: "rgba(35, 35, 0.5)", borderColor : "rgba(149, 62, 205, 1)", pointBackgroundColor: "rgba(62, 149, 205, 1)", data: [{{res.18}},{{res.19}},{{res.20}}] //numeric value }, ] }, options: { responsive: false, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); }} -
making modal for every entry in a list view using Js?
I have a page where multiple images are present and I want to make the users able to crop any of them so I made a for loop to make a modal for each image and I looped the js function also. this is my modal. {% for image in Patient_detail.images.all %} <div class="modal fade" id="modalCrop{{image.pk}}"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Crop the photo</h4> </div> <div class="modal-body"> <img src="" id="image{{image.pk}}" style="max-width: 100%;"> </div> <div class="modal-footer"> <div class="btn-group pull-left" role="group"> <button type="button" class="btn btn-default js-zoom-in"> <span class="glyphicon glyphicon-zoom-in"></span> </button> <button type="button" class="btn btn-default js-zoom-out"> <span class="glyphicon glyphicon-zoom-out"></span> </button> </div> <button type="button" class="btn btn-default" data-dismiss="modal">Nevermind</button> <button type="button" class="btn btn-primary js-crop-and-upload">Crop and upload</button> </div> </div> </div> </div> {% endfor %} and here's the function I used {% for image in Patient_detail.images.all %} $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#crop{{image.pk}").click(function () { var img_src = document.getElementById("img{{image.pk}}").src $("#image{{image.pk}}").attr("src", img_src); $("#modalCrop{{imahge.pk}}").modal("show"); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image{{image.pk}}"); var cropBoxData; var canvasData; $("#modalCrop{{image.pk}}").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", … -
django usercreationform is_valid always return false
i'm green hand to django, when i try to use the usersignupform, the request post is like `<QueryDict: {'csrfmiddlewaretoken': ['Wxlj42vbyAweKevBeSs5TvGj1ot8tJknUOGzmlKCphs5cDnqvsmriCSK9wYDuAof'], 'username': ['dulong11'], 'email': ['stephen.du@abc.com'], 'password1': ['dulong'], 'password2': ['dulong'], 'submit': ['']}` then the usercreationform.is_valid() will always return false, i do not know why, and how it happens? why it cannot work?? form.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserSignUpForm(UserCreationForm): #username = forms.CharField() email = forms.EmailField(max_length=100) #password1 = forms.CharField() #password2 = forms.CharField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2') register.html <form action="." method="post" id="frm" class="frm"> {% csrf_token %} <div class="r-list"> <div class="line"> <i class="dqfont icon-mobilephone"></i> <input type="text" name="username" placeholder="用户名" autocomplete="off"> <span class="error" id="tel_error"></span> </div> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-mobilephone"></i> <input type="email" name="email" placeholder="请输入邮箱" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-pass"></i> <input type="password" name="password1" placeholder="请输入密码" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="line"> <i class="dqfont icon-pass"></i> <input type="password" name="password2" placeholder="请再次输入你的密码" autocomplete="off"> </div> <span class="error"></span> </div> <div class="r-list"> <div class="protocol"> <span class="checkbox-checked" id="accept">我已阅读并同意<a href="#" target="_blank">《IPLink用户协议》</a>和<a href="#" target="_blank">《隐私保护》</a></span> </div> </div> <div class="r-list"> <span class="error"></span> <!--a href="#" class="btn" id="btn">同意协议并注册</--a>--> <button type="submit" class="btn" name="submit" id="btnSubmit" style="width:380px">同意协议并注册</button> </div> </form> -
Is it possible to have a hosted Django site use the client's interfaces to create a SSH session with a local privately addressed device
I am trying to learn programming to expand my horizons a bit. I have been creating a Django app that automates several aspects of my day to day job. It would be nice if that Django app could be on a public server for accessibility but also have a view that can initiate an SSH session with various privately addressed devices, mostly to verify network changes were successful. In my mind the script would almost need to run on the client side to use their IP address within the private network but from my understanding, Django is server side. Any advice on how to work around this? -
AssertionError: You need to pass a valid Django Model in UserProfile.Meta, received "None"
I'm adding Django Model to a graphql api using the AbstractBaseUser custom user model. The Admin works fine except that I get an error when trying to access the graphql api, 'You need to pass a valid Django Model in UserProfile.Meta, received "None"' I've tried adding AUTH_USER_MODEL = 'noxer_app.MyUser' to settings, yet it doesn't work In models.py: from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, company=company, company_reg_no=company_reg_no, address=address, phone=phone, image=image, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, company, company_reg_no, address, phone, image, password): user = self.create_user( email, password=password, first_name=first_name, last_name=last_name, company=company, company_reg_no=company_reg_no, address=address, phone=phone, image=image, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') company = models.CharField(max_length=255, default='') company_reg_no = models.CharField(max_length=255, default='') address = models.CharField(max_length=400, default='') phone = models.CharField(max_length=13, default='') image = models.ImageField(default='noimage.jpg', upload_to = 'profile_pics') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'company', 'company_reg_no', 'address', 'phone', 'image'] def __str__(self): … -
Is it recommended to manually redirect sub-domains to an application from the project itself?
We have different types of users whom we'd like to redirect to different views based on the sub-domain in the URL. In our project directory, we examine each and every request for the sub-domain keywords, viz. ut1.domain or ut2.domain. Is this a good solution? If not, please suggest something better. User Type 1 ut1.domain.com/login/ User Type 2 ut2.domain.com/login/ This is how the sub-domains are being planned to be handled. def handle_urls(request): if "ut1.domain." in request.build_absolute_uri(): return HttpResponseRedirect('login/') context = {} return render(request, "home.html", context) The purpose of the sub-domains is to point to different applications in the same project. We expect to add more than a dozen sub-domains in the next few months for various new applications. Thank you for your time reading this. -
how to perform count for a secod foreign key in django?
i have three models Category,Post,Comment class Category(models.Model): class Meta: verbose_name_plural = "Categories" COLOR_CHOICES = ( ('primary', 'Blue'), ('success', 'Green'), ('info', 'Sky Blue'), ('warning', 'Yellow'), ('danger', 'Red') ) title = models.CharField(max_length=250, unique=True) description = models.CharField(max_length=250) slug = models.SlugField(max_length=200,) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) visited = models.IntegerField(default=0) color = models.CharField( max_length=20, default='primary', choices=COLOR_CHOICES) class Post(models.Model): STATUS_CHOICES = ( (True, 'Visible'), (False, 'Hidden') ) title = models.CharField(max_length=250) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) slug = models.SlugField(max_length=200,) status = models.BooleanField(default=False, choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) visited = models.IntegerField(default=0) class Comment(models.Model): STATUS_CHOICES = ( (True, 'Visible'), (False, 'Hidden') ) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.BooleanField(default=True, choices=STATUS_CHOICES) i want to perform a query set to get categories and number of comments of each category, i cant find a good way. i already know how to count posts for each category using annotate. i tried : categories = Category.objects.annotate(nb_comments=Count('post__comment')) -
Django apache2 KeyError for SECRET_KEY with environment variable
I try to deploy django on a debian server. To protect the secret key i store them in a environment variable. I edit /etc/profile an add: SECRET_KEY="123456789...."; export SECRET_KEY I tested if the variable is set with printenv | grep SECRET_KEY and echo $SECRET_KEY. It works fine but if i open the website i get Forbidden You don't have permission to access / on this server. and in the error.log from apache: .... raise KeyError(key) from None [Tue Sep 17 14:11:20.062194 2019] [wsgi:error] [pid 13523:tid 140622223152896] [client 123.456.78.910:50361] KeyError: 'SECRET_KEY' .... Why django can't read the environment variable? -
why am I getting a none value in my method inside of my model with nested if?
I'm new in django trying to do a project of management of a small restaurant, in my consummation model,I have attributes that are foreign keys, and the date of consummation, now I try to calculate the sum of those attributes in a method inside the model by returning the total. I tried class Consommation(models.Model): entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True) food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True) dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True) boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True) autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True) consomme_le = models.DateTimeField(default=timezone.now, editable=False) class Facture(models.Model): consommation = models.OneToOneField(Consommation, models.CASCADE, null=True, blank=True, verbose_name='Facture') fait_le = models.DateField(default=timezone.now, editable=False) is_regle = models.BooleanField(default=False, verbose_name='Est regle') initials_caissier = models.CharField(max_length=5, verbose_name='Initiales du Caissier') def __str__(self): return 'Facture du :' + ' ' + str(self.fait_le) def get_absolute_url(self): return reverse('clients:facture_detail', kwargs={'pk': self.pk}) def net_a_payer(self): if self.consommation: if not self.consommation.entree: self.consommation.entree.price = int(0) if not self.consommation.food: self.consommation.food.price = int(0) if not self.consommation.dessert: self.consommation.dessert.price = int(0) if not self.consommation.boisson: self.consommation.boisson.price = int(0) if not self.consommation.autres: self.consommation.autres.price = int(0) return self.consommation.entree.price + self.consommation.food.price + self.consommation.dessert.price + self.consommation.boisson.price + self.consommation.autres.price net_a_payer: means the total sum to pay I expect the result to be the sum of the attibutes instead of … -
Creating a generic search view in Django
I am struggling to create my custom generic view in django to easily create search pages for certain models. I'd like to use it like this: class MyModelSearchView(SearchView): template_name = 'path/to/template.html' model = MyModel fields = ['name', 'email', 'whatever'] which will result in a view that returns a search form on GET and both form and results on POST. The fields specifies which fields of MyModel will be available for a user to search. class SearchView(FormView): def get_form(self, form_class=None): # what I'v already tried: class SearchForm(ModelForm): class Meta: model = self.model fields = self.fields return SearchForm() def post(self, request, *args, **kwargs): # perform searching and return results The problem with the code above is that form will not be submitted if certain fields are not be properly filled. User should be allowed to provide only part of fields to search but with the code I provided the form generated with ModelForm prevents that (for example because a field in a model cannot be blank). My questions are: Is it possible to generate a form based on a model to omit this behaviour? Or is there any simpler way to create SearchView class? I don't want to manually write forms if … -
How to redirect to previous page after language changing?
When I am trying to use next it doesn't work because in next-url there are old language code so language doesn't change. my template: <a href="{% url "set_language_from_url" user_language="en" %}?next={{request.path}}">en</a> <a href="{% url "set_language_from_url" user_language="ru" %}?next={{request.path}}">ru</a> my url: path('language-change/<user_language>/', views.set_language_from_url, name="set_language_from_url"), my view: def set_language_from_url(request, user_language): translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language redirect_to = request.POST.get('next', request.GET.get('next', '/')) return redirect(redirect_to) -
Run multiple Django application on mutilple subdomains with nginx and Gunicorn
I want to run multiple sites on the same instance of EC2. I configured my site as per this doc. I have two projects: 1. project_1 2. project_2 project_1 on beta.example.com project_2 on api.example2.com I am running project_1 successfully with Nginx and gunicorn and want to add project_2. I have tried this answer but is not working.