Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wrong configuration for database in seetings.py or docker
I'm learning how to work with Compose + Django using this manual https://docs.docker.com/compose/django/ Here are my configuration files docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } When I run using docker-compose up everything is fine. But when I run using python manage.py runserver I got this error psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known Guess, I have wrong cofiguration -
DRF polymorphic many-to-many with extra fields
I'm tinkering around with Django Rest Framework to build an api that can handle Bills of Materials (BoM) of electronic components. I'm using django-polymorphic and django-rest-polymorphic so I can use polymorphic models for the components (they have shared attributes, but I still want to handle them in much the same way. The polymorphic models are great for this purpose). All is well and good until I introduce many-to-many relations with a 'through' attribute. What I would like is a BoM that has several different components, each with a quantity, e.g. BoM1 has 2x470k resistor & 3x 100uF capacitor. models.py: (pruned a bit to keep this post from being an epic novel) class BoM(models.Model): """Bill of Materials: a list of all parts and their quantities for a given pedal""" pedal = models.ForeignKey(Pedal, on_delete=models.CASCADE) variant = models.CharField(max_length=100, blank=True) electronic_components = models.ManyToManyField( 'ElectronicComponent', through='ElectronicComponentQty', blank=True) class Meta: verbose_name = 'Bill of materials' verbose_name_plural = 'Bills of materials' def __str__(self): return str(self.pedal) class ElectronicComponent(PolymorphicModel): """Shared data model for electronic components""" value = models.CharField(max_length=20) datasheet = models.FileField(upload_to='uploads/components', blank=True) def __str__(self): return self.value class ElectronicComponentQty(models.Model): """Combination of resistor and quantity""" bom = models.ForeignKey(BoM, on_delete=models.CASCADE) component = models.ForeignKey( ElectronicComponent, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) class Meta: verbose_name = … -
Django: Problem in doing complex annotation
This is model: class Purchase(models.Model): date = models.DateField(default=datetime.date.today,blank=False, null=True) total_purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True) I want to perform a month wise calculation of "total_purchase" within a specific daterange in such a way that if there is no purchase in a month the total purchase should be the previous month purchase value And if there is purchase in two months then total purchase will the addition of those two... Example: If there is a Purchase of $2800 in month of April and $5000 in month of August and $6000 in month of October.. Then the output will be like this: April 2800 May 2800 June 2800 July 2800 August 7800 #(2800 + 5000) September 7800 October 13800 #(7800 + 6000) Any idea how to perform this in django queries? Thank you -
How do I reduce the amount of queries of my Django app?
My app is currently making over 1000 SQL queries and taking around 20s to load the page. I can't seem to find a way to come up with a solution to get the same data displayed on a table in my template faster. I wan't to display 100 results so that's way my pagination is set to 100. these are the methods in my my models.py used to get the count and sum of the orders, these two are in my Company model and the get_order_count is also in my Contact model def get_order_count(self): orders = 0 for order in self.orders.all(): orders += 1 return orders def get_order_sum(self): total_sum = 0 for contact in self.contacts.all(): for order in contact.orders.all(): total_sum += order.total return total_sum views.py class IndexView(ListView): template_name = "mailer/index.html" model = Company paginate_by = 100 and here is the table body in my template {% for company in company_list %} <tr id="company-row"> <th id="company-name" scope="row">{{ company.name }}</th> <td>{{ company.get_order_count }}</td> <td id="order-sum">{{ company.get_order_sum|floatformat:2 }}</td> <td class="text-center"> <input type="checkbox" name="select{{company.pk}}" id=""> </td> </tr> {% for contact in company.contacts.all %} <tr id="contact-row"> <th scope="row">&nbsp;</th> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td id="contact-orders"> Orders: {{ contact.get_order_count }} </td> <td></td> </tr> {% endfor … -
Configuring Traefik, Caddy, and Gunicorn inside Docker using docker-compose
I'm a beginner. I have gone through the tutorial on Docker and have been searching and reading online for a way to use Traefik as a reverse proxy for the web server Caddy to serve my static files and web application using Gunicorn. My problem is coming up with a working solution. Currently, I have a docker-compose file for Traefik; port forwarding from 80 and 443, to default to 443 (https with ACME SSL, etc.). My other docker-compose is for the web application and Caddy. I'm using abiosoft/Caddy image on Docker Hub. This is my current docker-compose file the web app and Caddy. Also, how do I do static content as well? I've been trying, and no luck. version: '3' services: unipgdb: image: postgres restart: always container_name: unipgdb environment: POSTGRES_USER: xxxx POSTGRES_PASSWORD: xxxx PGDATA: /var/lib/postgresql/data/pgdata volumes: - ./db-data:/var/lib/postgresql/data/pgdata ports: - "5432:5432" networks: - internal djangoapi: build: context: . dockerfile: Dockerfile image: unicausal/backend:latest command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && gunicorn --preload --chdir api --bind 0.0.0.0:8000 -w 4 api.wsgi:application" container_name: djangoapi volumes: - .:/unicausalapi - static_volume:/home/roycea/project_five/static networks: - unicausalnetwork - internal depends_on: - unipgdb - caddyproxy restart: always labels: - "traefik.enabled=true" … -
how to use models in django for a query
Assume that i have a table usr with feilds name and age table usr id|name |age| 1 |dinkan | 12| my query is select id from usr where name="dinkan" or age="20"; the corresponding output should be 1 so , my question is how to implement this in django 2.1 using models Thanks in advance -
How to binding data that get from Stored Procedure and display the result as a data grid
How to map result from Stored Procedure to each column on html datagrid -
Where I should filter data? Server side or front side?
Imagine I have array of reviews like this: [{title: '...', text: '...'}, {title: '...', text: '...'}]. And I have an text input. If user type some text I want filter reviews using that text. I can do it on both sides: front end and back end. What I know is: front end may be faster if array of reviews is small may be done offline back end may be faster if array of reviews is big I want to know what should I prefer and when (I appreciate complete overview). Taking in consideration such things as: UX, mobile devices, requests to server, server may be overloaded because of too much requests, user mobile may be overloaded because data is too big, array may be either big and small, array items may be either big or small (not only text and title), and what is "big" and "small". -
How to give database name in runtime and migrate all changes to it
i am making one API which will create database. I want to migrate changes in that database. How to migrate changes in database whose name is user defined. -
Send request in certain date and time in django
i want to send one POST request or GET request in certain date and certain time. Those date and time is stored in database. What should be the approach for that? -
I am getting a 2026, SSL connection error when trying to connect my local django to an Amazon RDS MySQL database
Im trying to connect an Amazon RDS MySQL. It works fine when I run it on my terminal. I can connect with ease, but when I try to connect it using my Django app. It give me this error: django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') My database config in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'llda_waterquality', 'HOST': '<host_name>', 'USER': '<rds_uname>', 'PASSWORD': '<password>', 'PORT': '3306', } } -
Django ManyToMany relationship with ModelMultipleChoice Error
I am fairly new to Django. So trying to use inbuilt functionalities instead of overriding the functions. I have established ManyToMany relationship between user and service. Means a user can have many services and a service can be obtained by many users. (Not sure if I am correct) Following are my models Userdata from django.db import models from django.contrib.auth.models import User from services.models import Services class Userdata(models.Model): username=models.OneToOneField(User,on_delete=models.CASCADE) tel=models.CharField(max_length=10,unique=True) address=models.CharField(max_length=100,null=True,blank=True) city=models.CharField(max_length=10,null=True,blank=True) zipcode=models.CharField(max_length=6,null=True,blank=True) services=models.ManyToManyField(Services,through='dashuser.UpcomingUserServices') Services from django.db import models class Services(models.Model): sname=models.CharField(max_length=20) scost=models.IntegerField() def __str__(self): return self.sname UpcomingUserService from django.db import models from services.models import Services from log.models import Userdata class UpcomingUserServices(models.Model): userdata=models.ForeignKey(Userdata,on_delete=models.CASCADE) service=models.ForeignKey(Services,on_delete=models.CASCADE) name=models.CharField(max_length=20) phone=models.CharField(max_length=10) date=models.DateField() address=models.CharField(max_length=100) zipcode=models.IntegerField() remarks=models.CharField(max_length=100,null=True,blank=True) ServiceForm from django import forms from .models import UpcomingUserServices class ServiceForm(forms.ModelForm): service=forms.ModelMultipleChoiceField(Services.objects.all(),widget=forms.CheckboxSelectMultiple()) class Meta: model=UpcomingUserServices exclude=['userdata'] view def book(request): if request.method=='POST': serlist=[] f=ServiceForm(request.POST) if f.is_valid(): s=f.save(commit=False) u=request.user u1=Userdata.objects.get(username_id=u.id) s.userdata_id=u1.id f.save() f.save_m2m() return HttpResponse('Done') else: return render(request,'ns.html',{'f':f}) else: u=request.user u1=Userdata.objects.get(username_id=u.id) i={ 'name':u.first_name+" "+u.last_name, 'phone':u1.tel, 'email':u.email, 'address':u1.address, 'zipcode':u1.zipcode } f = ServiceForm(initial=i) return render(request,'ns.html',{'f':f}) # ns.html is where the form is rendered When the form is submitted, I get following error ValueError at /user/book Cannot assign "<QuerySet [<Services: Lawn Mowing>, <Services: Lawn Fertilization>]>": "UpcomingUserServices.service" must be a "Services" instance (/user/book is view's URL) … -
Django dependent dropdowns along with backend api calls
I'm using Python 3.5.2 and with latest Django version installed. I'm writing a view which consists of dependent dropdowns. When user selects the value from first dropdown, corresponding value should be passed in backend to make an API call and the data obtained, is to be displayed in the next dropdown. I want to create it in the same view. Can it be done in django without using any other technology (like ajax, jquery etc.)? If yes then how? -
Django Unique Together Combination
My scenario is this: class Partnership(models.Model): partner_a = models.ForeignKey( "Person", on_delete=models.CASCADE, related_name='%(class)s_partner_a', ) partner_b = models.ForeignKey( "Person", on_delete=models.CASCADE, related_name='%(class)s_partner_b', ) class Meta: unique_together = (partner_a, partner_b) This works just fine at refusing a duplicate partnership if a=a and b=b: Ex: >>> a = Person('a') >>> b = Person('b') >>> Partnership.objects.create(person_a=a, person_b=b) >>> Partnership.objects.create(person_a=a, person_b=b) # IntegretyError as expected However, it does not correctly refuse the following >>> a = Person('a') >>> b = Person('b') >>> Partnership.objects.create(person_a=a, person_b=b) >>> Partnership.objects.create(person_a=b, person_b=a) # Allowed Is there some class Meta I am missing? Or is there another way to ensure this? (I know I can override the save class, but I'm asking if there is a way to do this without doing that). -
Django test command fail after changing models.py to a directory structure
This is in Django 2.0 , python 3.6.5 I have an app called posts, and I changed models.py to a folder structure, i.e., create a directory models and move the file models.py insid. Also config __ init__.py file, as explained next. The project runs ok, but my test suite fails. In my settings, installed apps i have the app as: 'myproject.apps.posts.apps.PostsConfig' My app config (posts/apps.py) from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' verbose_name = 'posts' I have move posts/models.py to a directory structure. So I have posts/models/models.py posts/models/proxymodels.py posts/models/__init__.py inside models/__ init__.py I do import my models as explained in doc from .models import Job from .proxys import ActiveJob The project works well, but when trying to run tests: python manage.py test I have this error: RuntimeError: Model class tektank.apps.posts.models.models.Job doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The model is a normal one, with fields, nothing extrange. The thing is that if I declare in the meta class Meta: app_label = 'posts' I got the following error: RuntimeError: Conflicting 'job' models in application 'posts': <class 'posts.models.models.Job'> and <class 'tektank.apps.posts.models.models.Job'>. Note: If I use pytest, I run the command: pytest It runs OK -
bootstrap 3 modal - buttons are not working?
I ran This fiddle finely using chrome.(By this i'm meaning that "The button that closed the modal is:" pop-up can work well.) However, I copy-paste the codes to my .js and .html files and they don't work.(the browser remained silence after I click any buttons.) $('#delete-file-modal').on('hide.bs.modal show.bs.modal', function(event) { var $activeElement = $(document.activeElement); if ($activeElement.is('[data-toggle], [data-dismiss]')) { if (event.type === 'hide') { // Do something with the button that closed the modal alert('The button that closed the modal is: #' + $activeElement[0].id); } if (event.type === 'show') { // Do something with the button that opened the modal alert('The button that opened the modal is: #' + $activeElement[0].id); } } }); I'm using Django 2.1.5 and I have customized the bootstrap. In my .html header: {% load staticfiles %} <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script> <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <link rel="stylesheet" href="{% static "css/font-awesome/css/all.css" %}"> <link rel="stylesheet" href='{% static "css/bootstrap.css" %}'> <link rel="stylesheet" href='{% static "css/bootstrap.min.css" %}'> <link rel="stylesheet" href='{% static "css/button.css" %}'> <script type="text/javascript" src='{% static "js/createchapter.js" %}'></script> -
Downloading 40,000+ row csv with Django fails with "Network error"
I have a paginated table that consumes data from an endpoint that returns JSON with Django ReST Framework (DRF). Table filtering is achieved through passing URL parameters to DRF. I'm building a button that let's the user download the filtered data as a CSV. The button works with around 10K rows, but failing when the number of results is above 20K. The download is saying Failed - Network error, but I can see in the network tab of Chrome dev tools that the request I made for the csv data is succeeding with a 200 response code. Here is the function that returns the CSV response: def download_csv(data): pseudo_buffer = Echo() writer = csv.DictWriter(pseudo_buffer, fieldnames=fieldnames) rows_to_write = [ {'col1': 'a', 'col2': 'b', 'col3': 'c'}, {'col1': 'e', 'col2': 'f', 'col3': 'g'}, # 40K more rows here that are calculated # from the data parameter which is # serializer.data (a DRF serializer) ] # setup streaming http response response = StreamingHttpResponse( (writer.writerow(row) for row in rows_to_write), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="download.csv"' return response I started by trying to use Django's HttpResponse. This was working for 10K rows, but was failing with 20K+ rows. I switched to StreamingHttpResponse as described in this example … -
Migration - Create table from models to PostgreSQL
In my project of Django, i have four applications. I created a folder named databasemodels. In this folder i created a file: models.py; in wich i implemented all the classes. And after, in the settings.py of the project, i putted the name of the folder "databasemodels" in the INSTALL_APP, to facilitate the migrations. Is it a good idea to work like this ? -
request.POST.get('username') returns NONE
def profile(request): if request.method != 'POST': update_username = request.POST.get('username') u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): p_form.save() #Other if conditions .... else: update_u_form.save() return redirect('/users/profile/') This is the html template: <form method="post" class="form" enctype="multipart/form-data"> {% csrf_token %} {{ u_form.as_p }} {{ p_form.as_p }} <button name="sumbit" class="btn btn-primary" >Update</button> </form> {{update_username}} My forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] As I type in updated username, and press submit. However The {{update_username}} always print NONE. What is going on? I thought UserUpdateForm should inherit from User model. So request.POST should have a dictionary key-value pair 'username':username. -
How to implement the moderation of new posts at Django 2.1
I want to moderate new posts created. That is, that it was possible to put a tick in the admin panel, and only after that the post would be published. But ideally, of course, so that the administrator could see the new entries right on the site and allow them to publish right there. models.py class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) body = models.TextField() moderation = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) forms.py from .models import Post class PostForm(forms.ModelForm): title = forms.CharField(required=True) body = forms.CharField(widget=forms.Textarea) class Meta: model = Post fields = ['title', 'body'] views.py from .forms import PostForm class PostCreateView(FormView): form_class = PostForm template_name = 'blog/post_form.html' success_url = reverse_lazy('posts') def form_valid(self, form): response = super(PostCreateView, self).form_valid(form) form.instance.user = self.request.user form.save() return response admin.py from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ('title', 'user', 'moderation') admin.site.register(Post, PostAdmin) urls.py urlpatterns = [ url(r'^posts/$', views.PostListView.as_view(), name='posts'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post-detail'), ] I want it to be like in the picture. Or you can watch and moderate the post right away on the site. enter image description here -
Django Built In AuthenticationForm Not Validating User
I'm trying to build a login system with the Django framework. I extended the UserCreationForm to add names and emails. Now that I have users in the database, I'm trying to authenticate them and log them in. However, when I call the built in AuthenticationForm class, create an instance with the post data, and try to authenticate the user, I get no user returned and authentication fails. All the code for the views.py file is below. I have tried reading the AuthenticationForm source code, but none of that is helping. Any suggestions? from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.db import models from django import forms from django.forms import EmailField from django.forms import CharField from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = EmailField(label=_("Email address"), required=True, help_text=_("Required.")) class Meta: model = User fields = ('email', 'username', 'first_name', 'last_name',) def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.firstName = self.cleaned_data["first_name"] user.lastName = self.cleaned_data["last_name"] user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user def signup(request): if request.method == 'POST': # if sending data to the server form = SignUpForm(request.POST)# creates form from request data if form.is_valid(): user = form.save() … -
Call gRPC Client Stub from External Django Application
I'm following https://blog.codeship.com/using-grpc-in-python/ to use gRPC with Python. Has anyone used the client wrapper (client_wrapper.py ) with an external Django application? I need a way to call the client or client wrapper from an external Django application and obtain a stub to make the RPC calls. Is this possible? Any help would be appreciated. Thanks. -
Django assigning a remote file to a FileField without download and reuploading
I'm using django-storages as my default file storage. I have a script that uploads videos directly from the client to google cloud storage. Is there any way to associate this file to a FileField without downloading and reuploading the file. Thank you for any help! -
Is there a better way to move between Django's views aside from pasting new url?
I'm learning to use Django to build my web application. I want to access another page through a link on the index page, but the browser keeps appending the file and app name to the request. How do I get the browser to switch through links without appending the directory name each time ? I've tried using reg exp with the old url method but it doesn't seem to work # My project # urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')), ] # My app # urls.py urlpatterns = [ path('index/',include([ path('', views.index,name="index"), path('theteam', views.theteam,name="theteam"), path('services',views.services,name="services"), path('quotes',views.quotes,name="quotes"), path('insurance',views.insurance,name="insurance"), path('contact',views.contact,name="contact"), path('thanks', views.thanks,name="thanks"), ])), ] # Views def index(request): return render(request, 'index/index.html') def theteam(request): return render(request, 'index/theteam.html') def services(request): return render(request, 'index/services.html') def quotes(request): form = ContactForm(request.POST or None) if request.method == 'POST': return redirect(request, '/thanks/') return render(request, 'index/quotes.html', { 'form': form }) def insurance(request): return render(request, 'index/insurance.html') def contact(request): return render(request, 'index/contact.html') def thanks(request): return render(request, '/thanks.html') #My Views HTML <div class="menu-bar "> <ul> <a href="{% url 'services' %}"> <li>Services</li></a> <a href="{% url 'theteam' %}"><li>The Team</li> </a> <a href="{% url 'quotes' %}"><li>Quotes</li> </a> <a href="{% url 'insurance' %}"> <li>Insurance</li></a> <a href="{% url 'contact' %}"><li>Contact Us</li></a> </ul> </div> So far I've … -
Which platforms to use for backend and Android frontend
I plan to write a service that should communicate both with Android app and Desktop app and send various data (login data, images, texts etc.) My questions are: 1) What to use for backend, on server side I have an experience with Django and MySql but should you recommend something else cause this is a large project and I don't mind learning new stuff 2) What to use for frontend for developing Android app that will communicate with server Here I don't have the any clue, all I ever tried to develop any app but that was very primitive was some previous versions of Delphi XEs; I heard that new Delphi Seattle has great stuff for cross compiling, is it any worth or to complete forget about Delphi? Thanks.