Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
django urls.py: two modules with similar paths
I have two modules in my django app, let's say cats and dogs, and I want to have urls like this: /fluffy/meow.html - Fluffy is a cat's name /fluffy/eat.html /jackie/bark.html - Jackie is a dog /jackie/eat.html - same name as in cats module There will be a lot of different cats and dogs, but it's guaranteed, that cat and dog can't have the same name. If I make urls.py like this: urlpatterns += [ path('<slug:cat_name>/', include('cats.urls')), path('<slug:dog_name>/', include('dogs.urls')), ] request /jackie/eat.html wil be caught by cats module, but there's no cat with name jackie, so it will give 404 error. Is it possible to make django check another url path instead of getting 404 error? -
Django Allauth - How to hook to custom signals?
I am utilizing Django All Auth for my applications user management. I want to add some custom logic for after an email has been confirmed. I found these in the docs/library (Page 50). There are several signals emitted during authentication flows. You can hook to them for your own needs. • allauth.account.signals.email_confirmed(request, email_address) Sent after the email address in the db was updated and set to confirmed. And inside their signals.py file: email_confirmed = Signal(providing_args=["request", "email_address"]) I created my own signals.py file and added the following code: from allauth.account.signals import email_confirmed from django.dispatch import receiver @receiver(email_confirmed) def custom_logic(sender, **kwargs): a = 0 import ipdb; ipdb.set_trace() if a: pass But when I register an account, and follow the URL to confirm the email, my debugger statement is not being triggered (Note, I am using Debug=True and following the URL from my console, I am not sure if this changes things). Am I connecting to the signal correctly? How would I go about testing this out? -
Create a logging system to log user activity in Django
I would like to have a functionality to log a user activities after they have been logged into my Django app. The log will consist of user tracking details such as how long a user spent on a webpage, how often the webpage is being served up for the user. Mainly getting details on how popular a certain webpage or data in my Django app so that I could create more content that users prefer. Any ideas or tools to implement this? -
Razorpay accessing callback URL using GET method instead of POST
I have implemented the Razorpay payment gateway to my platform according to the documentation. As per the documentation after successful payment, the gateway will try to access the URL using the POST method with the order payment information to process the order on the platform. This is the success page I am seeing after the payment as the account is in test mode. After clicking on the success it is redirecting the callback URL using GET method without any data, so I am not able to process the order at my end. According to the docs, it should access using POST method. Does anyone know in what case the gateway is accessing the callback URL with GET method ? -
How to mock out the form_valid() superclass from a Python unit test?
I have a function within one of my views: def form_valid(self, form): ...some functionality... return super().form_valid(form) And am trying to test some part of the functionality, but would like to mock out the 'form_valid' superclass to prevent it from trying to redirect to the success url. How can I do this?