Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django database information to html template
i am trying to fetch information from a psql database and i would like to export it to a html template, however i get a list, not an object or dict, so i can not call the properties of the information in the tempalte def myview(request): conn = psycopg2.connect(user="bogarr",password="Testing321",host="localhost",port="5432",database="LoginDatabase") try: cursor = conn.cursor() cursor.execute("select * from blog_post") rows = cursor.fetchall() finally: conn.close() context = { 'rows': rows } for row in rows: print("kecske: ", row[1]) return render(request,"blog/mytemplate.html", context) -
Django: Passing 'name' to Client.post()
I want to pass 'name' variable to request.POST.get() from Client in test in Django to be further processed by post function in view. Something like that(product is ChoiceField in form): response = c.post('/ordersys/orders/create/', {'product':product, 'amount':3}, name="Add") I want that if to be True when posting from Client: if request.POST.get("Add"): self.add_to_order(product, amount) In form, submit like that works: <input type="submit" name="Add" value="Add item to order"> -
Chart.js not working after Django deployment on Heroku
My Django site was working fine at localhost:8000 but when I uploaded to Heroku, the charts no longer show up. Is there any typical reason why this would be? The errors I received in the console were Uncaught Error: Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com and The page at 'https://...com/' was loaded over HTTPS, but requested an insecure script 'http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js'. This request has been blocked; the content must be served over HTTPS. -
how do i debug or add a relation
The above exception (relation "blog_blog" does not exist LINE 1: INSERT INTO "blog_blog" ("title", "pub_date", "body", "image... ^ ) was the direct cause of the following exception: /usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/views/decorators/cache.py, line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/sites.py, line 233, in inner return view(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 43, in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/utils/decorators.py, line 130, in _wrapped_view response = view_func(request, *args, **kwargs) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1580, in _changeform_view self.save_model(request, new_object, form, not add) … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/contrib/admin/options.py, line 1093, in save_model obj.save() … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/db/models/base.py, line 753, in save self.save_base(using=using, force_insert=force_insert, … ▶ Local vars /usr/local/lib/python3.9/site-packages/django/db/models/base.py, line 790, in save_base … -
success url does not work in my class based DeleteView
My success_url for my class based delete view does not work for some reason. in views.py # allows a user to delete a project class DeletePost(DeleteView): template_name = 'user_posts/post_delete.html' model = Post # return to the all posts list success_url = reverse_lazy('posts_list') # make sure the user is looking at its own post def dispatch(self, request, *args, **kwargs): obj = self.get_object() if not obj.user == self.request.user: raise Http404("You are not allowed to Delete this Post") return super(DeletePost, self).dispatch(request, *args, **kwargs) in urls.py: path('list/', PostsListView.as_view(), name="posts_list"), path('create-post/', CreatePostView.as_view(), name="post_create"), path('update-post/<int:pk>', UpdatePost.as_view(), name="post_update" ), path('delete-post/<int:pk>', DeletePost.as_view(), name="post_delete") in the HTML file: {% extends 'base.html' %} {% block content %} <form action="." method="POST" style="width:80%;"> {% csrf_token %} <h3>Do You want to delete this post: "{{ object.title }}"</h3> <input class="btn btn-primary" type="submit" value="Confirm"/> <a href="{% url 'posts_list' %}">Cancel</a> </form> {% endblock content %} whenever I click ok to delete a specific project, it doesn't return to the list of posts for: image of the error on the webpage -
TypeError at /api/register/ 'module' object is not callable
I am trying to register users using django rest framework but this is the error i am getting, Please help Identify the issue TypeError at /api/register/ 'module' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/api/register/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: 'module' object is not callable Exception Location: C:\Users\ben\PycharmProjects\buddyroo\lib\site-packages\rest_framework\generics.py, line 110, in get_serializer Python Executable: C:\Users\ben\PycharmProjects\buddyroo\Scripts\python.exe Python Version: 3.8.5 below is RegisterSerializer from django.contrib.auth.password_validation import validate_password from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user and RegisterView.py from django.contrib.auth.models import User from rest_framework import generics from rest_framework.permissions import IsAuthenticated, AllowAny # <-- Here from rest_framework.response import Response from rest_framework.views import APIView from api import UsersSerializer, RegisterSerializer class RegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = RegisterSerializer permission_classes = (AllowAny,) -
how to write serializer and view for this type output data format and save in database drf,mysql
{ "user_name": "admin", "raw_data_column": [ "UPC Code", "Label or Sublabel", "Server Wise" ] } -
password_reset does not pick from_email
I have my email setup for entire django project and it works fine. When it comes to reset password in the following url: http://127.0.0.1:8000/rest-auth/password_reset/ and after submitting the email, it throws: SMTPDataError at /rest-auth/password_reset/ (550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. when I digged into the issue I noticed that this view doesn't catch from_email at all: If I manually enter the email here, everything works fine. I am wondering what is gone wrong that email is not read! -
Django IOT project
I am working in a Django project building a web application with a few features one of them is showing data from sensor connected to ESP8266 on a page on the project how can I POST these data showing on arduino to the project to use them in an app? (project includes creating users with API token if it's important) -
Django form does'nt render even if the code seems alright
I am beginner to Django. I have just started learning basic forms and here is the code which does'nt work. The method specified for the form in form_page.html is POST, so accordingly in views.py it must render me form_page.html but instead it prints thanks which means it does'nt recognize the method as post and run the else code snippet.Can you help me fix it!! Views.py from django.shortcuts import render from django.http import HttpResponse from .forms import formname def index(request): return render(request,'index.html') def form_name_view(request): if request.method == 'POST': form=formname(request.POST) if form.is_valid: print('NAME:',form.cleaned_data['name']) print('email:',form.cleaned_data['email']) print('text:',form.cleaned_data['text']) return render(request,'form_page.html',{'form':form}) else: form=formname() return HttpResponse('thanks') form_page.html <!doctype html> <html lang='en'> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title> Basic forms </title> <head> <body> <h1>Fill out the form</h1> <div class="container"> <form method="POST"> {{form.as_p}} {% csrf_token %} <btn type="submit" class="btn btn-primary ">Submit</btn> </form> </div> </body> </html> forms.py from django import forms from django.core import validators class formname(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) urls.py from django.contrib import admin from django.urls import path from basicformsapp import views from django.conf.urls import url urlpatterns = [ url(r'^$',views.index,name='index'), path('admin/', admin.site.urls), url(r'^formpage/',views.form_name_view,name='form_name_view') ] -
How can I bundle my JSON API data into one dictionary?
I'm trying to package my API data into one GET request simply using standard libraries python. class GetData(APIView): def get(self, request, *args, **kwargs): urls = [url_1, url_2, url_3, url_4 ] data_bundle = [] for x in urls: response = requests.get(x, headers={'Content-Type': 'application/json'}).json() data_bundle.append(response) return Response(data_bundle, status=status.HTTP_200_OK) The return response has to be JSON data, I'm trying to get it to work but it seems like the response data seems to be overiding eachother? How can I properly create a JSON dictionary of dictionaries. I've tried switching data_bundle to an empty dictionary instead of a list. However that just caused an error saying: ValueError: dictionary update sequence element #0 has length 8; 2 is required Is there a simple way to accomplish this that I'm missing? Thank you for the help. -
Django. How to design model so not to have vertical repetition for common name and family name?
In the below model there are fields like name and family name that will be repeated. For example Jhon or Jack would be common name which are bound to repeat themselves. Is there any better way to avoid this or this is ok by normalization standards of data models designs? class PropertyOwner(models.Model): name = models.CharField(max_length=200) family_name = models.CharField(max_length=200) contact_number = models.PositiveIntegerField() email = models.EmailField() def __str__(self): return self.name Is the fact that some names and family names will repeat themselves be a problem or better way to do this? -
'NoneType' object has no attribute 'id' in Django
I get the 'NoneType' object has no attribute 'id' error when opening a URL which view is this one: @login_required def order_checkout_view(request): product_id = request.session.get("product_id") or None if product_id == None: return redirect("/") product = None try: product = Product.objects.get(id=product_id) except: return redirect("/") user = request.user order_id = request.session.get("order_id") order_obj = None new_creation = False try: order_obj = Order.objects.get(id=order_id) except: order_id = None if order_id == None: new_creation = True order_obj = Order.objects.create(product=product, user=user) if order_obj != None and new_creation == False: if order_obj.product.id != product.id: order_obj = Order.objects.create(product=product, user=user) request.session['order_id'] = order_obj.id form = OrderForm(request.POST or None, product=product, instance=order_obj) if form.is_valid(): order_obj.shipping_address = form.cleaned_data.get("shipping_address") order_obj.billing_address = form.cleaned_data.get("billing_address") order_obj.mark_paid(save=False) order_obj.save() del request.session['order_id'] return redirect("/success") return render(request, 'orders/checkout.html', {"form": form, "object": order_obj}) The exception location is in this line if order_obj.product.id != product.id: There's an existing product in the database, however does this mean in this case the Product is 'None'? What could be the problem here? -
Flatpickr datetime field showing the wrong date in Edit form
I am working on an EDIT form to amend a specific record from a PGSQL table. The widget works well to select and save date, but when the EDIT page loads, the Start date of the record is incorrect. Below i call the actual date as it is saved in PG and the same exercise using the FlatPicker widget <label>Start Date</label> <div> {{ restricted_name_obj.Restriction_Start_Date }} <input type="hidden" name="Restriction_Start_Date" required="" id="Restriction_Start_Date" fp_config="{&quot;value&quot;: &quot;{{ restricted_name_obj.Restriction_Start_Date }}&quot;, &quot;id&quot;: &quot;fp_14&quot;, &quot;picker_type&quot;: &quot;DATETIME&quot;, &quot;linked_to&quot;: &quot;fp_13&quot;, &quot;options&quot;: {&quot;value&quot;: &quot;{{ restricted_name_obj.Restriction_Start_Date }}&quot;,&quot;mode&quot;: &quot;single&quot;, &quot;dateFormat&quot;: &quot;Y-m-d H:i:S&quot;, &quot;altInput&quot;: true, &quot;enableTime&quot;: true}}" class="flatpickr-input" value="{{ restricted_name_obj.Restriction_End_Date }}"> </div> But for some reason, the year is correct (always but day, month and hours/minutes are incorrect. I suspect there might be a formating to do while passing data to the field, but how ? Here is how it looks : -
wy in DB table is not creating and showing this errors invalid foreignKey in Django
wy in DB table is not creating and showing this errors invalid foreignKey .IntegrityError: The row in table 'myecomapp_toplist' with primary key '2' has an invalid foreign key: myecomapp_toplist.subcategory_id contains a value '1' that does not have a corresponding value in myecomapp_subcategory.id. models.py class TopList(models.Model): image = models.ImageField(upload_to='ProductImg') title = models.TextField(max_length=500) discountpercentage = models.IntegerField(blank=True,null=True) discountPrice = models.IntegerField(blank=True,null=True) brandName = models.TextField(max_length = 100 , default='',null=True,blank=True) desc = models.TextField(max_length=5000 ,null=True,blank=True) finalprice = models.IntegerField(blank=True,null=True) category = models.ForeignKey(ProductCategory , on_delete=models.CASCADE , default=1) subcategory = models.ForeignKey(subcategory , on_delete=models.CASCADE , default=1) class ProductCategory(models.Model): name = models.CharField(max_length=20) @staticmethod def get_all_categories(): return ProductCategory.objects.all() def __str__(self): representtion of this model object return self.name class subcategory(models.Model): name = models.CharField(max_length=20) MainCategory = models.ForeignKey(ProductCategory , on_delete=models.PROTECT) def __str__(self): return self.name admin.py @admin.register(subcategory) class SubcategoryAdmin(admin.ModelAdmin): list_display = ['name'] @admin.register(FirstSliderData) class FirstsliderModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] @admin.register(TopList) class TodoListModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] -
Django: values_list(flat=True) but for multiple fields
I have a model, TestModel As far as I know, if I were to implement TestModel.objects.values_list('FieldA', flat=True) This results in [A,B,C,(...)] (a list) And doing this TestModel.objects.values_list('FieldA','FieldB') results in [(A,1),(B,2),(C,3),(...)] (a list of querysets) But is it possible to get a similar result to Flat=True but for multiple fields? So, if I were to use something like testQS = TestModel.objects.values_list('FieldA','FieldB') and call testQS['FieldA'], this will return [A,B,C,(...)] Likewise, calling testQS['FieldB'] will return [1,2,3,(...)] Basically, I want to get all the data from a certain field in a values_list with multiple fields without resorting to for loop or creating values_list multiple times for each field. -
Cannot see my object models in Django admin view
I'm a relative Noobie at Django and have an issue with the admin interface. I am not able to see any of my custom object models, but I can see only the 'Groups' (under Authentication & Authorization), and 'Users' objects (under my 'CrushIt' app) (based on 'abstractuser') I used the startproject script to create my project (wedgeit) and app (CrushIt), and have gone through all the tips in the Django admin documentation, to try to troubleshoot the issue (see below). I also went through all the queries from other users I could find, but I'm still stuck. P.S. I can see my models from the shell and can create instances also, but they don't appear in the admin interface. Any hints would be appreciated. First time posting here so apologies if I've done something very stupid :D > Generated by 'django-admin startproject' using Django 3.0.8. Project settings file settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CrushIt.apps.CrushItConfig', ] 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 = 'wedgeit.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] apps.py … -
python-logstash and python-logstash-async not working with django
I tried two libraries to send some logs from our Django backend to our logging server: python-logstash python-logstash-async Here are the things I also tried/verified: Verify the Ec2 security group is accepting on port tcp/5000 (logstash) Monitor traffic from local machine and logging server to verify any network traffic. Using nc I was able to verify test logs being send and receive to our logging server. Re-create a bare minimum django project to see if there is an issue from versioning I'm sending logs after running the manage.py runserver class AppConfig(AppConfig): name = 'app' def ready(self): logger.info('info local django logging ') logger.error('debug local django logging ') logger.debug('debug local django logging ') print('logging init') This are the similar links that I've already checked: python-logstash not working? How to use python-logstash on Django settings.py (python-logstash-async) LOGGING = { 'formatters': { 'logstash': { '()': 'logstash_async.formatter.DjangoLogstashFormatter', 'message_type': 'python-logstash', 'fqdn': False, # Fully qualified domain name. Default value: false. 'extra_prefix': 'dev', # 'extra': { 'environment': 'local' } }, }, 'handlers': { 'logstash': { 'level': 'DEBUG', 'class': 'logstash_async.handler.AsynchronousLogstashHandler', 'transport': 'logstash_async.transport.TcpTransport', 'host': 'my.remote.host', 'port': 5000, 'ssl_enable': False, 'ssl_verify': False, 'database_path': 'memory', }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True, }, }, } Logstash … -
Change file name upload image in Django
Im having a trouble on how can I rename my image file to prevent duplication of filename. Currently I have a list of photos which can upload the filename to the database and it will automatically create folder and save those selected photos to my media folder. All I want is every image filename must be unique. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance views.py @login_required(login_url='log_permission') def scanned_docs_add(request): if request.method == 'POST': gallery = folder_info.objects.create( title = request.POST.get('title'), date_upload = datetime.date.today() ) for file in request.FILES.getlist('photos[]'): #imagefile-------- oas = gallery_photos.objects.create( gallery_info_id = gallery.id, photos = file, ) return JsonResponse({'data': 'success'}) models.py class folder_info(models.Model): title = models.CharField(max_length=50,blank=True, null=True) date_upload = models.DateField(null=True, blank=True) class Meta: db_table = "folder_info" class gallery_photos(models.Model): gallery_info_id = models.IntegerField() photos = models.FileField(upload_to='Photos/', unique=True) class Meta: managed = False db_table = 'gallery_photos' html <form id="uploadevent" > {% csrf_token %} <input type="file" multiple data-bind="fileInput: multiFileData, customFileInput: { }" accept="image/*" name="photos[]" required=""> <button type="submit" class="btn btn-outline-primary">Save changes</button> </form> Script <script type="text/javascript"> $('#uploadevent').on('submit', function(e){ $.ajax({ data : new FormData(this), url : "{% url 'scanned_docs_add' %}", type : 'POST', cache : false, contentType : false, processData : false }) … -
Django error 'WSGIRequest' object has no attribute 'request'
i made function of delete a student, it works but messages.info(self.request, student.name + ' blah blah blah ', extra_tags='danger') in views.py makes an error, error is 'WSGIRequest' object has no attribute 'request' Thank you guys and Happy new year ! my views.py class StudentUpdate(UpdateView): model = Student template_name = 'student/list_edit.html' context_object_name = 'student' form_class = AddStudent def form_valid(self, form): student = form.save(commit=False) student.save() return super().form_valid(form) . . . . . def delete_student(self, pk, school_year): student = get_object_or_404(Student, school_year=school_year, pk=pk) messages.info(self.request, student.name + ' blah blah blah ', extra_tags='danger') student.delete() return reverse('student_detail', kwargs={'pk':pk,'school_year':school_year}) my html function deleteconfirm(){ $('.delete-message').dialog({ dialogClass:"confirm-modal", modal: true, buttons: { "delete": function() { $(location).attr("href"," {% url 'delete_student' student.school_year student.pk %} "); }, "cancel": function() { $(this).dialog('close'); }, }, . . . . my urls.py urlpatterns = [ . . . . . path('student/<school_year>/<pk>/delete/', views.StudentUpdate.delete_student, name='delete_student'), ] -
How to restrict FloatField dynamically in Django?
I want restriction of weight(FloatField in redirectLink), max_value will change dynamically. But can not understand how can I implement those codes in CreateView or in Models.py. Here is my code: models.py class MinMaxFloat(models.FloatField): def __init__(self, min_value=None, max_value=None, *args, **kwargs): self.min_value, self.max_value = min_value, max_value super(MinMaxFloat, self).__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'min_value': self.min_value, 'max_value' : self.max_value} defaults.update(kwargs) return super(MinMaxFloat, self).formfield(**defaults) class redirectLink(models.Model): parameter = models.ForeignKey(shortenUrl, on_delete=models.CASCADE) url = models.URLField() country = CountryField(multiple=False, blank=True, null=True) weight = MinMaxFloat(min_value=0.0, max_value=1.0) My question is how can I add max_value restriction as below in CreateView or in Models.py? max_value = redirectLink.objects.filter(parameter=Shortenurl).aggregate(Sum('weight')).weight__sum #Shortenurl is a specific parameter -
Websockets with Django Channels on Heroku
I am trying to deploy my app to heroku. The app has a simple chatting system that uses Websockets and django channels. When I test my app using python manage.py runserver the app behaves just as intended. I tried deploying the app and all features work except for the chatting system. Here is the error message I am getting in the Chrome Console: layout.js:108 Mixed Content: The page at 'https://desolate-lowlands-74512.herokuapp.com/index' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://desolate-lowlands-74512.herokuapp.com/ws/chat/19/'. This request has been blocked; this endpoint must be available over WSS. This is what I tried to fix it: I went from ws to wss I changed this: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + friendship_id + '/' ); console.log(chatSocket) to this: const chatSocket = new WebSocket( 'wss://' + window.location.host + '/ws/chat/' + friendship_id + '/' ); console.log(chatSocket) with this change the websocket loads but the chatting system still doesn't work. The messages still don't get sent or received This is the error message I get when opening the Chatbox: layout.js:108 WebSocket connection to 'wss://desolate-lowlands-74512.herokuapp.com/ws/chat/19/' failed: Error during WebSocket handshake: Unexpected response code: 404 and this is the error message I … -
Django, Docker, postgreSQL Accepting TCP/IP connections on port 5432?
I I am using Docker and I got this message : Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Here is my docker-compose : version: '3.7' services: web: container_name: web build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/web/ ports: - 8000:8000 - 3000:3000 stdin_open: true depends_on: - db db: container_name: db image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=admin - POSTGRES_PASSWORD=pass - POSTGRES_DB=mydb - POSTGRES_HOST=localhost volumes: postgres_data: I precise I change the value of the parameter 'HOST' in the settings.py to db but it does not work I still have this error. Could you help me please ? -
Is possible to implement this function with a single django ORM query?
I'm making an aggregate report of stores, categories and customers for an ecommerce. Basically, I'm trying to achieve what this function does: from django.db.models import ExpressionWrapper, DecimalField, F, Sum from .models import Order def get_report_data(stores, categories, customers): result = [] for store in stores: for category in categories: for customer in customers: total = Order.objects.filter( store=store, orderitem__product__category=category, customer=customer, ).aggregate( total=Sum( ExpressionWrapper( F("orderitem__product__price") * F("orderitem__quantity"), output_field=DecimalField(), ) ) )["total"] result.append([store, customer, category, total]) return result Obviously, this is efficiently poor and I'm trying to turn this function into a query. I've tried the following, but I know I'm missing the mark by A LOT. total = ( Order.objects.filter( store__in=stores, customer__in=customers, orderitem__product__category__in=categories, ) .values("store", "orderitem__product__category") .annotate( total=Sum( ExpressionWrapper( F("orderitem__product__price") * F("orderitem__quantity"), output_field=DecimalField(), ) ) ) ) How should I proceed? Thank you very much! -
Django chained/dependant dropdown
I'm making a project in which I need to implement a chained dropdown, the users select first their state, then their County, and then their Neighborhood, I've been looking into a lot of options and all of them are for either only two selects (like country then city), or for a function based view, and replicating this code in my class based view it isn't working. I'd very much appreciate any help. I'm new to Django. Here are my models for location.models.py: class Estado(models.Model): estado = models.CharField(max_length=100) def __str__(self): return self.estado class Municipio(models.Model): municipio = models.CharField(max_length=100) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.municipio class CP(models.Model): cp = models.CharField(max_length=100) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.cp class Colonia(models.Model): colonia = models.CharField(max_length=100) cp = models.ForeignKey(CP, on_delete=models.CASCADE) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, on_delete=models.CASCADE) def __str__(self): return self.colonia As for where I want to implement it, is in the Posts model, here are all the relevant codes, I think: models.py class PostRoom(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author') colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=False, null=True) cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=False, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=False, null=True) views.py: class RoomSubmitCreateView(LoginRequiredMixin, CreateView): model = PostRoom …