Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Type error str in not callable python3 django models.py
I checked other problems and solutions in stack, but everywhere problem exists in views.py or urls.py like I understood. Now I,ve got only model.. Sorry for my English, but I'm learning now also :( (yes, yes too late) Where is my problem? below I paste traceback and models.py. Is this enough? If I broken every rules on stackoverflow I'm sorry, this is my first post, please correct me. It will be great help for me. Thank for the Help! from django.db import models from django.db.models.fields.related import ForeignKey class DeviceType(models.Model): """Model representing a device type.""" type_device_name = models.CharField(max_length=100) short_name_device= models.CharField(max_length=7, default='Maszyna') who_is_made = models.CharField(max_length=100) additional_notes = models.TextField(max_length=1000, help_text="Type all important information about.") def __str__(self): """String for representing the Model object.""" return f'{self.short_name_device}' class Device(models.Model): """Model representing a device.""" type_name = models.ManyToManyField(DeviceType, help_text='Select a device type') device_id = models.DecimalField(max_digits=4, decimal_places=0) short_name_device_own = ForeignKey(DeviceType, related_name='device_type_device', on_delete=models.SET_NULL, null=True) prod_year = models.DateTimeField(auto_now=False, auto_now_add=False) worked_science = models.DateField(auto_now=False) @property def __str__(self): """String for representing the Model object.""" return f'{self.short_name_device_own}, {self.device_id},' Traceback: File "/home/robert/.local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/robert/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/robert/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/robert/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File … -
Custom template tag rise error "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet."
I'm tying to create template filter, which will take value and search it in my model import django django.setup() tried this it didn't help Here is my code from catalog import models from django import template, shortcuts register = template.Library() @register.filter(name='test') def test(value): item = shortcuts.get_object_or_404(models.Equipment, pk=value) return item.name And i get this error File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\templatetags\catalog_custom_tags.py", line 1, in <module> from catalog import models File "C:\Users\mro\PycharmProjects\EuroWeb\catalog\models.py", line 4, in <module> class EquipmentCategory(models.Model): and Apps not loaded error File "C:\Users\mro\PycharmProjects\EuroWeb\venv\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. whole traceback is to big to post it here -
Why html skips my variable and how can I fix it?
views.py ... def home(request): data = { 'title':'Main page' } ... home.html ... <title>{{ title }}</title> ... browser page => show code ... <title></title> ... Why he just skipped title? It definitely worked in the tutorial. -
How to filter best related and create in one query?
I want to select best related object and save new one in one query to avoid race condition. Is it possible? Does select_for_update solves this problem? class Order(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2, default=0) maker_order = models.OneToOneField('self', on_delete=models.CASCADE, blank=True, null=True, related_name='taker_order') def save(self, *args, **kwargs): self.maker_order = Order.objects.filter(maker_order__isnull=True, taker_order__isnull=True, price__lte=self.price ).order_by('price').first() super().save(*args, **kwargs) -
How correct open connections to database in Python/Django
I want know how open correctly new connection to database. A problem rise when i want create single QUERY to database, from many places in my code. For example, one request is sent to database from login.html , second from register page, third to gallery in index.html . I guess , should i use some project patterns? Do you have some suggestion ? I have written this class which are responsible for connection to mysql database. I suppose that it is very wrong (i don't focus yet on validation - but i know about that): import mysql.connector import configparser class DataBaseConnectionHandler(object): __DATABASE = "" user = "" passwd = "" host = "" fileName = "" dataBaseConnection = "" def __init__(self, fileName=None, host='localhost'): if fileName is not None: config_file = configparser.ConfigParser() config_file.read('shop/config/dbConfig.ini') database: str = config_file.get('DEFAULT', 'database') user: str = config_file.get('DEFAULT', 'user') password: str = config_file.get('DEFAULT', 'password') self.__DATABASE = database self.user = user self.passwd = password self.host = host def connectToDatabase(self): """ EXECUTE CONNECTION AND RETURN AN HOOK TO DATABASE""" dataBaseConnector = mysql.connector.connect( host=self.host, user=self.user, passwd=self.passwd, database=self.__DATABASE ) if dataBaseConnector != "": self.dataBaseConnection = dataBaseConnector return self.dataBaseConnection else: self.dataBaseConnection = None return self.dataBaseConnection from .databses import DataBaseConnection class RegisterUser(object): __formName … -
Set ordering of Apps and models in Django admin dashboard
By default, the Django admin dashboard looks like this for me: I want to change the ordering of models in Profile section, so by using codes from here and here I was able to change the ordering of model names in Django admin dashboard: class MyAdminSite(admin.AdminSite): def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site. """ ordering = { "Users": 1, "Permissions": 2, "Activities": 3, } app_dict = self._build_app_dict(request) # a.sort(key=lambda x: b.index(x[0])) # Sort the apps alphabetically. app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower()) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: ordering[x['name']]) return app_list mysite = MyAdminSite() admin.site = mysite sites.site = mysite new look and feel: But as you see, I have lost the AUTHENTICATION AND AUTHORIZATION section; What should I do to have all the sections and at the same time have my own custom ordering for Profile section? -
S3 old uploaded image displayed with django-storages - deactivate caching?
When uploading a file I want to overwrite the existing file. I save all files with the same name. The upload to S3 seems to work but the new image is not displayed. I think, this is due to S3 caching making images (saved under the same name) available after 24h? I want to disable that cashing when uploading a new file with boto3 and django-storages but I can't seem to figure out how this works? I the docs I find this parameter, but is does not seem to work: AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } -
Unable to reach Django channels with Apache
I just deployed a Django Project on an Ubuntu server with Apache. Everything worked fine but I am unable to connect to the websocket.. I also enabled Proxy and put ProxyPass into the apache config file but still nothing. What way would be the most efecient? I also have a .app domain that only acceseble through https, so should I use wss in the config file and also to access the WebSocket? And If I run it on the same server as the main Django project in the settings it should be localhost as a server right? -
AttributeError: 'Manager' object has no attribute 'all_with_related_persons_and_score'
File "/home/syed007/PYTHON/myprojects/MyMDB/django/core/views.py", line 60, in MovieDetail queryset = Movie.objects.all_with_related_persons_and_score() AttributeError: 'Manager' object has no attribute 'all_with_related_persons_and_score' I'm using Django 2.2.4 on Python 3.6 when run "python3 manage.py makemigrations core", got the above error then changed the views script and that worked. But we cannot make views. However that created my models. But again, when running the command,"python3 manage.py runserver", got this error -- from django.db import models from django.conf import settings from django.db.models.aggregates import Sum class MovieManager(models.Manager): def all_with_related_persons(self): qs = self.get_queryset() qs = qs.select_related('director') qs = qs.prefetch_related('writers', 'actors') return qs def all_with_related_persons_and_score(self): qs = self.all_with_related_persons() qs = qs.annotate(score=Sum('vote__value')) return qs ` -
Django pre-selected checkbox with forms
I have two dropdown menus that depend on each other. In the first drop-thorn the annual number of maintenance can be selected. In the second dropdown menu the corresponding intervals can be selected. Now I would like to store the actual maintenance months in the database with preselected checkboxes. For this, I have created a table with the entire months of a year and established many too many relationships with the possible intervals. How can I preselect the checkboxes depending on the interval possibilities? I hope it is understandable and thank you for your help. Here is my code: models.py ss Systems(models.Model): systemUUID = models.CharField(max_length=30) idNum = models.CharField( max_length=50) postalcode = models.CharField(max_length=10, blank=True) city = models.CharField(max_length=50, blank=True) street = models.CharField(max_length=150, blank=True) fitter_mailaddress = models.EmailField(blank=True) general_mailaddress = models.EmailField() author = models.ForeignKey(User, on_delete=models.CASCADE) personnel_maintenance_per_year = models.ForeignKey(Personnel_maintenance_per_year, on_delete=models.SET_NULL, null=True) select_the_maintenance_months = models.ForeignKey(Select_the_maintenance_months, on_delete=models.SET_NULL, null=True) jan = models.BooleanField() feb = models.BooleanField() mar = models.BooleanField() apr = models.BooleanField() may = models.BooleanField() jun = models.BooleanField() jul = models.BooleanField() aug = models.BooleanField() sep = models.BooleanField() oct = models.BooleanField() nov = models.BooleanField() dec = models.BooleanField() def __str__(self): return self.systemUUID def get_absolute_url(self): return reverse('systems-detail', kwargs={'pk': self.pk}) form.py (currently not used) class SystemForm(forms.ModelForm): class Meta: model = Systems fields = … -
Django - I need help fixing this NoReverseMatch error
I'm following this tutorial upload multiple images to individual model objects within an object creation form. The main difference between my code and the tutorials is that I've changed the word 'photos' to 'images' for consistency with the rest of my project. Here is my views.py for the Upload form. class CarCreate(CreateView): model = Car fields = '__all__' success_url = reverse_lazy('showroom:car-detail') slug_field = 'id' slug_url_kwarg = 'car_create' def get(self, request): image_list = Car.objects.all() return render(self.request, 'showroom/car_form.html', {'images': image_list}) def post(self, request): form = ImageForm(self.request.POST, self.request.FILES) if form.is_valid(): image = form.save() data = {'is_valid': True, 'name': image.file.name, 'url': image.file.url} else: data = {'is_valid': False} return JsonResponse(data) The relevant template markup: <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span>Upload images </button> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'showroom:images:image_upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> Here is the error raised: Exception Type: NoReverseMatch at /showroom/create/ Exception Value: 'images' is not a registered namespace inside 'showroom' After reading through other Stackoverflow answers, I've tried a few different solutions: 1. It's not a namespacing error since I've already attached the 'showroom:images'. 2. The problem resides within: 'data-url="{% url 'showroom:images:image_upload' %}"' I know because if I change the data-url to '#', the page loads … -
Django rest framework csv renderer doesn't render €(EUR) sign correctly
I am using django-rest-framework-csv(https://github.com/mjumbewu/django-rest-framework-csv/) to download csv from api. Problem is when I write row with € sign, I get it like this in excel: Code: renderer = CSVRenderer() renderer.header = ['last_name', 'first_name', 'nutrition_text', 'monthly_total_price'] renderer.labels = { 'last_name': 'Nachname', 'first_name': 'Vorname', 'nutrition_text': 'Ernährung', 'monthly_total_price': 'Monthly total price' } data = [ {'last_name': 'asdasd', 'first_name': 'asdas', 'nutrition_text': '', 'monthly_total_price': ''}, {'last_name': 'Delic', 'first_name': 'Mirza', 'nutrition_text': '', 'monthly_total_price': '-18.00€'} ] response = HttpResponse(renderer.render(data), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Data.csv"' return response Excel screenshot: Also, Ernährung is not good in excel. Any solution for this? -
Decoding error when uploading file from Flutter frontend to Django backend
I would like to upload an image from flutter frontend to a python (django) server. I've been trying to debug this for longer than I'd like to admit. There are no resources online which show how to handle uploading a file from Flutter to Django backend. The backend is receiving the file, but I'm getting a UTF-8 decoding error when the file is being saved to local storage. This is the specific error I get when I try to upload an image: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. This is the file information as it is received by the backend: {'file': <_io.BytesIO object at 0x7fe121a44f50>, '_name': 'tempProfilePic.jpg', 'size': 311489, 'content_type': 'application/octet-stream', 'charset': None, 'content_type_extra': {}, 'field_name': 'file'} Below is my frontend code: if (_imageFile != null) { var stream = http.ByteStream(DelegatingStream.typed(_imageFile.openRead())); var length = await _imageFile.length(); var multipartFile = http.MultipartFile('file', stream, length, filename: basename(_imageFile.path)); request.files.add(multipartFile); } request.fields['token'] = token var response = await request.send(); _imageFile is a File variable which contains a .png image saved in storage. The file is sent without any error. Below is my backend code: models.py class userData(models.Model): profilePic = models.FileField(upload_to='documents/') token = models.CharField() And the view element which … -
i used the virtualenv venv command after installing django in my desired folder faced an error how to resolve this
D:\django>virtualenv venv Using base prefix'c:\users\admin\programs\python\python37' New python executable in D:\django\venv\Scripts\python.exe ERROR:the executable D:\django\venv\Scripts\python.exe is not functioning it tells the program cant start bcz VCRUNTIME140.dll is missing from my computer how do i reinstall and fix this problem -
django doesn't work with mongoengine, restframwork
i'm developing django restframework webpage using mongodb. I used sample source link from https://leadwithoutatitle.wordpress.com/2018/03/21/how-to-setup-django-django-rest-framework-mongo/ and this source worked well in my office django env. but when I run this source in my home, I doesn't work with this error enter image description here my settings.py part DATABASES = { 'default': { 'ENGINE': '', } } from mongoengine import connect MONGO_DATABASE_NAME = 'djangoDB' MONGO_HOST = '127.0.0.1' MONGO_PORT = 27017 connect(MONGO_DATABASE_NAME, host=MONGO_HOST, port=MONGO_PORT) and my pc django env. is like below. mongodb 4.2.0(win 64) python 3.7.3(64bit) Django 2.2.3 django-rest-framework-mongoengine 3.4.0 djangorestframework 3.10.3 mongoengine 0.18.2 -
Django can't find the static files
I just started a new project and currently Django can't find the static files. I'm using Django==2.2.6 The static files are located in an app called "website". This is the file structure. https://i.imgur.com/AnPACop.png This is from the settings: STATIC_URL = '/static/' -
How can I access to request.header in post_delete of models.signals
In post_delete of models.signals, I want send a request to other server to notify about this action, but I have a problem when I try to get some info from request.headers(ex: clientId send from client), please help me about this problem Thank you. -
class has no 'objects' member
so im new in django and im trying to make a small market. i made a product app. this is the inside codes: this is for views.py: from django.shortcuts import render from django.http import HttpResponse from products.models import product def index(request): Products = product.objects.all() return render(request, 'index.html', {'products': Products}) def new(request): return HttpResponse('New Product') this is for models.py: from django.db import models class product(models.Model): name = models.CharField(max_length=150) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) i also made a template folder and put this in it for experiment: <h1>Products</h1> <ul> {% for product in Products %} <li>{{ product.name }}</li> {% endfor %} </ul> and some other usual codes. but i get a error for this part: product.objects.all() please help me! thanks -
what does "verbose_name", "verbose_name_plural" , "index_together" do?
I am exploring a github project , but could understand what "verbose_name", "verbose_name_plural" , "index_together" doing? class Meta: verbose_name = "Payable To Person" verbose_name_plural = "Payable To Persons" index_together = ["organization", "status"], -
invalid: Syntax of transaction amount is incorrect. Should contain digits up to two decimal points
views.py 'MID': 'kdwQnP13817196283144', 'ORDER_ID': str(order.id), 'TXN_AMOUNT': str(Order.get_total_cost), 'CUST_ID': (order.email), 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL':'http://127.0.0.1:8000/payment/handleRequest/', models.py class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) get_total_cost = models.DecimalField(max_digits=10, decimal_places=2) phone = models.CharField(max_length=10, default="") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) https://www.facebook.com/photo.php?fbid=526521448115167&set=a.526521514781827&type=3&theater -
JS: alert input value from programatically generated input classes
I'm using Django as Backend. In my template I'm generating input fields for each item, and for now I'm just trying to alert the values in this fields when user clicks a link: Agregar al Carrito. Right now, it only works for only 1 of the three items. This is somehow illogic, as the logic is the same for all the items. It should work for all or for none, but not for some yes and not for others. Codepen: https://codepen.io/ogonzales/pen/YzzzYdd Code: <div class="container-fluid mt-3"> <div class="row justify-content-center"> {% for unitary_product in object_list %} <div class="col-auto mb-3"> <div class="card" style="width: 18rem;"> <a class="btn" data-toggle="modal" href="#FullImage{{ unitary_product.slug }}"> <img class="card-img-top" src="{{ unitary_product.image.url }}" alt="Card image cap" width="100" height="200"> </a> <div class="card-body"> <h5 class="card-title">{{ unitary_product.name }}</h5> <p class="card-text">Tamaño: {{ unitary_product.size }}</p> <p class="card-text"><b>Precio: S/ {{ unitary_product.price }}</b></p> <label for="tentacles"><b>Cantidad: </b></label> <input type="number" class="unitary_product_quantity_for_{{ unitary_product.slug }}" name="unitary_product_quantity_for_{{ unitary_product.slug }}" value="{{ unitary_product.quantity }}"> <a class="margin-top10 btn btn-azul text-white btn-block agregar-unitary-product-btn-for-{{ unitary_product.slug }}">Agregar al carrito</a> </div> <div class="card-footer"> <small class="text-muted">Creado el: {{ unitary_product.created }}</small> </div> </div> <!-- ### AJAX TO SEND QUANTITY --> <script> function get_unitary_product_quantity_for_{{ unitary_product.slug }}() { var unitary_product_quantity_for_{{ unitary_product.slug }} = $('.unitary_product_quantity_for_{{ unitary_product.slug }}').val(); alert(unitary_product_quantity_for_{{ unitary_product.slug }}); return unitary_product_quantity_for_{{ unitary_product.slug }}; // … -
how to make a django virtual environment using cmd or powershell?
As you can see the terminal in pycharm easily lays the foundation for creating a django project. but in powershell(cmd either) I see this.... so how should i run the command to make it work in powershell or cmd either ? is there any other way to make me able (not to be confined in pycharm terminal) to do the same with powershell and cmd ? -
How to get to another page after saving form by CreateView
I wan't to get to order_list page after adding new order. Was trying both reverse and reverse_lazy method also just to set page adres value to success_url directly like success_url = 'orders/order_list' or sucess url = 'order_list' but it always returns me Http 405 error. views.py django.shortcuts import render from django.urls import reverse_lazy from django.views import View from django.views.generic import ListView, DetailView, CreateView from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin from .models import Order from .forms import CreateOrder from django.contrib.auth.decorators import login_required # Create your views here. class OrderCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): login_url = '/login_required' permission_required = 'orders.add-order' model = Order success_url = reverse_lazy('orders:order_list') fields = ['airport', 'direction', 'adress', 'client', 'telephone', 'flight_number', 'plane', 'pick_up', 'gate', 'driver'] urls.py from django.contrib import admin from django.urls import path from django.contrib.auth import views as auth_views from orders.views import OrderCreateView, OrderListView, AboutView, LoginRequiredView urlpatterns = [ path('admin/', admin.site.urls), path('add_order/', OrderCreateView.as_view(template_name="orders/add_order.html"), name="add_order"), path('order_list/', OrderListView.as_view(), name="order_list"), path('login/', auth_views.LoginView.as_view(template_name="pages/login.html"), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name="pages/logout.html"), name="logout"), path('about/', AboutView.as_view(), name="about"), path('login_required/', LoginRequiredView.as_view(), name='login_required') ] add_order.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="container" style="width: 40%; height: 80%;"> <div class="page header"> <h1>Add new order</h1> </div> <form action="/order_list/" method="post"> {% csrf_token %} … -
return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: m
You have 8 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): myapp3. Run 'python manage.py migrate' to apply them. class STUDENTMARKSHEETDATA(models.Model): username=models.CharField(max_length=100,unique=True) dof=models.DateTimeField(max_length=100) reg_no=models.IntegerField() graph_theory=models.CharField(max_length=100) autometa_theory=models.CharField(max_length=100) data_mining=models.CharField(max_length=100) dsp=models.CharField(max_length=100) networking=models.CharField(max_length=100) computer_graphics=models.CharField(max_length=100) grade_S=models.CharField(max_length=100) grade_A=models.CharField(max_length=100) grade_B=models.CharField(max_length=100) grade_C=models.CharField(max_length=100) grade_D=models.CharField(max_length=100) grade_E=models.CharField(max_length=100) grade_U=models.CharField(max_length=100) code_962=models.IntegerField() code_302=models.IntegerField() code_303=models.IntegerField() code_903=models.IntegerField() code_301=models.IntegerField() code_304=models.IntegerField() branch_cse=models.CharField(max_length=100,default='00000') # gender=models.CharField(max_length=100) # degree=models.CharField(max_length=100, unique='aaaaa') def str(self): return self.username -
Connect to local mysql database from django app docker
I'm trying to dockerize my Django app with Docker, but having some trouble connecting with the mysql database since i'm not really experienced with Docker. I have a couple questions: I have installed mysql and set up the database locally on my computer, do i have to use a mysql image and create a db service in my docker-compose too ? Shouldn't Django connect to mysql normally like it did when it wasn't dockerized ? If a database is hosted on a server then is mysql installed on that server ? Do i have to use a mysql image to connect to the database ? Here is my docker-compose.yml: version: '3.7' services: web: build: ./appchat command: python appchat/manage.py runserver ports: - 8000:8000 - "3306" network_mode: "host" And here is the database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'PASSWORD': 'root', 'NAME': 'company', 'PORT': '3306', } } Here is the error when i ran docker-compose file: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Any help would be appreciated. Thank you.