Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django HTML for loop with filter
In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help! Model: class Question(models.Model): question = models.CharField(max_length=240) mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE) type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE) categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1) order = models.IntegerField(default=1) def __str__(self): return self.question class Question_Option(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1) option = models.CharField(max_length=240) correct = models.BooleanField() order = models.IntegerField(default=1) View: class Questions(LoginRequiredMixin, FormView): template_name = "questions.tmpl" def get(self, request, pk): context = { 'pk': pk, 'section': Mission_Section.objects.get(pk = pk ), 'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'), 'questions': Question.objects.filter(mission_section__pk = pk ), 'question_types' : Type_Question.objects.all(), 'questions_categories': Categories_Question.objects.all()} return render(self.request, self.template_name, context) HTML <input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required> <h1>{{ section.name }}</h1> <div id="contentDiv"> <ol> {% for question in questions %} <div name="question" class="form-group" id="question-{{question.id}}" > <form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'> <li><div class="input-group"> {% csrf_token %} {{ form.as_p }} <input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control"> <input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})"> </div> </form> <br> <!-- Options … -
JSON vs. Tables in PostgreSQL
I am trying to make a questionnaire and am considering 2 data structures: JSON: I could use JSON to store the different questions as follows: { "questions": [ { "question": "how old are you?", "type": "input_int", }, "question": "what is your name", "type": "input_string", }, { "question": "how are you today?", "type": "multiple_choice", "options": [ "good", "bad" ] }, ] } Or a table for each type of question: InputIntTable - Question - Order InputStringTable - Question - Order MultipleChoiceTable - Question - Options - Order I am using Django. Which way would be better both computationally, structurally, and cost wise to host. Which would take more storage? Thanks!! -
User model inherit AbstractBaseUser but still get AttributeError: 'User' object has no attribute 'check_passsword'?
I try to create custom model like this: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Create and saves a new User""" user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom User that support using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' and i add this line to my settings.py AUTH_USER_MODEL = 'core.User' Then i try to run this test class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test Creating a new user wint an email is successful""" email = 'test@example.com' password = 'Password123' user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_passsword(password)) It still say AttributeError: 'User' object has no attribute 'check_passsword' Then i check this question , it says that the solution was inherit AbstractBaseUser to User model. I have done that, but i still got an error, what should i do? -
How to implement something similar to list_display on generic list view?
I was trying to create a generic list template which would render all defined fields I wanted, just like the list_display from django admin.. I tried obj.values and obj.values_list, along with the specific fields, but these are not suitable when rendering choice fields since they bring a dict and a querysetdict and the get_foo_display is not available.. A managed=False also won't help since there is a filter of a field that can't be shown as well.. the .only() method also did not help because it does not 'cut' the fields from the obj.. I tried to copy the logic behind django admin list_display, but am I missing something in the generic list view? -
Dynamically Switch Database In Django App running inside docker container using environment variable
Problem: I want to switch the Django database after changing environment variables during run time Django app settings.py file PG_DB_USER = os.environ.get('PG_DB_USER', '') PG_DB_NAME = os.environ.get('PG_DB_NAME', '') PG_DB_PASS = os.environ.get('PG_DB_PASS', '') PG_DB_HOST = os.environ.get('PG_DB_HOST', '') PG_DB_PORT = os.environ.get('PG_DB_PORT', '') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': PG_DB_NAME, 'USER': PG_DB_USER, 'PASSWORD': PG_DB_PASS, 'HOST': PG_DB_HOST, 'PORT': PG_DB_PORT, } } There is a docker-compose.yml file where different services are listed along with the respective environment variable. After the successfully running of Docker containers, I am able to see all the environment variables inside containers using printenv or env command. Things I have Tried: I am trying to switch the environment variable using export PG_DB_NAME=**** command inside the container. But after running python manage.py shell and then import os and os.environ commands I am not able to see the changed environment variable PG_DB_NAME=****. Ps: All this command I will execute from a bash script to change the Django database during runtime. Thanks In advance. Any help would be much appreciated. -
SSL Certificate for WSGI application
I have a Django project that I deployed using only the WSGI server provided by Django(no webserver like apache, ngnix ...). The problem is that I want to upload an SSL certificate for the HTTPS version of the website. How can I do it please ? Thank you in advance for your answers. -
Deploying Django to Elastic Beanstalk, migrations failed
I'm trying to deploy a project I've been working on with django. In development, i've been using SQLite, in production i'm trying to use MySQL. Usually when I create the EB instance, everything runs fine, and the console says the status is OK. Upon trying to deploy (running eb deploy in ebcli), I get met with the following error 2020/06/18 15:59:50.357281 [INFO] Copying file /opt/elasticbeanstalk/config/private/rsyslog.conf to /etc/rsyslog.d/web.conf 2020/06/18 15:59:50.358945 [INFO] Running command /bin/sh -c systemctl restart rsyslog.service 2020/06/18 15:59:50.394223 [INFO] Executing instruction: PostBuildEbExtension 2020/06/18 15:59:50.394243 [INFO] No plugin in cfn metadata. 2020/06/18 15:59:50.394252 [INFO] Starting executing the config set Infra-EmbeddedPostBuild. 2020/06/18 15:59:50.394273 [INFO] Running command /bin/sh -c /opt/aws/bin/cfn-init -s arn:aws:cloudformation:eu-west-2:433403353655:stack/awseb-e-qamgvpp7ft-stack/3e6774d0-b17c-11ea-9476-0a5f6fd32d44 -r AWSEBAutoScalingGroup --region eu-west-2 --configsets Infra-EmbeddedPostBuild 2020/06/18 15:59:50.721919 [ERROR] Error occurred during build: Command 01_migrate failed 2020/06/18 15:59:50.721944 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: Container commands build failed. Please refer to /var/log/cfn-init.log for more details. 2020/06/18 15:59:50.721949 [INFO] Executing cleanup logic 2020/06/18 15:59:50.722079 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[]}]} 2020/06/18 15:59:50.722249 [INFO] Platform Engine finished execution on command: app-deploy The culprit seems to be my db migration command, which is as follows, in '.ebextensions', named 'db-migrate.config' container_commands: … -
How to Access values from dictionary in Javascript
I am try to fetch my item_id field from model.py in django in query set form that below <QuerySet [<Item: Shoulder Bag Boys Shoulder Bag (Yellow )>, <Item: Sweeter Cotton Sweeter>, <Item: Shirt Full Sleeves Shirt>, <Item: Jacket Jackson Jacket>, <Item: Yellow Shoes Leopard Shoes>, <Item: Bag Mini Cary Bag>, <Item: Coat Overcoat (Gray)>, <Item: TOWEL Pure Pineapple>, <Item: Coat Pure Pineapple>, <Item: TOWEL Pure Pineapple (White)>]> Here is my JS Code $.ajax({ type: 'GET', url: '/shopsorting/' + selected_value, // data: formData, encode: true }) .done(function(data) { items = JSON.parse(data) console.log(items) for (var item in items) { console.log(item['product_id']) }; But it print in console `(index):765 {items: "<QuerySet [<Item: TOWEL Pure Pineapple>, <Item: Ba…s Leopard Shoes>, <Item: Jacket Jackson Jacket>]>"} (index):767 undefined` -
Ajax sending data twice in views.py django
I have this form in index.html and two submit button on clicking on one button named .graph-btn I m using jquery and ajax to send data from form to Django. Code: index.html <form action="{% url 'Graph' %}" method="post"> {% csrf_token %} <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" formaction="{% url 'Graph' %}" name="_predict" value="Predict Closing Price"> </td> </tr> {% endfor %} </tbody> </table> </form> <script> $(".graph-btn").click(function(e) { var $row = $(this).closest("tr"); var $text = $row.find(".comp_name").text(); var name = $text; console.log(name); $.ajax({ type:'POST', dataType: "json", url:'{% url 'Graph' %}', data:{ 'text': name, 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success:function(json){ }, error : function(xhr,errmsg,err) { } }); }); </script> here I want to take data from th row named .comp_name and pass the data to views.py in Django. There is problem is Ajax. views.py def graph(request): if request.method == 'POST': print("testing....") print(request.body) print(request.POST.get('text')) name = request.POST.get('text') context = { 'name': name, } print(context) return render(request, 'StockPrediction/chart.html') else: return render(request, 'StockPrediction/greet.html') I m using Print statement …