Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Delete Function without return but a popup success message
i am trying to have a delete button in the list view that once clicked a popup success message shows and once confirmed the data get deleted and return to the same page. also note that my form and list are in the same page as i am trying to achieve a single page CRUD. appreciate any idea on how to approach this. -
Creating a Register Page by using DJANGO
How can I redirect in such a way that whenever a new USER account is created in my site in "REGISTER" page then after the creation of that account, the account should get logged in simultaneously into my website?? -
Difference on field based on other field value?
So this is my model: class InAndOut(models.Model): quantity = models.FloatField() date= models.DateField(null=True) type = models.CharField(max_length=12) id_product = models.ForeignKey(Products, on_delete=models.CASCADE) I want to query distinct values based on id_product and for each one the difference quantity based on type field("in" or "out"): So a real example would look like: quantity = 1500 type = In id_product = Gas quantity = 300 type = Out id_product = Gas query - Gas 1200 -
Heroku - I deleted migrations in my local enviro, pushed to staging no issues, and then pushed to product and SQL error
I ran into an issue with my migrations in local environment so I deleted migrations in my local enviro and reset database. I pushed these changes to staging on Heroku through git command with no issues my procfile contained the following command release: python manage.py migrate. No issues in staging environment. I then promote to production within Heroku admin portal and run into SQL errors in production environment. My application is built in Django / Python. Any idea how to resolve this conflict - I cannot delete the database as this is a production app? -
Django - Query user groups and load iframe source in a custom template based on user group
I usually develop in PHP but I took it upon myself to learn Django so please be patient with me, I have a long way to go... I am working on a project that simply does one thing for now, user can login and when the user is logged in the app will show an Iframe that streams some digital content that is created by another server I have which is stored in this model: class Show(models.Model): show = models.CharField(max_length = 200) description = models.TextField() mfg_date = models.DateTimeField(auto_now_add = True) iframe = models.CharField(max_length = 300, null=True) group = models.ForeignKey( Group, default='1', on_delete=models.CASCADE,) active = models.CharField(max_length = 1, choices = Active) def __str__(self): return self.show def show_desc(self): return self.description[:50] My views.py currently: from django.shortcuts import render from django.views.generic import TemplateView class StreamingView(TemplateView): template_name = 'stream/stream.html' And my template stream.html: {% extends '_base.html' %} {% load static %} {% block title %}[I would like to print "show" from my model here{% endblock title %} {% block content %} <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center"> <h2>[I would like to print "show" from my model here]</h2> <iframe width="560" height="315" src="[input "iframe" as the iframe src based on user group, and if user … -
How to do location wise product display in Django for eCommerce site
I want to know What is the best way for displaying products location wise in eCommerce website like used in these websites (https://www.walmart.com/) (https://grofers.com/) (https://www.bigbasket.com/) Please share any eCommerce opensource project of Django where this kind of location filtering is done -
NoReverseMatch at
I've got this issue trying to redirect after submitting a form: NoReverseMatch at /app_blog/blog/1/blog_update/ Reverse for 'blog_detail' with no arguments not found. 1 pattern(s) tried: ['app_blog/blog/(?P[0-9]+)/blog_detail/$'] views.py: from django.shortcuts import render, redirect # from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from django.contrib import messages from app_users.decorators import unauthenticated_user, allowed_users from .models import BlogPost from .forms import BlogUpdateForm @login_required(login_url='app_users:login') @allowed_users(allowed_roles=['admin', 'staff', 'users']) def blog(request): posts = BlogPost.objects.all() context = {'title': 'Blog', 'posts': posts} return render(request, 'app_blog/blog.html', context) def blog_detail(request, pk): user_post = BlogPost.objects.get(id=pk) context = {'title': 'Blog', 'user_post': user_post} return render(request, 'app_blog/blog_detail.html', context) def blog_user_detail(request, pk): user_detail = BlogPost.objects.get(id=pk) user_type = user_detail.author.groups.all()[0].name.capitalize() context = {'title': 'Blog', 'user_detail': user_detail, 'user_type': user_type} return render(request, 'app_blog/blog_user_detail.html', context) def blog_update(request, pk): if request.method == 'POST': blog_update = BlogUpdateForm(request.POST, instance=BlogPost.objects.get(id=pk)) if blog_update.is_valid(): blog_update.save() messages.success(request, 'Your blog-post has been updated!') return redirect('app_blog:blog_detail') else: blog_update = BlogUpdateForm(instance=BlogPost.objects.get(id=pk)) context = {'title': 'Blog', 'blog_update': blog_update} return render(request, 'app_blog/blog_update.html', context) urls.py: from django.urls import path from .views import * app_name = 'app_blog' urlpatterns = [ path('blog/', blog, name='blog'), path('blog/<int:pk>/blog_detail/', blog_detail, name='blog_detail'), path('blog/<int:pk>/user_details/', blog_user_detail, name='blog_user_detail'), path('blog/<int:pk>/blog_update/', blog_update, name='blog_update'), ] models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class BlogPost(models.Model): title = models.CharField(max_length=100, … -
How to add variables from GitLab settings to docker-compose file for my container on the server?
I am trying to set environment variables for the server in the docker composer file for the mail client of my Django application. Before I add variables in Gitlab CI/CD settings (Rep->settings->CI/CD->variables) and try to use it in my docker-compose file My docker-compose file: version: '3' services: my-server: image: server:latest build: . entrypoint: ["./entry_point.sh"] container_name: my-server environment: - DEBUG=True - DB_HOST=db - SUPPORT_EMAIL=${SUPPORT_EMAIL} - EMAIL_HOST=${EMAIL_HOST} - EMAIL_PORT=${EMAIL_PORT} - EMAIL_HOST_USER=${EMAIL_HOST_USER} - EMAIL_HOST_PASSWORD=${EMAIL_HOST_PASSWORD} volumes: - media:/home/app/my-project/media/ ports: - "8000:8000" depends_on: - db But where I check docker container vars I see next. root@myserver:~# docker exec ce30fd7afa8e bash -c 'printenv' EMAIL_HOST= HOSTNAME=hjf7a7578 PYTHON_VERSION=3.7.5 PWD=/home/app HOME=/root LANG=C.UTF-8 PIPENV_SYSTEM=1 EMAIL_HOST_USER= EMAIL_PORT= EMAIL_HOST_PASSWORD= DB_HOST=db SUPPORT_EMAIL= DEBUG=True _=/usr/bin/printenv How can I fix this? I'm trying this format: -SUPPORT_EMAIL:${SUPPORT_EMAIL} and just: -SUPPORT_EMAIL But in this case, I don’t even see the keys inside the container. -
join() argument must be str or bytes, not 'tuple' -- in Django while making a newspaper projects
I am relatively new to Django and was trying to make a mock newspaper app from django following the 'Django for beginners' book. I made a CreateView for the articles and routing it for 'new/' in my articles app in the project and setting the correct templates. Now redirecting to '/new/' leads to this TypeError. Request URL: http://127.0.0.1:8000/articles/new/ Django Version: 3.0.6 Exception Type: TypeError Exception Value: join() argument must be str or bytes, not 'tuple' Exception Location: c:\users\adi\anaconda3\lib\genericpath.py in _check_arg_types, line 149 ======================================================================== Traceback (most recent call last): File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\response.py", line 81, in rendered_content template = self.resolve_template(self.template_name) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\response.py", line 63, in resolve_template return select_template(template, using=self.using) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\loader.py", line 42, in select_template return engine.get_template(template_name) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\ADI\.virtualenvs\DJANGOdEV-QAaUnZ0o\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) … -
Django-tinymce not showing in admin
I installed django-tinymce, put it in the installed apps, added the url. Then I created a model as below: from tinymce import models as tinymce_models class Post(models.Model): parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) unit = models.DecimalField(max_digits=20, decimal_places=2) title = models.CharField(max_length=200) content = tinymce_models.HTMLField() I have also registered this model into the admin. Upon adding a Post instance through the admin, all the fields are showing, except for the content field. That is the field using Tinymce. The field is just white space with no option to input anything. Anybody know a fix? -
Django Channels on AWS EC2 server with WebSocket: No route found for path 'chat/room/'
I am struggling to get Django Channels to work on my server (works fine locally). I get this error with python3 manage.py runserver : WebSocket DISCONNECT /chat/room/ [80.215.36.125:43626] [Failure instance: Traceback: : No route found for path 'chat/room/'. /home/ubuntu/.local/lib/python3.6/site-packages/autobahn/websocket/protocol.py:2847:processHandshake /home/ubuntu/.local/lib/python3.6/site-packages/txaio/tx.py:366:as_future /home/ubuntu/.local/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred /home/ubuntu/.local/lib/python3.6/site-packages/daphne/ws_protocol.py:83:onConnect --- --- /home/ubuntu/.local/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred /home/ubuntu/.local/lib/python3.6/site-packages/daphne/server.py:200:create_application /home/ubuntu/.local/lib/python3.6/site-packages/channels/staticfiles.py:41:call /home/ubuntu/.local/lib/python3.6/site-packages/channels/routing.py:54:call /home/ubuntu/.local/lib/python3.6/site-packages/channels/security/websocket.py:37:call /home/ubuntu/.local/lib/python3.6/site-packages/channels/sessions.py:47:call /home/ubuntu/.local/lib/python3.6/site-packages/channels/sessions.py:145:call /home/ubuntu/.local/lib/python3.6/site-packages/channels/sessions.py:169:init /home/ubuntu/.local/lib/python3.6/site-packages/channels/middleware.py:31:call /home/ubuntu/.local/lib/python3.6/site-packages/channels/routing.py:150:call ] mysite/routing.py 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) ) }) chat/routing.py url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), ] chat/urls.py urlpatterns = [ url(r'^(?P<room_name>[^/]+)/$', views.room, name="room"), ] mysite/urls.py urlpatterns = [ url(r'^$', index), url(r'^', include('app.urls', namespace='app')), url(r'^chat/', include('chat.urls', namespace="chat")), ] chat.js var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_path = ws_scheme + '://' + window.location.host + window.location.pathname; var chatSocket = new WebSocket(ws_path); Thank you !! -
DisallowedRedirect: Unsafe redirect to URL with protocol '127.0.0.1'
I am trying to get my Django application running, and stuck at the following error at all of my endpoints (except the root endpoint): DisallowedRedirect at /coffeeshop/items Unsafe redirect to URL with protocol '127.0.0.1' With the server logs saying: Unsafe redirect to URL with protocol '127.0.0.1' Bad Request: 127.0.0.1:80/myapp/items [01/Jun/2020 16:12:36] "GET /myapp/items HTTP/1.1" 400 65131 Here is the myapp/items view: class ItemViewSet(ReadOnlyModelViewSet): model = Item queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = ItemFilterSet The server is running on http://127.0.0.1:8000/, and I am not trying to redirect anything in any of my views. As can be seen in the logs, the server tries to redirect the request to :80 port, and I don't understand why. Here is my settings file, too, for reference (maybe there are problems that I cannot see): ALLOWED_HOSTS = [ 'localhost', 'localhost:3000', '127.0.0.1', '0.0.0.0' ] # Application definition INSTALLED_APPS = [ # 'jet_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.MyappConfig', 'rest_framework', 'phonenumber_field', 'django_filters', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, … -
How to implement a python script in a Django web app using parameters from a view
My question about implementing a script into a view in a django web app. I have a .py script that I want to run inside this django web app using the user-supplied data, the configfile, the modelfile and the choice as command line arguments. The output is then a list with different scores which will then be displayed inside the html (not the part I need help with yet). So I have 2 forms, one that uploads a ML model and another one (the one I need help with) that uses user-supplied data to run a uploaded model: class Meta: model = MlModel fields = [ 'modelname', 'configfile', 'modelfile', 'choice', ] class TestForm(forms.Form): testdata = forms.FileField() model = forms.ModelChoiceField(queryset=MlModel.objects.all()) My views are as follow, where the test view is where the testing happens: if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/mltesting/') else: form = UploadForm() context = {'form':form} return render(request,'mltesting/upload.html', context=context) def test_model(request): submitbutton = request.POST.get("submit") testdata = '' modfile = '' confile = '' choice = '' form = TestForm(request.POST, request.FILES) if form.is_valid(): testdata = request.FILES['testdata'] model = form.cleaned_data.get('model') model = MlModel.objects.get(modelname=model) modfile = model.modelfile.path confile = model.configfile.path choice = model.choice else: form = … -
Fit a text into a button
I have a button of fixed size and various chunks of text. The length of the texts is different. How can I make the size of the text font change dynamically according to its length in order to fit the button boundaries properly? Thank you. -
Django REST Framework: Specify data type of SerializerMethodField
It seems SerializerMethodField assumes the data type of the field is a string, even if it is an int. For instance, I have this field: num_sections = serializers.SerializerMethodField(help_text="The number of sections for this course") def get_num_sections(self, obj) -> int: return obj.sections.count() However, in the auto-generated OpenAPI schema, this field shows up as a string field. Is there any way to set the proper data type for a SerializerMethodField? -
Custom ManyToManyField (Django)
I'm trying to make my own model field in Django. I want to save a "dict-like" object in the DB. For now, I'm inheriting from a TextField. class PctDictField(TextField): def __init__(self, key_class=None, value_class=None, *args, **kwargs): self.key_class = key_class or int self.value_class = value_class or Decimal super().__init__(*args, **kwargs) def parse_pctdict(self, pctdict_string: str): """Takes a string of an abs_dict and returns a PctDict pctdict_string format = 'key1:value1,key2:value2,...,keyN:valueN' """ if pctdict_string == '': return PctDict() string_items = pctdict_string.split(",") abs_dict = {self.key_class(item.split(":")[0]): self.value_class(item.split(":")[1]) for item in string_items} return PctDict(abs_dict) def from_db_value(self, value, expression, connection) -> PctDict or None: if value is None: return PctDict() return self.parse_pctdict(value) def to_python(self, value) -> PctDict or None: if isinstance(value, PctDict): return value if value is None: return PctDict() return self.parse_pctdict(value) def get_prep_value(self, value: PctDict): if value == '{}' or value is None: raw = None else: raw = ",".join([":".join([str(p), str(a)]) for p, a in value.abs_dict.items()]) return raw This PctDict class I'm using just make it easier to store absolute values to get back relative values: e.g: >>> p = PctDict() >>> p.abs_dict = {1:100,2:200,3:300} >>> p {1:17%,2:33%,3:50%} >>> p.total_weight 600 The fact is that it would be great to inherit from ManyToManyField in that form, since the pctdict_key … -
Jinja variable in metadata
I want to pass curly braced jinja curly braced data into metadata for it to be used by Facebook Open Graph. I want my Facebook share button to display different content depending on the page content. <meta property="og:url" content="{{ request.get_full_path }}" /> <meta property="og:image" content="{% static 'store/img/cafe.png' %}" /> What is the right way to do it? -
Value of Queryset doesn't populate template-tag in Django
I am missing a detail somewhere when trying to populate a simple template-tag with a value returned by a queryset. Views.py def render_cube_app(request, template="cube_app.html"): user_equity = Profile.objects.all() context = { 'user_equity': user_equity } return render(request, template, context) HTML {% for user_equity in user_equity %} <p id="money_metrics_box_equity_figure">{{ user_equity.fields.equity }}</p> {% endfor %} which doesn't populate anything as of yet. Also I think I could get rid of the for-each loop basically? -
How to deploy an app with multiple Docker containers to AWS Elastic Beanstalk?
I have a Django application whose docker image's Dockerfile is as follows: FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip3 install -r requirements.txt COPY . /code/ ENV PORT=8000 EXPOSE 8000 Then, I have a docker-compose.yml file for defining other container images and dependencies for my Django application as follows: version: '3' services: web: &django_app build: . command: python3 manage.py runserver 0.0.0.0:8000 ports: - "80:8000" depends_on: - rabbitmq rabbitmq: image: rabbitmq:latest celery_worker: <<: *django_app command: celery -A DJingApp worker --loglevel=info ports: [] depends_on: - rabbitmq As you can see above, I've got to have 3 containers(web, rabbitmq, and celery_worker) running at any point in time for my Django app to work. So, how do I deploy this project's Docker images to AWS Elastic Beanstalk and run them out there? Are there any changes that I will have to make to my Dockerfile or docker-compose.yml? If yes, what are they? -
self-referential relationship in django template
Here I want to display the parent category of the category in the template but I am getting None even if the category has the parent category. How can I display parent category here in this template ? models parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True, max_length=50) title = models.CharField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views class ListCategoryView(generic.ListView): model = Category context_object_name = 'categories' template_name = 'list_categories.html' template <td>{{category.title}}</td> <td>{{category.parent}} </td> <td>{{category.slug}}</td> <td>{{category.created}}</td> <td>{{category.updated}}<td> -
Generate Row numbers for Django Admin Listview for an App
I want to generate row numbers for the Author list based on pagination. The following code displays the row number. But there is a flaw in this code: For Example: I have 100 records on the list and I set the pagination to 25 & now I have 4 Pages. Then I visited all the 4 pages. Then I tried to visit the first page but it counts from 101 and so on. Is there any way to change the code based on pagination value? What I want is to reset the counter to 1 if I visit the page one and then increment it for all the rows. class AuthorAdmin(admin.ModelAdmin): indexCnt = 0 # If you enable fields variable then you will see only these fields in the editable form # fields = ['first_name', 'last_name', 'email'] exclude = ['created_date'] # it will exclude this field in the editable field list_display = ['index_counter', 'first_name', 'last_name', 'gender', 'website', 'email', 'phone_number'] list_display_links = ['first_name', 'last_name'] list_filter = ['gender'] search_fields = ['first_name', 'last_name', 'email', 'summary'] ordering = ['id', 'first_name', 'last_name', 'gender'] list_per_page = 25 def index_counter(self, obj): self.indexCnt += 1 return self.indexCnt index_counter.short_description = '#' -
Add a custom column in django database
Iam litle new to Django and Iam struggling to add column in Django Database. I was working to create a subcategory for products, but the I want those subcategories to be predefined. That is for example "Fashion" category could have subcategory of 'Men', 'Women', 'Kids'. I want a table in DB of these subcategories, without having the user or admin panel option to manipulate these field. Use can only select article belong to which subcategory. I go through a few documentation, but could understood much: 1. https://docs.djangoproject.com/en/3.0/howto/custom-model-fields/ 2. Adding fields to an already existing database for Django (version < 1.7) Please suggest me how to add these predefined table values. -
How to execute functions when a blog saved in django-admin panel
I am trying to create a function in Django, that when ever a blog is saved by admin it will post its content in to facebook. for reference my models.py only have an ImageField() and a TextField(). -
Auth token in URL path
I'm using Django REST Framework TokenAuthentication. For a few URLs I'm constrained to having to include the token in the URL path: https://example.com/api/<auth_token>/something How do I authenticate requests to such URLs? -
Is this the best way to trigger a django background task?
I have a background task which will countinuously add data to a DB every second. This is my views.py file. tasks is the method that triggers the start of the background task, after receiving a POST request. from django.http import JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from logging import getLogger from .tasks import stream_data logger = getLogger(__name__) @csrf_exempt def tasks(request): if request.method == 'POST': return _post_tasks(request) else: return JsonResponse({}, status=405) def _post_tasks(request): message = request.POST['message'] # Call every second stream_data(repeat=1, repeat_until=None) return JsonResponse({}, status=302) And this is my tasks.py file: from background_task import background from logging import getLogger from .models import DbData from datetime import datetime import random logger = getLogger(__name__) @background(schedule=1) def stream_data(): time = datetime.now() value = random.uniform(0, 1) d = DbData(time=time, type='F', value=value) d.save() logger.debug('Added TIME:{} ; VALUE:{}'.format(time, value)) To trigger it, I just run this from the cmd line: curl -d message='' http://localhost:8000/data/tasks/ which triggers the tasks function from views.py. Do I actually need to trigger it this way, or is there any way for me to just run the background task as soon as I run python manage.py runserver Also, I'm seeing in the documentation https://django-background-tasks.readthedocs.io/en/latest/ the parameter MAX_RUN_TIME which I'm not …