Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mezzanine Fabric deployment, PSQL issue - "Error: role "project" already exists"
Having huge troubles deploying Mezzanine on digitalocean, and I'm taking it step by step to figure out all the small issues individually. Running "fab create" results in successfully (I guess?) setting up the virtualenv, but when it comes to setting up the PSQL database, it errors with the following (full output): [1xx.xx.xxx.xxx] Executing task 'create' ←[1;32m------ create ------←[0m ←[1;34m$ ←[0m←[1;33mlocale -a←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] Login password for 'adm': ←[1;34m$ ←[0m←[1;33mmkdir -p /home/adm/mezzanine/project←[0m←[1;31m ->←[0m ←[1;34m$ ←[0m←[1;33mmkdir -p /home/adm/.virtualenvs←[0m←[1;31m ->←[0m Virtualenv already exists in host server: project Would you like to replace it? [Y/n] y ←[1;34m$ ←[0m←[1;33mrm -rf project←[0m←[1;31m ->←[0m ←[1;34m$ ←[0m←[1;33mvirtualenv project←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: Using base prefix '/usr' [1xx.xx.xxx.xxx] out: New python executable in /home/adm/.virtualenvs/project/bin/python3 [1xx.xx.xxx.xxx] out: Also creating executable in /home/adm/.virtualenvs/project/bin/python [1xx.xx.xxx.xxx] out: Installing setuptools, pip, wheel... [1xx.xx.xxx.xxx] out: done. [1xx.xx.xxx.xxx] out: [localhost] local: git push -f ssh://adm@1xx.xx.xxx.xxx/home/adm/git/project.git master adm@1xx.xx.xxx.xxx's password: Everything up-to-date ←[1;34m$ ←[0m←[1;33mGIT_WORK_TREE=/home/adm/mezzanine/project git checkout -f master←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: Already on 'master' [1xx.xx.xxx.xxx] out: ←[1;34m$ ←[0m←[1;33mGIT_WORK_TREE=/home/adm/mezzanine/project git reset --hard←[0m←[1;31m ->←[0m [1xx.xx.xxx.xxx] out: HEAD is now at a1fe1de Droplet reset [1xx.xx.xxx.xxx] out: [1xx.xx.xxx.xxx] out: sudo password: [1xx.xx.xxx.xxx] out: ERROR: role "project" already exists [1xx.xx.xxx.xxx] out: Fatal error: sudo() received nonzero return code 1 while executing! Requested: psql -c … -
How to change a field in parent class while creating chiled class fields in forms.py and views.py?
I'm was creating ModelForm I try to make change the parent class while saving child class fields to the database, in the views.py I made but it didn't save to the database. here is my model.py class Table(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) book = models.BooleanField(default=False) class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) taple = models.OneToOneField(Table, on_delete=models.CASCADE, null=True, blank=True) @receiver(post_save, sender=User) def update_people_profile(sender, instance, created, **kwargs): try: instance.people.save() except ObjectDoesNotExist: People.objects.create(user=instance) Class People is the child class and Table is the parent class so I'm using People class for making forms. here is my forms.py class Booking(forms.ModelForm): class Meta: model = People fields = [ 'taple', ] So I want to make True book field in Table class and save it to the database when saving Booking form. here is my views.py def booking(request): if request.method == 'POST': try: people_instance = People.objects.get(user=request.user) except Table.DoesNotExist: people_instance = People(user=request.user) form = Booking(request.POST, instance=people_instance) if form.is_valid(): user = form.save(commit=False) user.taple.booking = True user.refresh_from_db() user.user = request.user user.taple = form.cleaned_data.get('taple') user.save() print(user.taple.booking, user.taple.id) return redirect('booked') else: form = Booking() return render(request, 'main/booking.html', {'form': form}) Any Idea? -
How to deploy a wep abb within my work network?
I created an API for the company i work however i would like people having access in the same company network, how can i achieve this? I currently modified the allowed host as follow: ALLOWED_HOSTS = ['127.0.0.1', 'localhost','192.168.6.7', '127.0.1.1', '161.19.109.123'] however only work in my computer under IP: 127.0.0.1:8000, any suggestions? FYI i do not have administrator privilege. -
Set up django-celery-email for local dev
It seems the best way to send emails from the django-allauth app asynchronously is to simply install django-celery-email. But the packages warns that This version requires the following versions:Python 2.7 and Python3.5, Django 1.11, 2.1, and 2.2 Celery 4.0 I've only been using python for several months and never encountered a situation where two python version are needed on a project. And I'm using the official recommendation of pipenv for local development. A quick google shows that it isn't possible to have two python interpreters installed in the virtual environment. Since the plugin seems so popular I wondered how others were setting it up? Apologies if I've missed something major that explains this. A bonus answer would also take into account that I am using docker and the docker image will install the python packages like this. RUN pipenv install --system --deploy --ignore-pipfile Many thanks in advance. -
How do I use Django template tags inside javascript
I am using a library called FullCalendar and I want my model data inside my template inside the javascript which I have seen many people do. But for some reason the template tags won't register as template tags and I get an error. <script> document.addEventListener('DOMContentLoaded', function() { var Calendar = FullCalendar.Calendar; var Draggable = FullCalendarInteraction.Draggable; var containerEl = document.getElementById('external-events'); var calendarEl = document.getElementById('calendar'); var checkbox = document.getElementById('drop-remove'); // initialize the calendar // ----------------------------------------------------------------- var calendar = new Calendar(calendarEl, { plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'bootstrap', 'interaction' ], themeSystem: 'bootstrap', selectable: true, select: function(info) { var titleStr = prompt('Enter Title'); var date = new Date(info.startStr + 'T00:00:00'); // will be in local time if (!isNaN(date.valueOf())) { // valid? calendar.addEvent({ title: titleStr, start: date, allDay: true, }); } }, locale: "sv", header: { left: 'prev,next today', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, customButtons: { }, eventClick: function(info) { alert('Event: ' + info.event.title); }, editable: true, droppable: true, events: [ {% for event in events %} { title: "{{ event.name}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', }, {% endfor %} ], }); calendar.render(); }); </script> the part that is not working is the {% for event in events %} loop, the view parses the … -
How to save objects en la UpdateView class, returning a Json?
I have 2 related models for an fk and to which I access. But to save the instances of the forms in the UpdateView class, I get the error "AttributeError: type object 'Users_up' has no attribute 'object' [10 / Oct / 2019 15:18:17] "POST / PermissionUpdateView / 3 / HTTP / 1.1" 500 "and don't let me save with the post help method please, what am I wrong? viws.py class PermisoUpdateView(UpdateView): model = Permiso second_model = Users template_name = 'plantillas/permisos_update.html' form_class = Permiso_update second_form_class = Users_up def get_context_data(self,*args,**kwargs): context =super(PermisoUpdateView, self).get_context_data(**kwargs) pk = self.kwargs.get('pk', 0) p = self.model.objects.get(id=pk) u = self.second_model.object.get(id=p.usuario_id) if 'form' not in context: context['form'] = self.form_class(instance=p) if 'form2' not in context: context['form2'] = self.second_form_class(instance=u) context['id'] = pk return context def post(self, request,*args, **kwargs): self.object = self.get_object id_Permiso = kwargs['pk'] per = self.model.objects.get(id=id_Permiso) us = self.second_form_class.object.get(id=per.usuario_id) form = self.form_class(request.POST, instance=per) form2 = self.second_form_class(request.POST, instance=us) if form.is_valid and form2.is_valid and request.is_ajax(): form.save() form2.save() return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole else: return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole -
Add context variable as an aggregate or annotate of 2 cols in CBV's get_context_data()
I want to return total value as revenue variable in get_context_data method of ClassBasedView. I also want to return another operation: total - shipping_cost as revenue_no_shipping_cost variable in context. I've tried: from django.db.models import F, Sum class OrdersListView(PermissionRequiredMixin,ListView): model = Order permission_required = 'is_staff' template_name = "order/revenue.html" paginate_by = 10 def get_queryset(self): filter_month = self.request.GET.get('filtromes', '0') if filter_month == "0": return Order.objects.filter(status = 'recibido_pagado') else: return (Order.objects .filter(created__month=filter_month, status = 'recibido_pagado')) def get_context_data(self, **kwargs): context = super(OrdersListView, self).get_context_data(**kwargs) qs = kwargs.pop('object_list', self.object_list) order = self.request.GET.get('orderby', 'created') context = {} revenue = qs.aggregate(revenue=Sum('total')) revenue_no_shipping = qs.annotate(revenue_no_shipping=F('total') + F('shipping_cost')) context['revenue'] = revenue context['revenue_no_shipping'] = revenue_no_shipping context['filtromes'] = self.request.GET.get('filtromes', '0') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = "catalogo" return context But in template, I'm getting: For revenue: {'revenue': Decimal('42')} #is 42.00 For revenue_no_shipping: <QuerySet [<Order: 58>]> #Should be 25.00 -
django.core.exceptions.ValidationError: ["'_auth_user_id' value must be an integer."] error on Django
as for the title I have this problem with validation in Django. This error occours when i Logout, it seems like the system is looking for the user id but, because i clear the session with the log out(not sure anyway if this is right, I use django auth for the login/logout system), it can't find any user with same id in the session and is giving me this error. So I tried removing all the user call i have in the code but it is still not working at all. Here as follow the full error log. Internal Server Error: / Traceback (most recent call last): File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\__init__.py", line 941, in to_python return int(value) ValueError: invalid literal for int() with base 10: '_auth_user_id' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\gello\Desktop\Projects\buyit\home\views.py", line 12, in index return render(request, "index.html", {"products": products, "product_reviews": product_reviews}) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\gello\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string return … -
Method GET Django and Angular error 500 internal server
I'm building a basic app with login, register, etc. now i try finish the login using Django like backend and fronted with Angular, but i can't end my login because this error, when i try login with the correct credentials and redirect to new page or url show this error. TypeError at /doctor 'list' object is not callable"in network panel" service .ts constructor(private http: Http, private httpClient: HttpClient) { } private headers = new Headers({ 'Content-Type': 'application/json' }); getDoctores(): Promise<Doctor[]> { return this.http.get(this.baseurl + '/doctor?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Doctor[]) } component .ts constructor(private dataService: dataService, public dialog: MatDialog, private router: Router) { this.getDoctores(); this.selectedDoctor = { id: -1, nombreDoc: '', apellidoDoc: '', rutDoc: '', direccionDoc: '' , telefonoDoc: '', release_date: '' } } getDoctores(): void { this.dataService .getDoctores() .then(doctores => this.doctores = doctores); } url.py path('auth/login/', obtain_jwt_token), path('auth/refresh-token/', refresh_jwt_token), url(r'^doctor$', views.DoctorList.as_view()), url(r'^doctor/(?P<pk>[0-9]+)$', views.DoctorDetail.as_view()), view.py class DoctorList(generics.ListCreateAPIView): queryset = Doctor.objects.all() serializer_class = DoctorSerializer class DoctorDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Doctor.objects.all() serializer_class = DoctorSerializer -
How to implement User system for job board (I need employers to be able to register and create posts)?
I am creating a job board where users can search a zip code and see jobs in their area. I have the following models.py: class Business(models.Model): name = models.CharField(max_length = 150) address = models.CharField(max_length = 150) city = models.CharField(max_length = 150) zip_code = models.CharField(max_length = 10) state = models.CharField(max_length = 30) phone_number = models.CharField(max_length = 10) class Job(models.Model): business = models.ForeignKey(Business, on_delete = "models.CASCADE") #when the referenced object is deleted, also delete the objects that have references to it. title = models.CharField(max_length = 100) description = models.CharField(max_length = 500) zip_code = models.CharField(max_length = 10) def save(self, *args, **kwargs): zip_code = self.business.zip_code super(Job, self).save(*args, **kwargs) To use the website to look for jobs, you do not have to sign in. However, I obviously need employer's to be able to create an account so that they can register a business and post jobs for said business. I am not sure how to approach this and have seen many different ways to go about it online. Should I have the Business model extend the User model as such: class Business(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #other fields... and then when an employer registers show a form that includes the User fields as well as … -
Importerror: How to import django-nose package?
Installed django-nose in virtual environment: (venv) user@~/../src$ pip install django-nose DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: django-nose in /home/user/../venv/lib/python2.7/site-packages (1.4.6) Requirement already satisfied: nose>=1.2.1 in /home/user/../venv/lib/python2.7/site-packages (from django-nose) (1.3.7) (venv) user@~/../src$ Django settings in test.py has django-nose package mentioned as INSTALLED_APPS, shown below: from base import * import os # Installed apps INSTALLED_APPS += ('django-nose', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' TEST_OUTPUT_DIR = os.environ.get('TEST_OUTPUT_DIR', '.') NOSE_ARGS = [ '--verbosity=2', '--nologcapture', '--with-coverage', '--cover-package=todo', '--with-spec', '--spec-color', '--with-xunit', '--xunit-file=%s/unittests.xml' % TEST_OUTPUT_DIR, '--cover-xml', '--cover-xml-file=%s/coverage.xml' % TEST_OUTPUT_DIR, ] # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('MYSQL_DATABASE', 'xxxxx'), 'USER': os.environ.get('MYSQL_USER', 'xxx'), 'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'xxx'), 'HOST': os.environ.get('MYSQL_HOST', 'localhost'), 'PORT': os.environ.get('MYSQL_PORT', '3306') } } But django-nose package is not getting imported, based on below error: (venv) user@~/../src$ ls db.sqlite3 manage.py todo todobackend (venv) user@~/../src$ python manage.py test --settings=todobackend.settings.test Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/../venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File … -
Pytest delete db after tests
I have a test suite in pytest-django and I want to create a database at the start of the test and then delete the same as soon a test is completed in order to simulate the scenario without keeping a huge chunk of data. Any help would be appreciated. Thanks in advance! -
Unable to fetch data from database using django
I have created one small project in django, in which database is connected with django and having 'Reg' as table name in database. In models.py from django.db import models class Reg(models.Model): Name = models.CharField(max_length=10) Email = models.CharField(max_length=20) TUID = models.CharField(max_length=10) Password = models.CharField(max_length=8) In views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from .models import Reg, Group from django.http import HttpResponse def login(request): raw = Group.objects.all() return render(request, 'login.html', {'raw': raw}) In login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <p>hello....</p> {% for val in raw %} <p>{{ val.Name }}</p> {% endfor %} <p>end...</p> </body> </html> expected result should be data from database, but getting only hello... end... -
DRF - How do I link back from model class with PrimaryKey to model class with ForeignKey
I have two models Job and JobDescription. I have a ForeignKey jobid defined in JobDescription. The django-rest-framework does its magic and finds the automatically created PK id in Job to link to. In serializers.py JobDescriptionSerializer jobid will give me a hyperlink to the Job id. So far so good. At this moment however, this is a one way street (JobDescription -> Job). I would like to add a field to Job model/serializer that will allow hyperlinking the other way around as well (Job -> JobDescription). I went through the Django models documentation around ForeignKey and there are some references to forward/backward relationships, but how do I implement this in the rest-framework models/serializers? Thanks for your help in advance! models.py: class Job(models.Model): title = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='') location = models.CharField(max_length=100, default='') created_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['id'] def __str__(self): return self.title class JobDescription(models.Model): jobid = models.ForeignKey(Job, related_name='desc2job', on_delete=models.CASCADE) description = models.TextField(blank=False) created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['id'] def __str__(self): return str(self.jobid) serializers.py: class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ( 'url', 'id', 'title', 'type', 'location', 'created_date') class JobDescriptionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = JobDescription fields = ('url', 'id', 'jobid', 'description', 'created_date') -
Django Testing - authenticate() returns None
Working on making some unittests with Django, and trying to make some testing with the login process with the login form. I am using modified User model just to make the email field unique; otherwise nothing drastically different. account/views.py def post(self, request): # Retrieve the username and password username = request.POST['username'] password = request.POST['password'] # Create a user object from authentication, or return None user = authenticate(username=username, password=password) # Check if user was created if user is not None: # Rest of the code, irrelevant... account/test_views.py def test_account_login_POST_successful_login(self): # Create a user to test login CustomUser.objects.create_user( username='test_user', email='test_user@intranet.com', password='flibble' ) response = self.client.post(self.login_url, { 'username': 'test_user', 'password': 'flibble' }) self.assertEqual(response.status_code, 301) account/models.py class User(AbstractUser): # Make the email field unique email = models.EmailField(unique=True) project/settings.py # Authentication AUTH_USER_MODEL = 'account.User' Funny thing is that login works normally on the web app, but when testing it always returns None. I've tried to check_password() with the created user, and it returns true in both the test method and the view method. I've also tried putting in AUTHENTICATION_BACKEND = ['django.contrib.auth.backends.ModelBackend'], but no go. -
Celery: different settings for task_acks_late per worker / add custom option to celery
This question is a follow up of Is there any way to find out the hash value of two files? I had a problem with celery (see the question that I follow up) and in order to resolve it I'd like to have two celery workers with -concurrence 1 each but with two different settings of task_acks_late. My current approach is not very beautiful. I am doing the following: in settings.py of my django project: CELERY_TASK_ACKS_LATE = os.environ.get("LACK", "False") == "True" This allows me to start the celery workers with following commands: LACK=True celery -A miniclry worker --concurrency=1 -n w2 -Q=fast,slow --prefetch-multiplier 1 celery -A miniclry worker --concurrency=1 -n w1 -Q=fast What would be more intuitive would be if I could do something like: celery -A miniclry worker --concurrency=1 -n w2 -Q=fast,slow --prefetch-multiplier 1 --late-ack=True celery -A miniclry worker --concurrency=1 -n w1 -Q=fast --late-ack=False I found Initializing Different Celery Workers with Different Values but don't understand how to embed this in my django / celery context. In which files would I have to add the code that's adding an argument to the parser and how could I use the custom param to modify task_acks_late of the celery settings. -
Django populating model in signal with accessing request
I am in trouble in populating a table, at first see my models. from django.contrib.auth.models import User class Group(models.Model): members = models.ManyToManyField( User, through='PersonGroup', related_name='person_of_the_group' ) class PersonGroup(models.Model): group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name='group_person_of_group' ) person = models.OneToOneField( User, on_delete=models.CASCADE, related_name='group_person_of_group' ) I want when I create a group, the PersonGroup should populate automatically, I tried to achieve it in the signal but failed to do it, coz, I couldn't access request.user in signal @receiver(post_save, sender=Group) def create_person(sender, instance, created, **kwargs): if created: PersonGroup.objects.create( # ) Can anyone help to access to request in the signal? I need to solve this problem in signal at any means -
Unusual error occurring when attempting to remove user from Django admin page
I am creating a simple endpoint in my project, where a user can delete their account. When I send this request, it successfully works: However when I attempt to remove a user from my admin page, this error occurs: Error: IntegrityError at /admin/users/user/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". My code: models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass def __str__(self): return self.username views.py: def deleteuser(request, username): user = User.objects.get(username=username) user.delete() return JsonResponse({"message": "User successfully removed"}, status=200) -
Why is bar blacklisted in pylint
I have an error while linting my django project with pylint. Pylint shows an error while linting my django project "C0102: Black listed name "bar" (blacklisted-name)" It's correct that I have a function called bar, but why is this name blacklisted? I don't know of a built-in with that name. -
gunicorn vs celery for concurrency in django
In Django webapp that's deployed, I get a POST request from external source in views.py As soon as post request is received, I modified post function to do certain action and deliver results(1.1.1.1 is endpoint) in views.py def post(self, request, *args, **kwargs): #do some action #deliver results to 1.1.1.1 In this case, I'm currently running task as the request comes. For instance, if 5 requests come in at once, it's currently processing one by one. But, I'd like to process all requests at once(assuming there are enough server load) and deliver results back. Would increasing workers in gunicorn solve the issue of concurrency or would it be better to utilize job queue like celery? I need something lightweight. If gunicorn is enough, how many workers would need to be set? And what is best practice method? -
Assign value to one-to-many field through django code
I am trying to assign value to a database entry that is defined using the models.ForeignKey. How should I refer to the variables in the referred model? In the code below, the assignment update_user.appointments.requester_name = requesting_user does not work. Googling has not helped me find the right solution. How should one refer to such variables from django/python? Below is my models.py class AppointmentRequest(models.Model): my_name = models.TextField(default='') requester_name = models.TextField(default='') meeting_year = models.TextField(default='') class CustomUser(AbstractUser): firstname = models.TextField(default='') lastname = models.TextField(default='') appointments = models.ForeignKey(AppointmentRequest, on_delete=models.CASCADE, default='', blank=True, null=True) I want to modify the value of appointments entry, i.e., my_name, requester_name, etc. Below is the code in views.py def book_appointment(request): requesting_user = request.GET['requesting_user'] update_user = CustomUser.objects.get(username=requested_user) update_user.appointments.requester_name = requesting_user -
ModuleNotFoundError: No module named 'mylife.wsgi'
So I'm trying to deploy my website in heroku. It gets deployed successfully but when i open the site, it displays application error. When I ran the logs, it displayed no module name mylife.wsgi. Here is the full error that I got. Starting process with command `gunicorn mylife.wsgi --log-file -` Process exited with status 3 State changed from starting to crashed. Also __import__(module) ModuleNotFoundError: No module named 'mylife.wsgi' I tried changing wsgi file, even added middleware, but no luck. Here is my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mylife.settings') application = get_wsgi_application() Here is my middleware from settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is my Procfile web: gunicorn mylife.wsgi --log-file - Here is my requirements.txt Django==2.0 dj-database-url==0.5.0 dj-static==0.0.6 gunicorn==19.9.0 Pillow==3.3.0 psycopg2-binary==2.7.7 whitenoise==4.1.2 django_ckeditor Here is the file structure └───mylife ├───accounts │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───accounts │ └───__pycache__ ├───daily │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ ├───css │ │ └───js │ ├───templates │ │ └───daily │ └───__pycache__ ├───mylife │ └───__pycache__ └───staticfiles ├───admin │ ├───css │ │ └───vendor │ │ └───select2 │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor … -
What are the directives available in django similar to angular directives?
Do we have any directives in django similar to Angular directives like ng-show, ng-if, ng-for etc? When I worked on Angular, those directives are very helpful to me to finish my work faster. For example: how will you use a for loop in templates of django? -
Quiero que todos los navegadores acepten la coma para decimales
Tengo un formulario que en Firefox me acepta la coma para separar los decimales pero con Chrome me acepta el punto. Quisiera que los dos navegadores me acepten siempre coma; quiero que sólo se pueda ingresar números como 560,25 o 1250,75, por ejemplo. Estamos usando HTML5, en un proyecto con Python/Django. -
How to filter models efficiently in Django?
I have a website which will have many companies (model instances) and each company will have many users (model instances). What is the best way to separate the users by company so that the users of each company are all segregated from each other? All the ways I am currently thinking about doing this seems to use some sort of filtering in every section of the site which seems very inefficient. I already used Django's Groups for different employee types. Should groups be applied at the top of the chain (i.e. companies)? Even if I applied companies to groups I would probably be filtering at the template level quite often which seems inefficient and "un-pythonic". What are the best practices here?