Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to close popup in Django Admin
I am using Python 3.7.10 with Django 3.1.6, and I have used the following code to create an admin popup that will be triggered when clicking on the "edit_link": class EditLinkWidget(forms.URLInput): def render(self, name, value, attrs, renderer): super().render(name, value, attrs, renderer) if not value: return '' return mark_safe(f'<a class="related-widget-wrapper-link change-related" href="{value}?_to_field=id&_popup=1" '\ 'data-href-template="{}?_to_field=id&_popup=1">Edit</a>').format( re.sub("(\d+)", "__fk__", value)) class PageForm(TranslatableModelForm): edit_link = forms.CharField(widget=EditLinkWidget, required=False, disabled=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: self.fields['edit_link'].initial = f'/admin/cms/car/{self.instance.car_id}/change/') class Meta: model = User fields = ('edit_link',) It works great, but the problem is that the popup doesn't close automatically when I click on the Save button, throwing the following javascript error: Does somebody know how can I fix it so the popup can be closed automatically? I guess it should communicate with the parent admin page somehow? -
How to use Base64FileField together with the FileField?
I am using Django rest and initially, I used form-data to upload images to Django. My model has a FileField and it worked well. Right now, I need to handle JSON uploads also. I integrated this Base64FileField from the drf-extra-fields, added it to the serializer, but now my form-data request fails with the following error: "innitial_file_path": [ "Invalid type. This is not an base64 string: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>" ] How can I make it work for both the form-data and JSON request body? I suppose I still need to keep FileField in my model, but somehow convert base64 to the JSON. Also, should I create multiple serializers? Right now I have multiple nested serializes, so it would be difficult to use by creating multiple. I would then need to get the content-type in the create method of the serializer and depending on that use different serializer. How can I get that? -
django migration error, InvalidTemplateLibrary
this error started popping up after i install django rest_frame work and coverage: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'six' from 'django.utils'(C:\Users\kaleb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\__init__.py) i even deleted the hole app and created it again but the error is still here. -
Better way to setup PWA for a Django project
thanks for your time. i have a Django project, with amp-html on front-end. and got to make it a PWA, the problem is that i still don't understand the requirements. Tried by just adding manifest.json and sw.js to the template folder, ain't got right. Tried with a third part library (https://pypi.org/project/django-pwa/) it worked, but i ain't understand why and how to work on it. Now i got the option to add service workers trough amp tag <amp-install-serviceworker> should i go to the simplest way that mozilla teachs('https://developer.mozilla.org/pt-BR/docs/Web/Progressive_web_apps')? I'm lost in which should be optional and which shouldn't -
use thousand separator in Django Admin input form?
I want to use a thousand separator in input forms in Django admin; such that when you enter the price in the price box, a separator added to it. -
virtualenv doesnt see to be isolated
Created Virtualenv Says Permission Denied (sometimes ..would love a fix for this too) Activated it with sudo pip freeze shows entire packages from global Installing packages shows Requirement already satisfied -
Photo upload: direct s3 upload vs via Django Imagefield and custom storage
My requirement: Get user to upload profile photo. Make sure that the file that is uploaded is really an Image. Image size cannot be more than 2MB. My options: Directly upload image to s3 using presigned url. In this case I don't have to worry about server resources running out when traffic load increases. But I would not be able to determine for sure if the file is an image. Just checking the extension is not enough to determine if the file is an image. I can upload it to s3 via django app using ImageField and custom s3 storage. ImageField uses pillow to make sure if the uploaded file is really an image. But I have to worry about server resources running out when traffic load increases. Increasing server resources is not an option. My questions: For direct upload how can I make sure if the file being uploaded is really an image? For image upload via django, how to mitigate or optimize the resource running out problem? -
Django-import-export problem importing foreignkey field
I am using the Django-import-export(version 2.5.0) module in Django(version 3.1.4). So I am able to import all my models fields except for the ForeignKey field. I don't know how to make this one work. Can you look at my code and see what is wrong or needs to change? I need Django Admin to import the ForeignKey field. models.py # myapp from django.db import models from django.contrib.auth.models import User class Agency(models.Model): system_name = models.CharField(max_length=255) county = models.CharField(max_length=60) state = models.CharField(max_length=2) active = models.BooleanField(default=True) system_no = models.CharField(max_length=7, unique=True) def __str__(self): return self.system_no class SitePart(models.Model): # I tried changing the "system_no" to another name "agency_no" through out the *.py's this did not resolve the problem. Maybe I missed something. system_no = models.ForeignKey('Agency', on_delete=models.CASCADE, to_field='system_no', null=True, blank=True) part_name = models.CharField(max_length=125) status_tuple = [('AB','Abandoned'),('AC','Active Compliant'),('DS','Destroyed'),('IA','Inactive'), ('SB','Stand By waiting acitvation'),('MO','Monitoring')] status = models.CharField(max_length=2, choices=status_tuple, default= 'SB') # sys_site_n is unique sys_site_n = models.CharField(max_length=15, unique=True) def __str__(self): return self.part_name resources.py from import_export import fields, resources, widgets from import_export.widgets import ForeignKeyWidget from myapp.models import Agency, SitePart class AgencyResource(resources.ModelResource): class Meta: model = Agency import_id_fields = ('system_no',) fields = ('system_name', 'county', 'state', 'active', 'system_no',) class SitePartResource(resources.ModelResource): system_no = fields.Field( column_name='system_no', attribute='system_no', widget=ForeignKeyWidget(Agency,'system_no')) print(system_no) class Meta: model = SitePart … -
Django: If I already deployed my app and want to make a change, how I manage the static files?
I already deployed my Django app, but now I'd like to make some changes to it, and I'll edit some static files too. Once I redeploy the app, should I run python3 manage.py collectstatic or should I do something else? Thanks for your precious time! -
Update variable passed to template on change of the model
I have a view home as follows: from .models import ExistencePredictions def home(request): context = { 'latest_prediction': ExistencePredictions.objects.last() } return render(request, 'detection/home.html', context=context) The problem is that new data is added to ExistencePredictions every second or so. Is it possible to update the context of the view every time the model is changed so that the latest data is shown in the template without reloading the page? -
How to create media folder and fetch images to my html dynamically | Django |
I have create a small project , where i am stuck at one point Issue : not able to get images dynamically and display in html using jinja i.image.url -> at this line in html images are not coming from folder media when i runserver the media folder is not getting created and images are not copied from pics to media folder As i uploaded images and its content from 127.0.0.1/8000/admin Project structure: My HTML {% for i in getdetails %} <div class="col-xl-3 col-lg-3 col-md-6 col-sm-12"> <div class="product-box"> <i> <img src="{{ i.image.url }}"/> </i> <h3>{{ i.name }} </h3> <span>{{ i.price }}</span> </div> </div> {% endfor %} My database My seeting.py file : from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%g52q0hek460brm&!ty_)o5ucXXXXXXXXXXXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'LEARN_FROM_TELUSKO', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF … -
Static file not found in Django production
I am trying to deploy my Django project using Ubuntu and apache webserver. When I transferred my project to the Ubuntu web server and tested it in development, everything went fine. However when changed to production, I experienced file not found problem and I suspect this problem is related to my setings.py, but I am unable to troubleshoot it further. The error I see in production when accessing my site is: Environment: Request Method: GET Request URL: http://139.162.163.35/ Django Version: 3.1.3 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/views/generic/base.py", line 63, in view self = cls(**initkwargs) File "/home/jianwu/HD_website/website/index/views.py", line 57, in __init__ self.ContextObject.importTextFile('static/mainAboutUs.txt') File "/home/jianwu/HD_website/website/index/views.py", line 50, in importTextFile with open(filePath,'r') as fid: Exception Type: FileNotFoundError at / Exception Value: [Errno 2] No such file or directory: 'static/mainAboutUs.txt' In my Meta I have CONTEXT_DOCUMENT_ROOT '/var/www/html' CONTEXT_PREFIX '' CSRF_COOKIE 'jF3vdEgpyhbKxavRw3pEWzRdIjc4lvw0MsV4lpBLdYXPqcGcIVyH02kEuBeGSXlh' DOCUMENT_ROOT '/var/www/html' GATEWAY_INTERFACE 'CGI/1.1' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' HTTP_ACCEPT_ENCODING 'gzip, deflate' HTTP_ACCEPT_LANGUAGE 'da-DK,da;q=0.9,en-US;q=0.8,en;q=0.7,bg;q=0.6,zh-CN;q=0.5,zh;q=0.4' HTTP_CONNECTION 'keep-alive' HTTP_COOKIE 'csrftoken=jF3vdEgpyhbKxavRw3pEWzRdIjc4lvw0MsV4lpBLdYXPqcGcIVyH02kEuBeGSXlh' HTTP_HOST '139.162.163.35' HTTP_PURPOSE 'prefetch' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT … -
Can you use a class object as property in Django?
I have three models in my Django application - simplified for demonstration. The first one is Base. The second one is Bill and has foreign key "base" to Base model. The third one is Point, and has a foreign key to Bill. class Base(models.Model): type = models.CharField() desc = models.IntegerField() class Bill(models.Model): base = models.ForeignKey("Base", related_name="bills") total_value = models.DecimalField() class Point(models.Model): bill = models.ForeignKey("Bill", related_name="points) value = models.DecimalField() My goal is to have a property for Base called def bill(self), that would sum up all "bill" objects fields and returned a bill-like instance. I would like to get a base object: my_base = Base.objects.get() bill = Base.bill <-- I can figure this out with @property points = bill.points <-- this does not work through @property function. My current solution is like this, to get the first part working: class Base(): ... @property def bill(self): sums = self.bills.aggregate(total_value=Sum('total_value')) return Bill(**sums) The second part, that would sum up bill-related-points and return them in a my_base.bill.points, does not work. If I filter for points and try to assign them to Bill(**sums).points = filtered_points, I get an error: Direct assignment to the reverse side is prohibited, or Unsaved model instance cannot be used in … -
Node Js vs Django
I am just a 14 year old trying to learn web development I am fairly good with Django. And I recently heard of Node Js is it worth learning Node Js. Well, I wanted to make a live chatting website I wanted to know which would be better at making it. I also checked Firebase's real-time NoSQL Database as well but I heard some as it's not good when the project gets bigger. So is node js really worth learning? -
Salom Savolbor menda Pythondan
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 13, 2021 - 11:54:44 Django version 3.1.3, using settings 'school.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Shu narsani qande korsam bo`ladi? -
How to save model instance in Django through JavaScript in HTML
I am Building a BlogApp and I am stuck on a Problem What i am trying to do I made a instance named user_location in model. I accessed it in template and I write JavaScript code to access User's Location using JavaScript BUT i want my model instance to save the JavaScript's Output country in the Database. The Problem I don't know how to save model instance through JavaScript. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') user_location = models.CharField(mac_length=100,default'') profile.html <script> $.ajax({ url: "https://geolocation-db.com/jsonp", jsonpCallback: "callback", dataType: "jsonp", success: function(location) { $('#country').html(location.country_name); } }); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div>Country: <span id="country"></span></div> #This is my model instance. {{ profile.user_location }} What have i tried I also tried THIS. BUT it didn't work for me. I don't know what to do. Any help would be Appreciated. Thank You in Advance. -
Handling three forms on the same page with one having multiple instances - Django
I am working on an Invoice that has three forms of which one has multiple instances. The first two forms each has one instance and the last one can accommodate as many as the user wants. meaning the user will be adding instances of the last form using JavaScript. With the below code I am getting an error that is saying that the fields of the first two forms are missing data cause whenever the user add extra fields to the last form Django thinks I am also adding extra forms to the other two forms. Please help This is an example of the POST data with two extra fields for the last form: form-TOTAL_FORMS '2' form-INITIAL_FORMS '0' form-MIN_NUM_FORMS '0' form-MAX_NUM_FORMS '1000' form-0-number '215' form-0-customer '4' form-0-sales_person '1' form-0-product '2' form-0-quantity '20' form-0-price '20' form-1-product '2' form-1-quantity '40' form-1-price '50' This is my view.py def createInvoice(request): invoiceFormSet = formset_factory(InvoiceForm) retailPriceFormSet = formset_factory(RetailPriceForm, extra=2) saleItemFormSet = formset_factory(SaleItemForm) if request.method == 'POST': invoiceform = invoiceFormSet(request.POST or None) retailPriceform = retailPriceFormSet(request.POST or None) saleItemform = saleItemFormSet(request.POST or None) if invoiceform.is_valid() and saleItemform.is_valid(): for si in saleItemform: saleItem = si.save() saleItem_id = get_object_or_404(SaleItem, id=saleItem.id) for i in invoiceform: inv = i.save(commit=False) inv.sale_item = saleItem_id … -
Django Error: local variable 'fav' referenced before assignment
I got an error in Djang, When I try to pass the favourite_add to ajax I got local variable 'fav' referenced before assignment def favourite_add(request, id): data = {} video = get_object_or_404(Video, id=id) if request.method == "POST": account = request.user.id if video.favourites.filter(id=account.id).exists(): fav = False video.favourites.remove(account) else: video.favourites.add(account) fav = True data["fav"] = fav print(data) return JsonResponse(data) -
i get this error in django ProgrammingError at /admin/persona/empleado/add/
the runserver runs correctly, but when i'm in django admin and try to add an employee i get that error message I suspect that the error is in the models.ManyToManyField, because I could add employees and they were saved correctly in the database, the ManyToManyField options were added to the django manager but when trying to save I get the error message https://i.stack.imgur.com/gZnKX.jpg from django.db import models from applications.departamento.models import Departamento from ckeditor.fields import RichTextField class Habilidades(models.Model): habilidad = models.CharField('Habilidad', max_length=50) class Meta: verbose_name='habilidad' verbose_name_plural='habilidades empleado' def __str__ (self): return str(self.id) + '-' + self.habilidad JOB_CHOICES=( ('0', 'CONTADOR'), ('1', 'ADMINISTRADOR'), ('2', 'ECONOMISTA'), ('3', 'OTRO'), ) class Empleado(models.Model): Firts_name = models.CharField('Nombre', max_length=50) Last_name = models.CharField('Apellido', max_length=50) Job = models.CharField('Trabajo', max_length=1, choices=JOB_CHOICES) departamento = models.ForeignKey(Departamento, on_delete=models.CASCADE) habilidades = models.ManyToManyField(Habilidades) hoja_vida= RichTextField() def __str__ (self): return str(self.id) + '-' + self.Firts_name + '-' + self.Last_name -
I'm trying to add env var to django secret_key on github action but showing error
name: MoneyTracker Test on: push: branches: - master pull_request: branches: - master jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up python 3.7 uses: actions/setup-python@v2 with: python-version: 3.7 - name: Install dependency run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Lint with flake8 run: | pip install flake8 flake8 - name: Coverage report env: secret_key: ${{secrets.SECRET_KEY}} debug: ${{secrets.DEBUG}} db: ${{secrets.DB}} run: | pip install coverage coverage run MoneyTracker/manage.py test coverage report - name: Django testing run: | python3 MoneyTracker/manage.py test MoneyTracker Project link is in here. How should I add secret key to my project on GitHub action? Environment variables are case-sensitive. Commands run in actions or steps can create, read, and modify environment variables. To set custom environment variables, you need to specify the variables in the workflow file. You can define environment variables for a step, job, or entire workflow using the jobs. -
adding many to many relations is producing an empty queryset
I have a model called Occurrence with a number of foreign key and manytomany relationships (i've only shown a few fields here). I am having issues when attempting to create any manytomany relation to an Occurrence instance after I have loaded bulk data to my postgres (postgis) database using the sqlalchemy engine. Before this upload of data I can make relations as usual with: Occurrence.objects.get(ind='1010106').minmat.add(Material.objects.get(code='Li')) I then check the relation was successful with: Occurrence.objects.get(ind='1010106').minmat.all() which returns a queryset of all the relations. I have dropped the database and after a fresh migrations everything worked as it should, but once I reloaded the data which consists of tables up to 150,000 rows, I am no longer able to create these relations. No errors occur, but no additions are mad to the model instance after running add(). Here is the model: class Occurrence(models.Model): ind = models.CharField(max_length=14, blank=False, null=False, primary_key=True) majmat = models.ManyToManyField(Material, related_name="majmat_occurrence", blank=True,) geom = models.PointField(srid=4202) def __str__(self): return self.ind class Material(models.Model): code = models.CharField(max_length=6, primary_key=True) name = models.CharField(max_length=50, blank=False, null=False) category = models.ManyToManyField(MaterialCategory, related_name="category_material", blank=True) def natural_key(self): return self.name Everything works properly before loading the data, so I assume the issue lies with loading the data outside of django, but … -
How to access html's <span> into {{ variable accessor }}
I am Building a BlogApp and I am stuck on an Error. What i am trying to do I am trying to access <div>Place: <span id="place"></span></div> into {{ place }} or {% if place %} The Problem It is not accessing when i insert it in {{ place}} I don't know what to do. Any help would be Appreciated. Thank You in Advance -
Django model admin custom get_queryset pagination is not working
In my django code i am displaying user list with custom queryset: class UserAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(UserAdmin, self).get_queryset(request) qs.filter(is_staff=0,is_superuser=0) paginator = Paginator(qs, 5) qs = paginator.get_page(1) return qs i dont know what is getting wrong here but it is returning me the error like . KeyError: 'request' but when i remove the paginator from there it is working fine. here i want to use client side datatable pagimation for my user list .can anyone have any idea why i am getting this -
How can I update sqlite database in django without original migration files and preserve the data in db.sqlite3 at the same time?
I am a beginner in django. I accidentally deleted the original migration files and the only remaining related file is db.sqlite3. Now I made some changes to models.py and want to update my database while preserving the previous data in db.sqlite3. How can I do this? Will python manage.py makemigrations work? -
Django Project OperationalError at /admin/products/product/add/
So when I am trying to add a product and click save on the browser I get this error message. I don't know what to do, and have tried looking for solutions. I attached the error image to this link