Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create a html view of form fields which allow editing with rick text editor and then create pdf in django
In djanog vr 3.1, I have three models and I store data based on operation. Now I want to create one view (like rich text editor) which contains all the fields values of my models. Also some non model fields with prefilled data ,so I can first edit the values and create PDF. How to achieve this. -
Django fetching data through webhook and download in system then save in database using rest-framework
can anyone help me solving these Serializers.py from .models import Data class DataSerializer(serializers.ModelSerializer): class meta: model = Data fields = '__all__' i used webhooks for getting JSON data then saving it into my system Views.py from django.shortcuts import render import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .models import Data from .serializers import DataSerializer from rest_framework.decorators import api_view from rest_framework.response import response @csrf_exempt @require_POST def webhooks(request): jsondata = request.body data = json.loads(jsondata) response = HttpResponse(data, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="data.json"' return HttpResponse(status=200) -
Update Django context variable using Ajax
I've spent quite some time trying to find a solution, but I am fairly new to Django and I just can't seem to wrap my head around this. In my detail view I pass the product I want to display (product) in the template and also the first product type of the product (pid). When a new product type is selected via a dropdown box in detail.html, I need to update the product type context variable without reloading the page, and so that I can send it to cart_add view as a parameter in the URL. I figured I can do this using Ajax. I can display the value of the selected product type, but I do not know how to update the context variable to this new value. views.py def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug) product_types = ProductType.objects.filter(product=product, available=True) pid = product_types[0] mylist = [] for product_type in product_types: mylist.append(dict((x.base, x.value) for x in ProductAttribute.objects.filter(product_type=product_type))) category = Category.objects.get(id=product.category.id) parent_category = category.parent_category cart_product_form = CartAddProductForm() return render( request, 'shop/product/detail.html', {'parent_category':parent_category, 'category':category, 'product': product, 'cart_product_form': cart_product_form, 'product_types': product_types, 'mylist': mylist, 'pid':pid} def load_product_type(request): product_type_id = request.GET.get('product_type_pk') product_type = ProductType.objects.get(id=product_type_id) return render(request, 'shop/product/product-type.html', {'product_type': product_type}) product-type.html {{product_type.id}} detail.html <select … -
Products on the homepage are not being displayed properly
this post is kind of a sequel of this post - (but I have progressed since then) A large number of problems with React, Django, Django REST and Axios I am using Django, Django Rest and React my products are being displayed like this - But I should see them like this - ProductScreen.js - import React from "react"; import { Link } from "react-router-dom"; import { Row, Col, Image, ListGroup, Button, Card } from "react-bootstrap"; import Rating from "../components/Rating"; import products from "../products"; function ProductScreen({ match }) { const product = products.find((p) => p._id == match.params.id); return ( <div> <Link to="/" className="btn btn-light my-3"> Go Back </Link> <Row> <Col md={6}> <Image src={product.image} alt={product.name} fluid /> </Col> <Col md={3}> <ListGroup variant="flush"> <ListGroup.Item> <h3>{product.name}</h3> </ListGroup.Item> <ListGroup.Item> <Rating value={product.rating} text={`${product.numReviews} reviews`} color={"#f8e825"} /> </ListGroup.Item> <ListGroup.Item>Price: ${product.price}</ListGroup.Item> <ListGroup.Item>Description: {product.description}</ListGroup.Item> </ListGroup> </Col> <Col md={3}> <Card> <ListGroup variant="flush"> <ListGroup.Item> <Row> <Col>Price:</Col> <Col> <strong>${product.price}</strong> </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Row> <Col>Status:</Col> <Col> {product.countInStock > 0 ? "In Stock" : "Out of Stock"} </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Button className="btn-block" disabled={product.countInStock == 0} type="button" > Add to Cart </Button> </ListGroup.Item> </ListGroup> </Card> </Col> </Row> </div> ); } export default ProductScreen; HomeScreen.js - import React, { useState, useEffect } from … -
Django static files not showing up
I tired following code first I copy the assets files to my project assests files Then I add following settings in setting .py STATIC_DIR = BASE_DIR / 'resume/static' STATIC_ROOT = BASE_DIR / 'static' STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] after that I tired python manage.py collectstatic and got a new directory new static directory after that I tired to add tag {% load static %} and alter the paths into {% static 'path' %} indext.html still my website is not showing up website image please help -
Form-data is send the same place independently of which url is parsed to action
I'm fairly new to Django, and I want to create a "delete user" button. I have the following: view.py @login_required def delete_profile_confirm(request): if request.method=="POST": request.user.delete() messages.success(request, "Profile has been removed!") return redirect("home_home") return render(request,"users/delete_profile_confirm.html") my urls urls.py urlpatterns= [. . path('', views.home,name="home_home"), path("delete_profile_confirm/",users_views.delete_profile_confirm,name="delete_profile_confirm") ] and my template delete_profile_confirm.html {% extends "my_app/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <legend class="border-bottom mb-4">Are you sure you want to delete your profile?</legend> <form action="{% url 'home_home' %}" method="POST"> <input class="btn btn-default btn-danger" type="submit" value="Yes"/> </form> <a class = "btn btn-outline-info" href="{% url 'my_overview' %}"> Nopes - take me back!</a> </div> </form> </div> {% endblock content %} The funny thing is, that it works even though if I put anything in the <form action={url}> - It doesnt matter if it is home_home, delete_profile_confirm. In my understanding, it should be delete_profile_confirm since the post-request is handled there, but for some reason it works anyway. I might misunderstand what the action tag does exactly here? -
How to send multiplechoicesfield in post request - Postman
I use django-multiselectfield package in my project and based on its docs I use MultipleChoiceField in my serializer: class InsCatSerializer(serializers.ModelSerializer): levels = fields.MultipleChoiceField(choices=LEVEL) when I send a request with raw JSON in postman that works fine "levels": ["INTERMEDIATE", "ADVANCED"] But I need to use form data because I have files and images in my request! I try this way: levels:INTERMEDIATE levels:ADVANCED but just saved the last element ( ADVANCED in this example ) any suggestion to solve? -
Django Model Attributes not obvious usage
class Invoice(models.Model): pass class Line(models.Model): cost = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) I have two models. In Invoice model I need a total field everywhere(summary of lines cost). First I created a total attribute with a @cached_property that is obvious and clear way to define total of invoice. @cached_property def total(self): return self.line_set.aggregate(total_sum=Sum('cost'))['total_sum'] But after that, I realised that I can override Manager objects = InvoiceManager() class InvoiceManager(models.Manager.from_queryset(InvoiceQuerySet)): def get_queryset(self): return super(InvoiceManager, self).get_queryset().annotate( total=Sum('line__cost') ) and annotate this field in every query and remove total method! In this case total field is less obvious for programmers(IDE will not highlight it), but cost less resources if you will forget to use select_related What way is more preferable ? -
Override parent(some method of django faramework's class)'s global behavior by inheritance
In django/contrib/admin/sites.py, I have class AdminSite: def get_app_list(self): //do something pass def an_other_to_change(self): //do something pass def not_to_change(self): //do something pass I want to change/override implementation of few methods of this class so that default function should have some thing new in it what i want. To be sure that my code is working I added follwoing to end of a views.py file in my application. I also tried to add sites.py in my application and used the same following code, but its never executed because I am not calling it anywhere manually. What could be the way to achieve "default calls of django could come to these overridden methods rather than going directly to parent functions written in django/contrib/admin/sites.py" from django.contrib.admin.sites import AdminSite as BaseAdminSite # from django.contrib.admin import AdminSite as BaseAdminSite class AdminSite(BaseAdminSite): def _build_app_dict(self, request, label=None): res = super(AdminSite, self)._build_app_dict(request, label) res.update({'new_attr': 1}) return res def get_app_list(self, request): res = super(AdminSite, self).get_app_list(request) res.update({'new_attr': 1}) return res -
Chat with pusher and database
I'm building a real time chat using Pusher framework and since I want to keep the chat history and display it I am using also db storage. Having private-channels for each one-to-one conversation I'm not sure what is a recommanded way to deal with the database. My approach is like this: save new-message with post on "/conversation" having two user type foreign-keys in the database model: sender, receiver when I receive or send new-messages I get from "/conversations" the stored-messages filtered by (sender, receiver), add them to the current message on client-side and show them. Is there a better/optimized aproach to build or get the stored-messages and display them ? -
Queryset is returning empty values even if there are values
serializer_class = ProductQSerializer http_method_names = ['get'] def get_queryset(self): queryset = ProductQ.objects.all() return queryset When calling get method it returns: [ {}, {} ] Response is not showing the values. -
Images are not showing in Production ( DEBUG =False )
I Build a WebApp and I am stuck on a Problem. Images are not showing in Production (DEBUG = False) settings.py MEDIA_ROOT= '/home/new/gitrepo/main/media' MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = '/home/new/gitrepo/static/' What have i tried I tried python manage.py collecstatic BUT images are still not showing in the Website. I found many answers on this Topic like THIS. BUT it didn't worked for me. I don't know what i am doing wrong. Any help would be appreciated. Thank You in Advance. -
Django modeform choose date
I'm doing a to-do web app and I want user to input deadline and I have DateTimeField for it, but user can write whatever they want, but I want them to choose a legit date. models: class Task(models.Model): title = models.CharField(max_length=50) completed = models.BooleanField(default=False) uploaded = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField(null=True) forms: class TaskForm(forms.ModelForm): title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'})) class Meta: model = Task fields = '__all__' views: def TaskView(request): tasklist = Task.objects.all() tasks = Task.objects.order_by('uploaded') form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tastlist': tasklist, 'tasks': tasks, 'form': form, } return render(request, "pages/index.html", context) -
How to remove user_permissions from django admin panel
let me know how to remove the user_permission field from user and groups in a model as shown in below pic enter image description here -
Not able to ignore static files from getting pushed to git in Django project
I had pushed a new Django project BTRE to my git repository. But I can't ignore the static files from pushed to the repository even though I have mentioned the directories in .gitignore file. -BTRE_Project |-btre |-static This is my .gitignore file: # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ # in your Git repository. Update and uncomment the following line accordingly. btre/static/ I have tried deleting the repository and pushing again after updating the .gitignore file. -
django and django_plotly_dash integration with two databases vs one
I have integrated django_plotly_dash with my django app. It is a simple app that allows logging in and viewing some data and charts. Django is linked to MySQL database. The data for the plotly dash charts actually come from a second MySQL database. I use pymysql to query the data in the second database. It works as it is now. My question is if it is better to create django model and store the tables from the second database in the django database. Currently the second database just has some sample data so I don't mind loading data to either. The data will always be loaded into database through a python script, not from django front-end. What are the pros and cons in the two options - two databases vs one? Is there any impact on database connection when there are multiple users? -
How to solve no module error when testing the code?
I faced the error No module named 'rest_framework' when testing the code, however rest_framework is installed and everything works just fine. The problem occurs only on tests. When I run pip3 install djangorestframework or python -m pip install djangorestframework , I get this Requirement already satisfied: Everything what I found in the internet did not help. -
Django view not redirecting based on response
I would like this Django view to redirect according to server response but it still stays on 'callback.html' no matter the response, any insight on what I am doing wrong would be appreciated. def callback(request): if request.method == 'POST': response = json.loads(request.body.decode('utf-8')) print (response) result_code = response["Body"]["stkCallback"]["ResultCode"] if result_code == 0: amount = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][0]["Value"] mpesa_receipt_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][1]["Value"] transaction_date = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Value"] phone_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][3]["Value"] str_transaction_date = str(transaction_date) transaction_datetime = datetime.strptime( str_transaction_date, "%Y%m%d%H%M%S") aware_transaction_datetime = pytz.utc.localize( transaction_datetime) our_model = Mpesa.objects.create( MpesaReceiptNumber=mpesa_receipt_number, PhoneNumber=phone_number, Amount=amount, TransactionDate=aware_transaction_datetime, ) our_model.save() return redirect('realtor:create') else: return HttpResponseRedirect(reverse('main:contact')) return render(request, 'callback.html') -
Pythonanywhere static problems [closed]
Yesterday I upload at first time a Django App to pythonanywhere for check. After fighting me with the static URL, finally I could see the images and css on my computer, but only in Firefox. I open Chromiun and I can't see the styles. I try in other devices and the same result. Reading forums they speak about DNS, do you know why I can't see the static in others devices? Best Regards. -
Module not found Error even after changing python version
I am trying to import PyPDF2 , into my django project ,I am getting ModuleNotFoundError I checked its properly installed inside virtualEnv , here I am even trying to change Python version from visual studio extension. How can I change the python version from 3.9.0 to 3.5.0 to check PyPDF2 if it works with 3.5.0 . In visual studio extension I changed python version but why its still using 3.9.0 when checked with python --version if I use num2words still I get same ModuleNotFoundError. -
how to set the placeholder property of django-ckeditor
while using django-ckeditor for my website, i want to set the 'placeholder' property for the editor I've tried to work directly in settings.py like this : CKEDITOR_CONFIGS = { 'default': { ... 'extraPlugins': ','.join(['placeholder']), 'placeholder': 'blabla' }, } and i tried this: widgets = { 'body': forms.Textarea(attrs={'placeholder': 'blabla'}) } but it didn't work! what should i do? -
django organize compliance check
Please tell me if there is an opportunity to check the compliance of the finished product with the client's requirements. There are three models: manufacturers Manufacturer Car - the characteristics of the cars they make through a one-to-many connection. and customer model with their own requirements for color and engine power I can't connect the customer with the Manufacturer and Car models. I would like to organize the check by type: if self.color == self.client_color = True retur self.client_name in other words, if the color matches the customer's color, then display the customer's name in the template class Manufacturer(models.Model): # ... pass class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) color = models.CharField(max_length=50, unique=True) engine_power = models.IntegerField() # ... class Specification(models.Model): client_name = models.CharField(max_length=50, unique=True) client_color = models.CharField(max_length=50, unique=True) client_engine_power = models.IntegerField() maybe someone has already done this or similar -
How do I set DB name in AWS EC2 MySQL server?
So, I have created a database instance. I'm using Django, and tried to make proper changes in settings.py, as below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'db-instance-bookcake', 'USER' : '', # my username 'PASSWORD' : '', # my pw 'HOST' : 'db-instance-bookcake.[therest]', 'PORT' : '3306', 'OPTIONS' : { 'init_command' : 'SET sql_mode="STRICT_TRANS_TABLES"' } } } Now I first thought that I needed to put the DB instance identifier in NAME. But then I realized that it's Database Name not Database Instance Identifier that's needed. So I looked for my DB name, but couldn't find it. I've tried modifying the DB instance, but all I could find was changing the DB instance identifier. How do I make change to, or set, the DB name, not DB identifier? Thank you very much in advance. -
Cannot overwrite django settings in production
I am using this settings layout in my porject website: settings ├── base.py ├── dev.py └── __init__.py In my manage.py file, there is path to settings: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings') My __init__.py file: import os try: from .base import * # noqa except ImportError: pass if os.environ.get('DJANGO_DEVELOPMENT') != 'prod': from .dev import * # noqa try: from .local import * # noqa print('----> Imported') except ImportError: print('----> No local settings found') Basicaly, if not environment prod, import dev, and if local file exists, import it. In base.py there are all settings shared and in dev or local files, I am replacing values depends on my personal requirements. On production, i am deploying local.py via ansible. I can see, the file is there, and I am setting up DB path for sqlite and ALLOWED_HOSTS or DEBUG. In production logs, I can see message ----> Imported so I assume, this should work, but: On production, I noticed, that setting are imported twice, I can see message ----> Imported twice. When I change DB name in my local.py file, or even in base.py file, no changes are made but also, no error in logs. This is my local file: from website.settings import base # I … -
Incorrect filr path in django clean() while validating file type
I have to validate file type in django forms. I am using python's imghdr to check file type (I have also used PIL, but error is same). This is my code class GlobalImagesForm(forms.ModelForm): class Meta: model = GlobalImages exclude = ('id',) def clean_home_next_image(self): home_next_image = self.cleaned_data['home_next_image'] file_type = imghdr.what(home_next_image) if file_type not in ['jpg', 'jpeg', 'png']: msg = gettext("Invalid file type. Accepted file type: %(types)s.") % {'days': "jpg, jpeg, png"} raise forms.ValidationError(msg) return home_next_image But this giving error The joined path (D:\admin\home\bg-cat.png) is located outside of the base path component (D:\Django\Vanloc\vanloc\media) How can I get path of Image that user is trying to upload.