Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Recommendation System Web App using Flask or Django
I want to create create a movie recommendation web app using python with flask or django. Web app should first ask the user to select 3 movies and then recommend him 5 movies related to his input. I have limited knowledge about flask and django. How can I proceed ? -
fcm push notification registeration id not registered
I'm using fcm api in push notification, my backend is django rest framework. fcm api: "https://fcm.googleapis.com/fcm/send" most of the time push notifications failed and the error is "Not Registered". I looked into it and it might be different cases as mentioned in docs I made sure that registration id is updated whenever firebase refreshed it. but it also give me that error. But the weird part is, i take a test user, when i sent an push notification it succeeded, and after 2 hours it gave me "Not Registered", and the user not uninstalled or reinstalled the app. Any Explanation ?! -
Stop Django Invalid HTTP_HOST header errors at the Elastic Load Balancer level
I am running a Django app on Elastic Container Service behind Elastic Load Balancer. I am seeing a ton of Invalid HTTP_HOST header errors at the Django App level that look like: Invalid HTTP_HOST header: '34.237.89.13'. You may need to add '34.237.89.13' to ALLOWED_HOSTS. How do I block these invalid requests at the load balancer level in Elastic Load Balancer? -
Apache throws ERROR 500: Internal Server Error when GET from localhost/internal network
I have a production server with apache and django installed using mod_wsgi. The django application has a REST API that serves some info when a GET request is sent. This has always worked fine on the develop server, were we ran django using manage.py in a screen. Now we created a production server with apache running django but this API returns Error 500 when running wget from localhost or other machines in the same network (using 192.168.X.X IP). Here's the output from wget: ~$ wget localhost:80/someinfo --2020-04-02 16:26:59-- http://localhost/someinfo Resolving localhost (localhost)... 127.0.0.1 Connecting to localhost (localhost)|127.0.0.1|:80... connected. HTTP request sent, awaiting response... 500 Internal Server Error 2020-04-02 16:26:59 ERROR 500: Internal Server Error. It seems that the connection succeeds, so I guess it's not an apache problem. The error comes from the API response. The error in apache error.log looks like this: 127.0.0.1 - - [02/Apr/2020:14:24:36 +0000] "GET /someinfo HTTP/1.1" 500 799 "-" "Wget/1.19.4 (linux-gnu)" question: what is the number after 500? Sometimes is 799 and other times is 803. But if the request is done using the public IP of the server from outside (i.e. from the browser) the API works fine and I see the correct information. … -
Start Django project and open Visual Studio Code using batch file
I want to create a batch file where I can start a Django project and open visual studio code at the same time while creating a new file inside the terminal command (Window 10). This is how it goes when I want to start a Django project: Command: >C:\Users\bvsia\Documents\Programming\Python\Django >django-admin startproject mysite >cd mysite >python manage.py startapp main >python manage.py runserver then I open Visual Studio Code from the terminal command typing code . on the file that was created. Then I will have my Django project to work on. I want the one click file for all what I did step by step. This is what I got so far in batch file. @echo off start cmd.exe /C "django-admin startproject mysite && cd mysite && python manage.py startapp main && python manage.py runserver && cd C:\Users\bvsia\Documents\Programming\Python\Django" start cmd.exe /C "C:\Users\bvsia\Documents\Programming\Python\Django && code ." start http://127.0.0.1:8000/ I have tried several ways to execute this but nothing worked. I hope you can see what I am trying to do here and help me with this. Thanks -
Fill value on hidden django input field
I have a model form and I'm manually entering the fields into my template. Model form: class ProductEntryForm(forms.ModelForm): class Meta: model = Product fields = [ 'image', 'product_name', 'price', 'options', ] Manually rendering fields in Template: <form method="POST" enctype="multipart/form-data"> <h2>New Product</h2> {% csrf_token %} {{ form.non_field_errors }} <p> <label for="">Image</label> {{ form.image.errors }} {{ form.image }} </p> <p> <label for="">Product name</label> {{ form.product_name.errors }} {{ form.product_name }} </p> <p> <label for="">Description</label> {{ form.description.errors }} {{ form.description }} </p> ... The options field of the form is hidden in the template because the user doesn't fill this field directly. They fill it from a different input field. <form method="POST" enctype="multipart/form-data"> ... <p style="display: none"> {{ form.options }} </p> <input type="text" name="visible_option_input" :value="[[make_this_value_of_{{form.options}}_when_submitted]]"> ... </form> I want the value of "visible_option_input" to be the value of {{ form.options }} when submitted -
Django model TypeError at /writeReview/1 __str__ returned non-string (type int)
I am facing issues related to the above error (also shown in picture 4). Can someone help me out here? I am seeing this error while trying to submit the form which saves the data to the ReviewTable as shown in the picture 2. enter image description here enter image description here enter image description here enter image description here -
How can I upload and edit images to a post? - Django
I am building a blog app using Django and I would like the ability for users to add images to each post in a template. I have already added the image upload and everything works fine. The problem, however, is that the default Django image form (upload, edit and delete) doesn't look very pleasing and I am having too much difficulty customizing this. If anyone knows of a cabable and good looking solution or integration/service that works, please let me know. -
OSError: [Errno 30] Read-only file system when unzipping files in Django
I'm trying to implement unzipping files function to my Django app. Basically users will upload data and some process will start with Celery. But I get OSError: [Errno 30] Read-only file system: '/media' error (from settings.MEDIA_URL, probably). At the moment, I'm developing the app on my Mac. How can I fix this? Unzipping Code @app.task(bind=True) def extract_zip(self, returns_from_first, user_id): user = Profile.objects.get(user_id=user_id) with zipfile.ZipFile(user.file, 'r') as zip_ref: zip_ref.extractall(str(settings.MEDIA_URL) + str(user.file)) Thanks! -
protecting a json endpoint in django as part of an ajax call
I have a conceptual question. I am currently using an ajax call to send data from my database to the django template to populate a chart on the page urls.py urlpatterns = [ path('chartdata1/', tracker.get_chart_data_json1, name="global_trend_chart"), ] views.py def get_chart_data_json1(request): data = {} cd = ChartData.get_global_trend() data['chart_data'] = cd return HttpResponse(json.dumps(data, default=str), content_type='application/json') HTML / JAVASCRIPT var chartDataUrl = "{% url 'global_trend_chart' %}" $.getJSON(chartDataUrl, function(data) { chartOptions.xAxis.categories = data['chart_data']['date']; chartOptions.series[0].data = data['chart_data']['confirmedcases']; var chart = new Highcharts.Chart(chartOptions); }) While this is working fine, I don’t want people to be able to access the url directly (i.e. I don’t want them to be able to access the json data by going to myurl.com/chartdata1). I just want this view/data to be accessible by my django template to populate the charts there. I also don’t require users to login to see the main page so don’t want to create a @login_required restriction to the view Is there any way for me to protect the myurl.com/chartdata1 endpoint so it’s only consumable by the charts? Thanks -
TemplateDoesNotExist even though the file exists
I get this error even though the file exists - why? -
Why and how does Django send HTTP 200OK for example.com to AWS Scanner
I'm running Django 3.0 on Ubuntu in AWS cloud and in my Nginx logs I see the following: 44.224.22.196 - - [02/Apr/2020:18:49:13 +0530] "GET http://example.com/ HTTP/1.1" **200** 396 "-" "AWS Security Scanner" example.com is their in my Django sites but I haven't put it in allowed hosts (in settings.py). Neither example.com exists in my Nginx's server block, then why does Nginx send HTTP 200 to AWS Scanner? -
UpdateView for ModelForm with custom field form
I have two model Model A: fieldA1 fieldA2 Model B: fieldA = ForeignKey(A) fieldB1 fieldB2 I need to create ModelFormB but i need also insert value to Model B via form. So i create ModelForm B: fielda1 = form.CharField() fielda2 = form.CharField() class Meta: model = ModelB field = [fielda1, fielda2, fieldb1, fieldb2] Mu UpdateView code: class ModelBUpdateView(LoginRequiredMixin, UpdateView): model = ModelB form_class = ModelFormB template_name = "....." success_url = reverse_lazy('...') The problem is, in template i can see only ModelB(fieldb1,fieldb2) instance initial value but fielda1 and fielda2 are completely blank. How i send the value to fielda1 and fielda2 during updateview? -
django.setup() in every python test file needed?
I execute one particular test via PyCharm (ctrl-shift-F10). I get this error: Testing started at 18:12 ... /home/guettli/simple21env/bin/python /snap/pycharm-community/188/plugins/python-ce/helpers/pycharm/_jb_unittest_runner.py --target simple21.tests.TermTests.test_str_of_sub_term Launching unittests with arguments python -m unittest simple21.tests.TermTests.test_str_of_sub_term in /home/guettli/simple21env/src/simple21tree Traceback (most recent call last): File "/snap/pycharm-community/188/plugins/python-ce/helpers/pycharm/_jb_unittest_runner.py", line 35, in <module> main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING) File "/usr/lib/python3.6/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/lib/python3.6/unittest/main.py", line 141, in parseArgs self.createTests() File "/usr/lib/python3.6/unittest/main.py", line 148, in createTests self.module) File "/usr/lib/python3.6/unittest/loader.py", line 219, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python3.6/unittest/loader.py", line 219, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) File "/home/guettli/simple21env/src/simple21tree/simple21/tests.py", line 7, in <module> from . import views File "/home/guettli/simple21env/src/simple21tree/simple21/views.py", line 5, in <module> from simple21.models import Term, SearchLog, GlobalConfig File "/home/guettli/simple21env/src/simple21tree/simple21/models.py", line 1, in <module> from django.contrib.auth.models import User File "/home/guettli/simple21env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/guettli/simple21env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/guettli/simple21env/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/home/guettli/simple21env/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/home/guettli/simple21env/lib/python3.6/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Process finished with exit code 1 Empty suite I guess I need … -
How can I resolve or fix Django cyclic model field dependencies?
I've a database design corresponding to the following pseudo-code: class AModel(models.Model): c_model_instances = models.OneToOne(CModel, ...) # "is a" relationship class BModel(models.Model): a_model_instances = models.ManyToMany(AModel, ...) # "contains" relationship class CModel(models.Model): b_model_instances = models.ManyToMany(BModel, ...) # "contains" relationship Belief it or not... this design makes total sense from a business perspective :) However of course I get an error NameError: name 'CModel' is not defined when I try to migrate the database. How can I resolve or fix (via different design) the issue? -
Django - not generating an automatic reverse relation
I want to enable my users to add bookmarks to there account but sadly each time I try to add a new bookmark I get the following error: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. models.py bookmarkable_models = models.Q(app_label='App', model='model-a') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_models, on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=50, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) class Meta: verbose_name = "Bookmark" verbose_name_plural = "Bookmark(s)" ordering = ['-date_added'] -
Django: Multi-Model Inheritance
I have a custom User-Model Inheriting from AbstractUser. Everything worked fine, but then I tried to inherit from another Model aswell, allowing Soft-Deletion: from django.db import models from django.db.models.query import QuerySet from django.utils import timezone class SoftDeletionQuerySet(QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update(deleted_at=timezone.now()) def revive(self): return super(SoftDeletionQuerySet, self).update(deleted_at=None) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete() def alive(self): return self.filter(deleted_at=None) def dead(self): return self.exclude(deleted_at=None) class SoftDeletionManager(models.Manager): use_for_related_fields = True def __init__(self, *args, **kwargs): self.status = kwargs.pop("status", "all") super(SoftDeletionManager, self).__init__(*args, **kwargs) def alive(self): return SoftDeletionQuerySet(self.model).filter(deleted_at=None) def dead(self): return SoftDeletionQuerySet(self.model).exclude(deleted_at=None) def get_queryset(self): if self.status == "alive": print("TEST") return SoftDeletionQuerySet(self.model).filter(deleted_at=None) elif self.status == "dead": return SoftDeletionQuerySet(self.model).exclude(deleted_at=None) else: return SoftDeletionQuerySet(self.model) def hard_delete(self): return self.get_queryset().hard_delete() class SoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager(status="alive") dead_objects = SoftDeletionManager(status="dead") all_objects = SoftDeletionManager() class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def revive(self): self.deleted_at = None self.save() def hard_delete(self): super(SoftDeletionModel, self).delete() The Model: class User(AbstractUser, SoftDeletionModel): email = models.EmailField(unique=True) email_confir med = models.BooleanField(default=False) The View: User.dead_objects.filter(deleted_at_`_gte=(now - timezone.timedelta(hours=US_EXP_DATE))).hard_delete()` But now, from a View, I cant access the hard-delete function from a given User-Queryset (see The View). It gives the following Error: AttributeError: 'QuerySet' object has no attribute 'hard_delete' I guess the BaseUser is somehow shadowing it, since the Soft-Delete-Model … -
django fixtures with default value in
Can I use default value in django fixtures? I want to change primary_key to uuid_key class hogeModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=256) [ { "model": "app.hogeModel", "pk": "", "fields": { "name": "hogehoge" } } ] It's hard to make uuid every time. Can't I fixtures without making a primary_key? Waiting for your answer!! -
Is the server running on host "localhost" Djanog and PostgreSQL Connection?
I am trying to run migrate command in Django on MAC. python3 manage.py migrate But, I stuck in an error. The error says : Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I am using PgAdmin4 and it is running on the web. I downloaded the postgresql and pgadmin4 and installed it. 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dj_learning', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432', } -
Python Django login URLS and Views - Security Approach
I have this login practice in my app, it's up and running but my concerns goes to securing this login approach. My App URLS: urlpatterns = [ path('', views.index, name='index'), path('accounts/login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('dashboard/', views.dashboard, name='dashboard'), ] My App Views: def index(request): if not request.user: return redirect(login_view) return redirect(dashboard) def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) login(request, user) if request.GET.get('next'): return redirect(request.GET.get('next')) return redirect(dashboard) context = { 'form': form, } return render(request, 'index.html', context) def logout_view(request): logout(request) return redirect(index) in my views.py index(request), I believe it may be vulnerable because if someone could make it and change the request and set a fake user it may go through ?. I know security concepts but not expert on Django appliance approaches. Is there a better way to do this or I don't have to change this and it's secured practice already? -
django-rules: trouble making it work as expected in templates
Disclaimer: I'm new to django and django-rules. I have defined my model. The Model has 2 foreign keys to the user table. Creator and supervisor. Instances should be changeable/updated by staff, creator or supervisor. I have defined predicates for is_creator and is_supervisor and made a rule: @rules.predicate def is_creator(user, mymodel): return mymodel.creator == user @rules.predicate def is_supervisor(user, mymodel): return mymodel.supervisor == user can_edit = is_supervisor | is_creator | rules.is_staff And in the models meta class I added: rules_permissions = { 'change': can_edit } In my view I then want to show an edit button that links to edit form based on these permissions. {% block content %} {% has_perm 'mymodel.change_mymodel' user instance as can_edit %} {% if can_edit %} <button type="button" class="btn btn-warning"><h6>Edit</h6></button> {% endif %} {% endblock %} When I log in as superuser, the button is displayed as expected. When I user a test user that should be able to edit a specific instance, the button is not displayed at all. So there are certain checks made but not as expected. I have a second similar functionality for the index page. Showing only actions the users has the privilege for. Again, the superuser sees it all but the … -
Celery revoked task still executes
I am trying to cancel/revoke a task planned with apply_async. Once I revoke it using the revoke function (revoke(celery_task_id)) celery shows me that the task has been flagged as revoked [2020-04-02 17:37:06,131: INFO/MainProcess] Tasks flagged as revoked: 5bca7db0-8d35-43f0-a900-6c8d94787265 However the task only gets discarded if the eta time has passed. If I restart my celery worker before that time the task is, strangely enough, not seen as revoked anymore and still executes at the specified eta time. When I restart it, celery says that it received a task, which is the task I revoked. [2020-04-02 17:39:47,077: INFO/MainProcess] Received task: testproject.taskapp.celery_tasks.celery_test[5bca7db0-8d35-43f0-a900-6c8d94787265] eta:[2020-04-02 17:42:56.206297+02:00] For the queue I use redis 2.10.5 the celery version is 3.1.25 does anyone know what is going wrong here and how I can get revoked tasks to not be executed? -
How to display an uploaded image manipulated with PIL without saving to file Django
I am pulling a image from a database to be used as a background and placing a user uploaded image on top of the background using PIL. I would like to display this image to the html page after the transformation is complete without saving to the file system. I have looked at many similar questions, but I am doing something different here. I have tried to craft some code based on the other answers, but I can't get the image to display on the screen after the user submits their photo. How can I get this to work? Here is my code: from django.core.files.storage import FileSystemStorage from PIL import Image from io import BytesIO import base64 import io from .models import Samplecards def imageUpload(request): if request.method == 'POST': selection = request.POST['selection'] sample = getImage() theImage = io.BytesIO(sample.image) print("DONE") uploaded_image = request.FILES['img'] foreground = Image.open(uploaded_image).convert("RGBA") background = Image.open(theImage).convert("RGBA") background.paste(foreground, (440, 190), foreground) buffered = BytesIO() background.save(buffered, format="png") b64_img = base64.b64encode(buffered.getvalue()) return render(request, 'uploadpage.html', {"image": b64_img}) def getImage(): img = Samplecards.objects.get(image_id=1) return img In my html file, I try to display the image like this: <img src="data:image/png;base64,{{image}}"> -
CSS not working while in deployment in django
This is my file structure Project asgi.py . . . main admin.py . . static css files templates users admin.py . . static files static (created after collectstatic) db.sqlite3 manage.py Static url and root STATIC_URL = "/STATIC/" STATIC_ROOT = OS.PATH.JOIN(BASE_DIR, 'static') I did collectstatic and it works properly all files are coped to /static/ folder now this all works fine with running with debug = true but when I set debug false none of the css loads. example of a css in html <link rel="stylesheet" href="{% static 'main/style.css' %}"> this is happening only with any templates inside "main" app, for "users" app all the css is loading properly -
Django Apache 2.4.18 Ubuntu 403
I am trying to configure my django app with Apache 2.4.18.. I am using Django 3.0.5 and Python 3.8.2., on Ubunu 16.04. Everything works fine in runserver mode. Forbidden You don't have permission to access this resource. This is my apache config gile Listen 80 <VirtualHost *:80> ServerAdmin xxx@xxx.com ServerName servername.net DocumentRoot /srv Alias /static /srv/tacdb/mysite/static <Directory "srv/tacdb/mysite/static"> Require all granted </Directory> Alias /media /srv/tacdb/mysite/media <Directory "srv/tacdb/mysite/media"> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/portal_error.log CustomLog ${APACHE_LOG_DIR}/portal_access.log combined WSGIDaemonProcess mysite python-home=/srv/tacdb/virtualenvironment/project_1 python-path=/srv/tacdb WSGIProcessGroup mysite WSGIScriptAlias / /srv/tacdb/mysite/wsgi.py <Directory /srv/tacdb/mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> configtest is ok and server status is ok. root@test-tools:~/srv# systemctl status apache2.service ● apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Thu 2020-04-02 15:18:20 UTC; 5min ago Docs: man:systemd-sysv-generator(8) Process: 26327 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 25036 ExecReload=/etc/init.d/apache2 reload (code=exited, status=0/SUCCESS) Process: 26356 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) CGroup: /system.slice/apache2.service ├─26372 /usr/sbin/apache2 -k start ├─26375 /usr/sbin/apache2 -k start ├─26376 /usr/sbin/apache2 -k start └─26377 /usr/sbin/apache2 -k start Apr 02 15:18:19 test-tools systemd[1]: Stopped LSB: Apache2 web server. Apr 02 15:18:19 test-tools systemd[1]: Starting LSB: Apache2 web server... Apr 02 15:18:19 test-tools apache2[26356]: * Starting Apache …