Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For Python's Django experts Chrome console in django doesn't work means console.log won't show any messages
Hello i'll try to go directly to the point with all the necessary details i have a django application working on a website with only html js css and some images. in javascript if i put console.log() anywhere in my javascript file it doesn't log any messages in the console alert() works pretty well javascript code works fine only my logs doesn't show up. note that i haven't done any changes in settings or any other parameters when this problem has came out i was only doing some javascript text and tried deleting it but nothing changes same problem persists knowing that if i try live server with or another server with the html js css... without django in the same path it logs everything and it works fine but in django it doesn't i've tried the cmd instead of shell it the same problem i the problem is in django's local server don't know how. Literally running a console.log() in the console itself returns undefined in the console, but not the console log itself as shown below. i'm using vs code, chrome, python 3.6 django last version i'm in this problem from yesterday i tried everything i wish to … -
No module named 'django_heroku'
I am trying to migrate my database to Heroku through: heroku run python3 manage.py migrate and I get this error: Traceback (most recent call last): `File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 63, in _run_checks issues = run_checks(tags=[Tags.database]) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/utils.py", line 222, in all return [self[alias] for alias in self] File "/app/.heroku/python/lib/python3.8/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/learning_log/settings.py", line 134, in <module> … -
Preventing a hyperlink showing using CSS
A widget I use has this line of code as default. <a href="javascript:map_Location.clearFeatures()">Delete all Features</a> I don't want that hyperlink to be visible. I tried using - id_Location_span_map a:link { color: white; } But then I discovered there was other hyperlinks attached to the widget so I tried the following but none of them worked. #id_Location_span_map href="javascript:map_Location.clearFeatures()" { color: white; } /*#id_Location_span_map a:href="javascript:map_Location.clearFeatures()" { color: white; } #id_Location_span_map a:link href="javascript:map_Location.clearFeatures()" { color: white; } Does anyone have any other suggestions? Update Instead of {color:white} I will use {display:none}. But I still haven't figured out how to just apply the changes when the hyperlink is linking to a specific page. Update 2 This code solves my problem. Thank you to Gubasek Duzy and https://css-tricks.com/almanac/selectors/a/attribute/ for the help. a[href="javascript:map_Location.clearFeatures()"] { display: none; } -
How do I migrate data from the parent model/table to the child model/table?
So my child model inherits the parent model. After I run migrate, the child has a parent_ptr_id column referencing the parent. Great! But the child table remains empty while the parent table has data. How do I migrate the data from the parent table to the child table? I want to specify which columns to migrate from the parent table and which types of records to NOT migrate. This should be done automatically every time the parent table changes. Using Django v.3.0 -
Django trying to add an existing field when making a model managed
How can I stop Django 2.2.4 from trying to create a database column that already exists when making a model managed? I have 2 models, ticket and message, which were connected to tables in a third-party database so the models were created with managed=False. I'm moving away from the third-party tool. The ticket model was change to managed=True a while ago by somebody else, and now I'm trying to do the same with the message model. These are the relevant parts of the model: from django.db import models class Message(models.Model): mid = models.BigAutoField(db_column='MID', primary_key=True) ticket = models.ForeignKey('Ticket', on_delete=models.CASCADE, db_column='TID') author = models.CharField(db_column='AUTHOR', max_length=32) date = models.DateTimeField(db_column='DATE') internal = models.CharField(db_column='INTERNAL', max_length=1) isoper = models.CharField(db_column='ISOPER', max_length=1) headers = models.TextField(db_column='HEADERS') msg = models.TextField(db_column='MSG') class Meta: # managed = False db_table = 'messages' permissions = ( ("can_change_own_worked_time", "Can change own worked time"), ("can_change_own_recently_worked_time", "Can change own recently worked time"), ("can_change_subordinate_worked_time", "Can change subordinate worked time"), ) This are the migrations that get generated by commenting out managed=False: # Generated by Django 2.2.4 on 2020-06-18 20:56 (0017_auto_20200618_1656) from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('troubleticket', '0016_auto_20200511_1644'), ] operations = [ migrations.AlterModelOptions( name='message', options={'permissions': (('can_change_own_worked_time', 'Can change own worked time'), ('can_change_own_recently_worked_time', 'Can change own … -
alternatives to gmail usage for django password reset
settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_USE_TLS = True EMAIL_HOST_USER = "myemail" EMAIL_HOST_PASSWORD = "mypassword" i am trying to implement django password reset, but i need to create app password in gmail which requires two-step verification which is not allowed by google in my country Nigeria what alternative do i have so i can implement django password reset? -
How to edit a BoleanField in Django
please i need your help been stuck like this for days,here is my problem, i have a profile page of a user that contain a BooleanField and a Button if the user would like to subscribe or not, i am wanting to design it this way, in which their will only be a one click button that will show Subscribe and once clicked you you get redirected to the payment page then you choose your plan and make payment,then in the user info it will show a dead btn of Subscribed and underneath would be the code generated for a specific task,just help me share even if its a link to a tutorial to follow as a starting point,here is my code and the picture model.py class Patient(models.Model): STATE_CHOICES=( (True, u'Yes'), (False, u'No'), ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=True, choices=STATE_CHOICES) html <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 h4 text-center center">Your Email</legend> <legend class=" mb-4 h3 center text-center">{{ user.email }}</legend> </fieldset> <div class="form-group text-center center"> <button class="btn btn-outline-info" type="submit">{{ user.patient.subscribe }} </button> </div> </form> -
Django + DRF and Domain Driven Design
Recently, I meet such concept as Domain Driven Design and opinion, that usual DRF application (CRUD enpoints) are not satisfied DDD consepts. Does really django-rest-framework uses different patterns and can't be implemented with DDD? Some example (if I understand everything right) There is a table called Items. There are two cases - 1) api should return all items with is_published=true 2) api should return all items DRF - one endpoint with filtering 1) /items/?is_published=1 2) /items/ DDD - two endpoints, because there is two different domain objects 1) /published_items/ 2) /all_items/ -
Sum of model methods django
I'm trying to get the sum of some of my model methods and display them on a results page. I'm not sure how possible it is to get this done in my views.py. I get the following error when I run the server. Unsupported operand type(s) for + 'method' and 'method' models.py class Organization(ModelFieldRequiredMixin, models.Model): exist = models.BooleanField(help_text='Does organization exist physically?') blacklist = models.BooleanField(help_text='Has organization previously been blacklisted by a national authority, funder or fund manager?') grant_amount = MoneyField(decimal_places=2, max_digits=12, help_text='Total amount of grant(s) from largest donor to organization ') estimatedAnnual_budget = models.IntegerField(help_text='Estimated annual budget of the organization (inclusive of the largest funder), in US Dollars') class Scores(ModelFieldRequiredMixin, models.Model): organization = models.ForeignKey(Organization,on_delete=models.CASCADE) score = models.DecimalField(max_digits=9, decimal_places=2) # Section1 - ORGANIZATIONAL BACKGROUND def exist_score(self): if self.organization.exist == True: self.score=0.1 return self.score #The higher score else: score=0.1 return self.score #The lower score def accessibility_score(self): if self.organization.accessibility == True: self.score=5 return self.score else: score=0 return self.score def blacklist_score(self): if self.organization.blacklist == True: self.score=0 return self.score else: score=0 return self.score # Section2 - PREVIOUS GRANTS & PERFORMANCE def grant_amount_score(self): if self.organization.grant_amount >= 2000000: self.score=3.5 return self.score else: score=0 return self.score def estimatedAnnual_budget_score(self): if self.organization.estimatedAnnual_budget == True: self.score=2 return self.score else: score=0.1 return self.score Views.py … -
How does repl.it render Pygame? [closed]
I have seen the website repl.it render pygame in the browser and am wondering how they are able to do it. I am making a website using Django and would like to use something similar to what they are doing since it works very well and has low latency and high frame rates. -
error with installing virtualenv with python 3
ive updated to python3 and downloaded virtualenv using: sudo /usr/bin/easy_install virtualenv when i go to start the virtualenv i got the following error message : virtualenv project1 Traceback (most recent call last): File "/usr/local/bin/virtualenv", line 6, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module> @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 585, in _build_master return cls._build_from_requirements(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 598, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'zipp>=0.4' distribution was not found and is required by importlib-resources i looked around and realised the that 'zipp' had not been installed so i installed that also. when i went to run the virtualenv again i got the same error message again as above. and for some reason it keeps referencing python 2.7 even though ive upgraded to python3. -
Django check if url parameter was provided
i have a url : path('admin-panel/users/update/<id>/',user_update_for_admin, name="user_update_for_admin"), and the view for that url: def user_update_for_admin(request,id): user = get_object_or_404(UsersForAdmin, id=id) everything works fine but if an id is not provided in the url for exemple if i type : admin-panel/users/update/ i got this error: Field 'id' expected a number but got 'update'. how do i fix that ? -
How do I create custom users permission
I am trying to create a custom user permission. When user A block user B, when user B login and try to access user A profile through url (localhost:8000/user_a_profile/) it should show 404 Forbidden, but user B can be able to access other users. I have found out the way to do this is to create a decorator.py, i have done that and i have a problem. I have created a decorator.py, but when user A block user B, when user B login and try to access user A profile through url, the reverse is the case. User B was able to access user A profile (which is wrong) but when i try to access other users profile, i get 404 Forbidden. How do i set only user A to show 404 Forbidden when user A already blocked user B, and user B can access other users. But it seems my code is working in u-turn. Model class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) blocked_users = models.ManyToManyField('Profile', related_name="blocked_by",blank=True) class Blocked(models.Model): user_is_blocking = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_is_blocking', null=True, blank=True) user_is_blocked = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_is_blocked', null=True, blank=True) Decorator.py from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from pixmate.models import Profile, Post #Blocked users can not … -
SyntaxError: expected expression, got '&' (Django)
I have an analytic dashboard with Django as a backend. After analyzing data in Python I'm sending a dictionary with name and salience. var things_mentioned = {{entity.name}}; var things_salience = {{entity.salience}}; which produces an error: SyntaxError: expected expression, got '&' Below code does not produce any error and works perfectly: var things_mentioned = ['noodles', 'food', 'Chinese', 'flavor', 'umami flavor']; var things_salience = {{entity.salience}}; when I try to view {{entity.name}} value in plain HTML page it exactly displays this ['noodles', 'food', 'Chinese', 'flavor', 'umami flavor']. Also, there is not a single '&' in my entire program. -
No scroll bars in windows 10
I have a django app, and for certain users running Windows 10 they are unable to scroll pages in my app, neither horizontally nor vertically. It does not happen for users on Mac or Linux, and it does not happen to all users on Windows. For the users it does happen to, it occurs on all browsers. There are no scroll bars and they cannot scroll with the mouse wheel, the page down keys or the arrow keys. I did see this: https://www.ghacks.net/2018/07/16/disable-windows-10-hiding-scroll-bars/ and I had them check and hide scroll bars was on, but setting that to off did not resolve the issue. Also, for users who are not having this problem, hide scroll bars was on. Anyone ever seen this and know what could be causing it? -
Django 2.2 | Cookie with name "sessionid" is not create while anonymous user open site
I'm using PostgreSQL with Django 2.2. I'm trying to set cart id on the session but every time session gets none value while the user login or not. Even if I tried to open website in incognito mode sessionid cookie is not create with anonymous users. Because of that every time it create a new cart where user is login or not. views.py def index(request): context = {} res = getCart(request) context.update(res) return render(request, 'index.html', context) def getCart(request): lines = [] order = {} cartQuantity = 0 if request.session.get('cart'): cart = Cart.objects.get(pk=request.session.get('cart'),state='draft') lines = cart.cartlines_set.all() cartQuantity = int(cart.getQuantity) if not order: cart = Cart.objects.create(customer_id=request.user, state='draft') request.session['cart'] = cart.id lines = cart.cartlines_set.all() cartQuantity = int(cart.getQuantity) return {'lines': lines, 'cart':cart, 'cartQuantity': cartQuantity} ** url.py ** urlpatterns = [ path('', shop, name="shop"), ] settings.py SESSION_SAVE_EVERY_REQUEST = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom moduels 'cart.apps.cartConfig', ] -
What kind of Queries are considered NoneType in django?
I made a query to save data. a = balance(name='MyName', income=50) a.save() Then I got, AttributeError: 'NoneType' object has no attribute 'save' My code works fine without any problem. My question is, why the object is considered NoneType ? The Model is like: class balance(models.Model): name = models.CharField(max_length=100) income = models.IntegerField() date = models.DateTimeField(null=True, blank=True) -
Cannot access my Django page hosted on AWS EC2 instance
I cannot access my Django app on an EC2 instance in my browser by typing its public DNS name with port number: ec2-public-dns-of-this-instance.compute-1.amazonaws.com:8000 I'm using the same Security Group that my other EC2 instance is using which is working just fine (my other Django app hosted on this instance works perfectly fine), with HTTP/TCP open on 0.0.0.0/0 on port 8000 I started my Django project this way: ./manage.py runserver 0.0.0.0:8000 I've added hosts into my ALLOWED_HOSTS file which has these now: ALLOWED_HOSTS = ['*', '127.0.0.1', 'ec2-public-dns-of-this-instance.compute-1.amazonaws.com', '0.0.0.0', 'localhost'] I was able to curl localhost:8000 which returned me very valid responses when I'm ssh'ed into this instance. Any ideas how to fix this would be greatly appreciated! -
How to send data from index.html to views.py in django
I have a table contains a list of fifty companies(items) on a side there is a button. I want to send the name of the company from the table is which user is clicked. index.html <table class="table table-striped table-dark" cellspacing="0"> <thead class="bg-info"> <tr> <th>Company's Symbol</th> <th>Current Price</th> <th>View Current chart</th> <th>Action</th> </tr> </thead> <tbody> {% for a,b in stocks %} <tr> <th scope="row" class="comp_name">{{ a }}</th> <td>{{ b }}</td> <td> <input type="submit" class="btn graph-btn" name="_graph" value="View Graph"> </td> <td> <input type="submit" class="btn predict-btn" name="_predict" value="Predict Closing Price"> </td> </tr> {% endfor %} </tbody> </table> there is two button for different URL. Like when user liked on .graph-btn it will goes to different URL. -
contenttypes framework in Django
I am reading Django documentation (https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/#module-django.contrib.contenttypes). I did not understand content type app, the Django docs describe it as below Django includes a contenttypes application that can track all of the models installed in your Django-powered project, providing a high-level, generic interface for working with your models. Can someone explain this from beginner perspective ? I have experience in developing websites in Django but never touched in this app. -
Is there a way to copy a postgres database from elephantsql to heroku?
I have a django project that I was initially running on pythonanywhere using a postgres database. However, pythonanywhere doesn't support ASGI, so I am migrating the project over to heroku. Since heroku either much prefers or mandates use of its own postgres functionality, I need to migrate the data from elephantsql. However, I'm really coming up short on how... I tried running pg_dumpall but it didn't seem to want to work and/or the file disappeared into the ether. I'm at a loss for how to make this migration... If anyone could help, I'd appreciate it so much. T-T -
Alternative for Aldryn-forms (Django-CMS)
Divio announced an end of support for Aldryn-forms at the end of September 2020. (http://support.divio.com/en/articles/3849075-essential-knowledge-django-addons-list). I'm looking for add-on alternatives for Aldryn-forms that can work with the latest versions of Django, Django-CMS and Phyton. On the marketplace website I only could find one package but its' last update was in 2015. Does anyone knows a good package or has some information to implement forms which can be edited by content editors in the frontend website. Thanks for any help. Regards, Carla -
Ordering stopped working after implementing slug
as I mentioned in title: Ordering was working before implementing slug like below. Can anyone see whats wrong? Models.py class Post(models.Model): title = models.CharField(null=False, blank=False, max_length=200) content = models.TextField(null=False, blank=False, max_length=1000) date_of_create = models.DateField(null=False, blank=False, auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True, blank=True) def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=Post) Views.py class PostListView(ListView): model = Post template_name = 'blog/homepage.html' context_object_name = 'posts' ordering = ['-date_of_create'] -
Question about Database architecture and Django models
I am working on a project about cards. I have two questions: 1) Question about database architecture: I designed the database architecture, is it correct? 2) Questions about models in Django: a) I want 4 sections to be created when I create a new set (sections have different sizes). b) When creating a new card, you could choose only those categories that belong to a certain set. -
Module not found for django celery on heroku instance
I've set up celery with django with a redis broker. It all has worked great locally, but when I log my heroku instance after deploying I am getting this error: ModuleNotFoundError: No module named 'app' Here's my celery.py which is in the root of my project folder project/project/celery.py: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AutomatedInterview.settings") app = Celery("AutomatedInterview") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() My init.py in the same directory: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) My Procfile: release: python manage.py migrate web: gunicorn AutomatedInterview.wsgi worker: celery worker -A AutomatedInterview -l info The full logs after running command heroku logs -t -p worker 2020-06-18T19:11:38.697329+00:00 app[worker.1]: Traceback (most recent call last): 2020-06-18T19:11:38.697361+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ 2020-06-18T19:11:38.697485+00:00 app[worker.1]: return obj.__dict__[self.__name__] 2020-06-18T19:11:38.697488+00:00 app[worker.1]: KeyError: 'data' 2020-06-18T19:11:38.697509+00:00 app[worker.1]: 2020-06-18T19:11:38.697509+00:00 app[worker.1]: During handling of the above exception, another exception occurred: 2020-06-18T19:11:38.697510+00:00 app[worker.1]: 2020-06-18T19:11:38.697510+00:00 app[worker.1]: Traceback (most recent call last): 2020-06-18T19:11:38.697513+00:00 app[worker.1]: File "/app/.heroku/python/bin/celery", line 11, in <module> 2020-06-18T19:11:38.697621+00:00 app[worker.1]: sys.exit(main()) 2020-06-18T19:11:38.697624+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/__main__.py", line 16, in main 2020-06-18T19:11:38.697747+00:00 app[worker.1]: _main() 2020-06-18T19:11:38.697749+00:00 app[worker.1]: File …