Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
template inheritance not working i.e extends in django html template is not working
I am new to django web development and learning how to inherit one HTML template to another within templates folder I have tut.html(base) and card.html(child) card.html {% extends "templates/tut.html" %} {% block content %} <div class="container px-4 py-4"> <div class="row gx-5"> {%for tut in Tutorial %} <div class="card col-lg-5" style="background-color: rgb(115, 128, 128)"> <div class="card-body"> <h4 class="card-title">{{tut.name}}</h4> <p class="card-text">{{tut.content|safe}}</p> <p>{{tut.date}}</p> </div> </div> <div class="col-lg-1"></div> <br /><br /> {% endfor %} </div> </div> {% endblock %} this is child HTML template that I intend to use in parent HTML tut.html {% load static %} <html> <head> <link href={%static "tinymce/css/prism.css" %} rel="stylesheet" /> <!-- CSS only --> <link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css' integrity='sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk' crossorigin='anonymous'> <!-- JS, Popper.js, and jQuery --> <script src='https://code.jquery.com/jquery-3.5.1.slim.min.js' integrity='sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj' crossorigin='anonymous'></script> <script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js' integrity='sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo' crossorigin='anonymous'></script> <script src='https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js' integrity='sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI' crossorigin='anonymous'></script> </head> <body> <nav class="navbar navbar-expand-sm navbar-light bg-light"> <a class="navbar-brand" href="#">Tutorial</a> <button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavId"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu" aria-labelledby="dropdownId"> <a class="dropdown-item" href="#">Action 1</a> <a class="dropdown-item" href="#">Action 2</a> </div>enter code here … -
Update models using signals
There are two models and I want to know how the profile bio can be updated using signals when the website model is modified (I need profile bio updated) Models.py from django.contrib.auth.models import User from django.db import models class Website(models.Model): url = models.URLField() users = models.ManyToManyField(User) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) nickname = models.CharField(blank=True, null=True, max_length=50) location = models.CharField(blank=True, null=True, max_length=50) weight = models.DecimalField(null=True, max_digits=5, decimal_places=2) Signals.py from .models import * from django.dispatch import receiver from django.db.models.signals import post_save, m2m_changed @receiver(post_save, sender=User, dispatch_uid='') def receiver_func(sender, instance, created, update_fields, **kwargs): if created and update_fields == None: profile = Profile.objects.create(user=instance) @receiver(m2m_changed, sender=Website.users.through) def AutoUpdateBio(sender, instance, action, reverse, pk_set, **kwargs): if action == 'post_add': # ** Add user to website - instance: website if not reverse: # ! HOW TO IMPLEMENT THESE TWO LINES # ** Add website to user - instance: user else: # ! HOW TO IMPLEMENT THESE TWO LINES My problem is with the AutoUpdateBio part Any help is highly appreciated -
Importing a django model to a python file
Project structure enter image description here import os import sys import django project_path = os.path.dirname(os.path.abspath('/mnt/c/WEB/codepython/PaymentForParking/index/telegram')) sys.path.append(project_path) os.environ["DJANGO_SETTINGS_MODULE"] = "PaymentForParking.settings" django.setup() And I get the error ModuleNotFoundError: No module named 'PaymentForParking' -
Url to the product after payment for subscription with Stripe in Django app
I've build Django app with authentication (Login/Sing up function). Then I created with Striple functionality to pay subscription for the product. In what way I can redirect user to the url with the product after payment? Does it require any special url/mechanism to activate the url after payment? I haven't yet created webhooks, is the mechanism of redirection to product url anyway related to webhooks implementation? -
ModuleNotFoundError: No module named 'my_app.urls' in django
after deploying site on heroku ,it's showing Internal server error. for debug I made "debug=true" and I found this error : "ModuleNotFoundError: No module named 'my_app.urls' " I've added my app in installed app list INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_app', ] my_project urls : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('my_app.urls')) ] my app(my_app) urls: from django.urls import path,include from . import views urlpatterns = [ path('',views.home ), ] views.py: from django.shortcuts import render def home(request): return render(request,'index.html') site running on local server while debug = true but not running while debug=false(showing server error ) how to fix this "ModuleNotFoundError: No module named 'my_app.urls' " What did I miss. Any help/suggestion will be highly appreciated. Thanks -
Error inserting data into two joined serializers
I am making an application in Django Rest Framework which the user can register multiple tasks in a project, but I am running into a problem and it is that when I want to record the data it generates an error where it says that task_id cannot be null: This my serializer: class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'title', 'description' ) class ProjectSerializer(serializers.ModelSerializer): start_project = serializers.DateField(input_formats=['%Y-%m-%d']) end_project = serializers.DateField(input_formats=['%Y-%m-%d']) task = TaskSerializer(read_only=True, many=True) class Meta: model = Project fields = ( 'developer', 'title', 'description', 'start_project', 'end_project', 'task', 'project_state' ) This is the json that I send: { "developer": [ 1 ], "title": "Inicio", "description": "Iniciar", "start_project": "1999-02-02", "end_project": "1999-02-02", "task": [ { "title": "Titulo", "description": "empezar" } ], "project_state": 1 } When I show the response by console it returns the complete data: data={'developer': [1], 'title': 'Inicio', 'description': 'Iniciar', 'start_project': '1999-02-02', 'end_project': '1999-02-02', 'task': [{'title': 'Titulo', 'description': 'empezar'}], 'project_state': 1} But when I want to get the data from the serializer it doesn't show me the tasks: {'developer': [1], 'title': 'Inicio', 'description': 'Iniciar', 'start_project': '1999-02-02', 'end_project': '1999-02-02', 'project_state': 1} -
How to remove empty label from choices in django filters while using foreignkey
enter image description here This is the image.How to remove these (---------) lines from these choices.I am using django-filters. class NotesFilter(django_filters.FilterSet): subjects = CharFilter(field_name='subjects', lookup_expr="icontains", label='Subject', widget=TextInput(attrs={'placeholder':'Enter Subject'})) term = django_filters.ChoiceFilter(choices=SEMESTER_CHOICES, required=False, label='Semester', empty_label=None,widget=Select(attrs={'placeholder':'Enter Subject'})) class Meta: model = Notes fields = ['subjects', 'faculty', 'program','term'] -
How to open a DAL ( Django Autocomplete Light ) Select2 programmatically
I'm using DAL to render an autocomplete from a form field like this: search = forms.ChoiceField( widget=autocomplete.Select2( url='/search/my_search/', attrs={ 'data-placeholder': 'Select an option', 'data-minimum-input-length': 1, 'data-theme': 'bootstrap4', }) ) It gets rendered with this class: "select2-hidden-accessible" and gets this attr "data-autocomplete-light-function="select2". It doesn't get the "select2" class, that is given to one of its spans. Everything works well, except that I can't open the select2 programmatically. I tried: $('#id_search').select2('open') But it gives the error: "The select2('open') method was called on an element that is not using Select2.", because DAL doesn't pass the class "select2" to the rendered form field "id_search". Due to some peculiarities, I can't pass the class manually to the component. If I click on the field, it opens and works normally. I need some help in opening the select2 on page load. -
not able to access related model data using foreign key in Django
models.py class products(models.Model): name = models.CharField(max_length=100) sku = models.CharField(max_length=50) vendor = models.CharField(max_length=50) brand = models.CharField(max_length=50) price = models.FloatField() product_status = models.BooleanField() quantity = models.IntegerField() def __str__(self): return self.name # categories class categories(models.Model): category_name = models.CharField(max_length=50) parent_id = models.IntegerField() # product categories class product_categories(models.Model): product = models.ForeignKey(products, on_delete=models.CASCADE) category = models.ForeignKey(categories, on_delete=models.CASCADE) def __str__(self): return self.category I can access 'category' table data using data = products.objects.all() data.values('product_categories__category__category_name') output: <QuerySet [{'product_categories__category__category_name': 'xxxx'}}]> If I put this data.product_categories.category output: 'QuerySet' object has no attribute 'product_categories' how do I get a qureyset(can be passed to html) which includes data from "categories" table along with the data of "products" table -
How can i assign task to an employee?
I am developing a HR Task management system where employee can assign a task to another emloyee. what I am able to do is create two fields in the form. One field is named ASSIGNED TO and the other is name ASSIGNED BY. WHAT I WANT If I am assigning a Task to another employee, the employee should be able to know who assigned the task to him without me indicating or using the field called ASSIGNED TO in the form. WHAT I HAVE DONE SO FAR class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) # avatar = models.ImageField(upload_to='Avatars', null=True, blank=True) # user_type = models.CharField(max_length=10, choices=user_type, default='manager', null=True, blank=True) avatar = models.ImageField(upload_to="avatars", null=True, blank=True, default='default.jpg') # organisation = models.ForeignKey('Organisation', on_delete=models.RESTRICT, null=True, blank=True) # department = models.ForeignKey('Department', on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) street_address = models.TextField(max_length=200, null=True, blank=True) appartment_unit = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) zip_code = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(max_length=40, null=True, blank=True) #state_of_birth = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.CharField(max_length=100, null=True, blank=True) marital_status = models.CharField(max_length=100, null=True, blank=True) # spouses_name = models.CharField(max_length=100, null=True, blank=True) # spouses_employer = models.CharField(max_length=100, null=True, blank=True) # spouses_work_phone = models.CharField(max_length=100, null=True, blank=True) … -
Assigning issue, unable to give or take roles in user admin , django
so basically what is happening is that i am trying to stop a user from acessing specific views, for example: admin and so on, unfortunately for some weird reason every time i create a user it receives every group role i created, even tho i didnt even write the code for it. I also cant take out a user from a group or put him in one, when i go inside a user infos. it is worth noting i am using, an abstract user model which may be the cause. This is how my user admin currently is, this is a new user by the way And this is how i think it should look like -
How to create separate form widgets for ModelMultipleChoiceField in Django
I have a ManyToMany relationship between two Django Models: Team and Member. A single Member can be part of multiple teams. I am able to successfully bind a Form class to a CreateView, and, using the standard ModelMultipleChoiceField,can successfully save the Form using the save_m2m method. However, the default widget for the field is not suitable for my user experience. Instead of using a picklist, I would like to create a separate select box for each number of selectable Members per team. For example, if the Team can have 7 Members, I would like to show 7 select boxes, rather than one pick list that a user selects 7 different objects from. I understand I may not get a complete answer, but would appreciate any pointers on if I should be looking into overriding the Field with a custom MultiWidget, or if using an inline formset might be a more appropriate route. Or, something else... -
Existing Django site implementation of wagtail. How to get RichTextField to show in admin?
I have added wagtail to an existing Django site. I wish to change the content part of the model to a RealTextField. What I had and what I have altered is shown below: class Post(models.Model): content = models.TextField() class Meta: ordering = ['-date_added'] def __str__(self): return self.title Post(models.Model): content = RichTextField() class Meta: ordering = ['-date_added'] content_panels = Page.content_panels + [ FieldPanel('content', classname="full"), ] def __str__(self): return self.title class Meta: ordering = ['-date_added'] content_panels = Page.content_panels + [ FieldPanel('content', classname="full"), ] def __str__(self): return self.title -
Why does javascript create spurious images using ajax?
Firstly I must apologise for the length of the code in this question. It is based on Django and javascript and I have stripped out as much as I can to give a working example The challenge is to create a composite image using a random number of rooks - all black rooks on the top row and all red rooks on the bottom row This works perfectly when the page is first loaded, but if I click on the New Board button, then randomly red rooks might appear in the top row, or black in the bottom (The image was downloaded from here) html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head> <body> {% block content %} <div style="display:none;" id="pieceImages"></div> <p>Red:<span id="red-count"></span> Black:<span id="black-count"></span></p> <canvas id="top-image" style="background-color:#ffff00;"></canvas> <p><button id="new-board">New Board</button> {% endblock content %} <script type="text/javascript" src="{% static 'js/test.js' %}"></script> </body> </html> urls.py #pages/urls.py from django.urls import path from .views import HomePageView, NewBoard urlpatterns = [ path('', HomePageView.as_view()), path('new-board', NewBoard.as_view(), name= 'new-board'), ] views.py # pages/views.py import os import io import random import base64 from PIL import Image as PilImage from django.views.generic import View from django.shortcuts import render from django.http import JsonResponse … -
Circles not showing up in webpage when created via JavaScript (Django, Python)
I have made a page in my Django webapp that displays an image and allows the user to click on the image and should place a circle on top of the image where the user clicked. The following code is able to get the location of the mouse click on the image, and adds a tag to the html in the right place, but it won't actually show up on the page. If I hard code a circle into the html, it shows up just fine. It also seems like the mouse is on a different coordinate system than the SVG element... I have tried event.x, event.pageX, and event.clientX but noticed no difference. Even if I hard code the position of the circle, it won't show up on the click html: {% extends 'main/base.html' %} {% block head_content %} {% load static %} <script type="text/javascript" src="{% static 'js/click.js' %}"></script> {% endblock %} {% block content %} <div class="my-div"> <div> <h1>The Page!</h1> </div> <form enctype="multipart/form-data" method="POST" action="/mysite/nextpage/"> {% csrf_token %} <svg id="svg"> <image href="data:image/png;base64,{{ my_img }}"/> <!-- Placing a circle manually works just fine! --> <circle cx='50' cy='150' r='50' fill='red'/> </svg> <input type="submit" name="submit" class="submit-btn"></input> </form> </div> {% endblock %} Javascript: … -
get the name of the qs lookup instead of the value
I am trying to display the total number of tickets created in a day and have them show up as a dashboard feature . it only gives me the "0" for resolved and "p" for paused instead of the actual "Paused" or "Open". So I am guessing the values being looked at in "Status" of my model Support Tickets is not being called right but i have no idea how to call the values I need @admin.register(TicketSummary) class TicketSummaryAdmin(ModelAdmin): change_list_template = 'admin/Webapp/ZoomAccount/ticket_summary_change_list.html' date_hierarchy = 'Created_At' def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'total': Count('Ticket_Number'), 'total_tickets': Count('Ticket_Number'), } response.context_data['summary'] = list( qs .values('Status') .annotate(**metrics) .order_by('-total_tickets') ) response.context_data['summary_total'] = dict( qs.aggregate(**metrics)) return response -
How to use loop for requesting from html template in Django
From html template say "createlist" I want to add link which actually request server to get one more object of image form to the "createlist" page. But when I run the code it actually happens only one time but I want maximum of 5 times this should be accepted. So here how I can use loop in html template so that it will get the request again and again up to the limit say 5. here is the template code - {% if morepicform %} {{ morepicform }} {% endif %} Want to add more pics? <a href="{% url 'createlist' 'morepic' %}" role="button"> <img src="static/auctions/plus-circle-solid.svg" height="20px" width="20px"></a> views function def morepic(request, morepic=''): return render(request, "auctions/createlist.html",{ "morepicform" : PictureForm(), "picform" : PictureForm(), "listform" : ListingForm() }) url pattern path function - path("createlist/<str:morepic>", views.morepic, name="createlist") Now how can I add the functionality of requesting "morepicform"? -
Cannot get Django to connect to MySQL within Dockerfile
I have been trying to get a Django project to connect to a MySQL database on my local computer using a Dockerfile. I would like to be able to do this so that I can use a container to host a website on AWS, so ideally I would like to use a Dockerfile only (not docker compose) as it makes installing it onto Elastic Beanstalk and Lightsail easy. I have created a repository on GitHub in the following location: https://github.com/MarkyMark1000/PYTHON_MySQL_Django_Docker I have tried all kinds of things such as using 'RUN apk update && apk add py3-mysqlclient' or trying to install python mysql connector, but I have no luck at present. If you could let me know what I need to do, I would be very grateful. Many thanks Mark -
Django: can't read urlopen responses's file as binary
I have a problem with file requesting. python 3.9.1, django 3.1.7 What i do: response = request.urlopen('some_good_address') response.class == <class 'django.core.files.base.File'> response.file.class == <class '_io.TextIOWrapper'> After that i need to read response as binary: base64.b64encode(response.read()) On 2.7 it was OK. -
Email automation for Amazon Orders - MWS API/SP API
I am trying to create a tool for sending automatic follow up ( review request, feedback request) for the Amazon order and I am using Amazon SES for the email service. I successfully connected marketplaces via login with Amazon and fetched user order, buyer email etc and sending emails to those buyer emails. SES shows they are delivered on the buyer email but I can't find them inside seller-buyer messages in amazon seller central. After playing around a bit I added my email as a verified sender on my own account then it sends the email and I can also see inside buyer-seller central. Now the problem is how can I verify my email as a verified email for other sellers who registered on my website via login with Amazon. Thanks in advance for the help. -
Django project is missing migrations, prodcution and development has different migrations
So I started working on a project that is right now on production but the preovious dev kinda made a mess with migrations (or maybe I am wrong), the migrations in developement and in production are not the same (he gitignored them) and I can not start working because there are missing migrations in development so the database is no fully migrated. Im thinking I can just delete all migrations in development, reset them but I don't think that is a good idea in production. What should I do? -
can't get Primary Key from kwargs
i have this views.py class AddToCartView(APIView): def post(self, request, *args, **kwargs): pk = self.kwargs.get('pk') print(pk) if pk is None: return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST) item = get_object_or_404(items, pk=pk) i am getting None from print(pk), what am i doing wrong? -
Python 3.8 DJANGO GCLOUD issue
Strange and frustrating issue. Have two django apps which require to be hosted on Google Cloud. The first app is currently active and being served, the second app will not give in. The situation is as following; Two python 3.8 django apps Two different cloud project with each dedicated MySQL 8.0 instances When runserver app one locally with glcoud first project activated and CLoud_sql_proxy to be listening for connections. It correctly connects to the Google MySQL insctance. (Development) D:\Development>Cloud_sql_proxy.exe -instances="someinstance:europe-west2:somename"=tcp:3306 2021/04/29 13:42:08 Listening on 127.0.0.1:3306 for someinstance:europe-west2:somenam 2021/04/29 13:42:08 Ready for new connections Now I am doing the same thing for the second app (not simultaneously), correct project activated and CLoud_sql_proxy to be listening for connections based on connection to the second Google MySQL instance. It will not connect to the MySQL instance, instead local is being used. if os.getenv('GAE_APPLICATION', None): is always true. Has anyone some tips? Maybe someone has experienced the same? Two apps work along the same lines, and cloud configuration is the same. Setting.py # https://docs.djangoproject.com/en/3.2/ref/settings/#databases import pymysql # noqa: 402 pymysql.version_info = (1, 4, 6, 'final', 0) # change mysqlclient version pymysql.install_as_MySQLdb() # Local development mode 24/04/2020 if os.getenv('GAE_APPLICATION', None): # Running on production App … -
Error 404 Nginx can't find media files. +Django
I was setting up basic Django site with nginx. When i navigate to the url of the file i get error 404 Not Found nginx/1.18.0 (Ubuntu) This is the conf file upstream django { server unix:///home/jo/testproject/testproject.sock; } # configuration of the server server { listen 80; server_name _; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media/ { alias /home/jo/testproject/media/; } location /static { alias /home/jo/testproject/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/jo/testproject/uwsgi_params; } } the media folder is in /home/jo/testproject/media and inside it i have media.gif, but ip/media/media.gif doesnt work when i write the ip in the browser i get Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. I think everything else i setup correctly -
How to use variable column name in filter in Django ORM?
I have two tables BloodBank(id, name, phone, address) and BloodStock(id, a_pos, b_pos, a_neg, b_neg, bloodbank_id). I want to fetch all the columns from two tables where the variable column name (say bloodgroup) which have values like a_pos or a_neg... like that and their value should be greater than 0. How can I write ORM for the same? SQL query is written like this to get the required results. sql="select * from public.bloodbank_bloodbank as bb, public.bloodbank_bloodstock as bs where bs."+blood+">0 and bb.id=bs.bloodbank_id order by bs."+blood+" desc;" cursor = connection.cursor() cursor.execute(sql) bloodbanks = cursor.fetchall()