Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Grouping queryset by date
I have a class which contains a date as well as some other fields. What I'm trying to figure out is a query which will return me each of the items, grouped by the date. So, given the following class:- class Item(models.Model): item_date = models.DateField() <other fields> I'd like to get something like this:- [ { 'item_date': datetime.date(2018, 9, 12), 'items': <Queryset [<Item: item1>, <Item: item17> ...] }, { 'item_date': datetime.date(2018, 9, 13), 'items': <Queryset [<Item: item2>, <Item: item33> ...] }, { 'item_date': datetime.date(2018, 9, 14), 'items': <Queryset [<Item: item34>, <Item: item37> ...] } ... ] I'm pretty sure I need some sort of annotation but I'm not 100% sure how to structure it. The closest I've got is:- Item.objects.values('item_date').annotate(Count('id')).order_by('item_date') but that just gives me the counts of how many Items are on each date - not the actual Items (obviously!). What do I need instead of that Count? Is this even possible?! -
Python: ValueError: invalid literal for int() with base 10: '' but, can't find error
I'm not sure where the issue is with my app. I haven't made any changes but, now I have this valid int error. Here is the error: ProgrammingError at /restaurant/orders/ column yummyApp_order.delivered_at does not exist LINE 1: ...der"."created_at", "yummyApp_order"."picked_at", "yummyApp... ^ Request Method: GET Request URL: https://yummy-.herokuapp.com/yummy/orders/ Django Version: 1.10 Exception Type: ProgrammingError Exception Value: column yummyApp_order.delivered_at does not exist LINE 1: ...der"."created_at", "yummyApp_order"."picked_at", "yummyApp... When I attempt to migrate, I get this error: ValueError: invalid literal for int() with base 10: '' But my "Orders" have a delivered_at in models: delivered_at = models.DateTimeField(default = timezone.now) I'm not seeing the issue. Help! -
Django logging thread safety between server and commands
I want output from my Django server as well as Django management commands to all be written to the same file. This is easy to set up in the settings.py file, but are there any concerns with thread safety or file locking with a management command (which is run from the command line) trying to write to the same file as the main Django server (running from wsgi)? Any concerns with this set up running under Windows vs Linux or other operating systems? In case there are different answers in different versions: python 3.4 Django 1.11 Thanks! -
django pdf generation function is not working properly
i have copy pasted a django pdf generation class.it is having two parts js and django, in js i am trying fetch data from button on click and in django end i am getting those datas with request.GET.get parameter and sending them to API to get desired data so i can parse them and can give Httpresponse as pdf, but problem is every code is working fine,i am hitting the ajax on button click and getting data in backend and able to hit API, but i am not able to give Httpresponse! When i write button in an a tag with < a href={% utl 'app_name':'url_name' %}><button></button></a> its calling the function and gives Httpresponse as pdf but not with this ajax button on click method. ajax $('.btn-download').click(function(){ $.ajax({ url:'{% url 'tom:detail' %}', method:'GET', data:{ 'data-id':$(this).attr('data-id'), 'data-order':$(this).attr('data-order') }, } }) }) view.py class GeneratePDF(View): def get(self, request, *args, **kwargs): user_id = request.session['user_id'] invoice_id = request.GET.get('data-id') order_number = request.GET.get('data-order') parameter = { 'invoice_id': invoice_id, 'order_number': order_number, 'user': user } print(parameter) url = '{}{}'.format(API_URL, '/rest/getOrderDetail') r = requests.post(url=url, params=parameter) context = { "name": r.json()['name'], } pdf = render_to_pdf('pdf/contract.html',context) response= HttpResponse(pdf, content_type='application/pdf') return response urls.py url(r'^contract-pdf$',GeneratePDF.as_view(),name='detail'), -
Converting raw SQL to Django ORM QuerySet
This is my SQL: Event.objects.raw('SELECT DISTINCT unnest(ARRAY[start_date::date, end_date::date]) as dates, * FROM api_event') How can i do this using Django ORM? -
setting up Reactjs in Django project
I am building project with react in django. Hierarchy of the Django project: -library -assets -library -frontend -manage.py I have created production_settings.py in the same direction as settings.py is. when I run the command below i just got an error that : Error reading /Desktop/Library/library/webpack-stats.prod.json. Are you sure webpack has generated the file and the path is correct? command : python3 manage.py runserver --settings = library.production_settings production_settings.py: from .settings import * STATICFILES_DIRS = [ os.path.join(BASE_DIR, "assets"), ] STATIC_URL = '/static/' WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack- stats.prod.json'),}} -
How can i get form data from django layouts (like 'base.html') without sending forms in all page through views?
many templates extend from base.html. base.html have one newsletter form that get email from user. Is there any easy way to get the form data from 'base.html' to view. (Sending forms in all page through views is possible But I think there is A easy good Looking idea) -
How to deploy Django Channels on Ubuntu and Nginx?
I have Django channels running in local but it doesn't work in production. My setup files are upstream app_server { server unix:/home/urban/run/gunicorn.sock fail_timeout=0; } server { # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name 206.189.130.189; keepalive_timeout 5; client_max_body_size 4G; access_log /home/urban/logs/nginx-access.log; error_log /home/urban/logs/nginx-error.log; location /static/ { alias /home/urban/homet_dj/static/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://app_server; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/hometadka.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/hometadka.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot and supervisor file includes [program:homet_dj] command=/home/urban/bin/gunicorn_start user=urban autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/urban/logs/gunicorn-error.log [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8000 # Directory where your site's project files are located directory=/home/urban/bin/homet_dj # Each process needs to have a separate socket file, so we use process_num command=/home/urban/ daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers homet_dj.asgi:application # Number of processes to startup, roughly the number of CPUs … -
why do I see different results for www and non-www version of my blog in django/Mezzanine
I am using django/mezzanine 4.3.0 as my blog engine. In the non-www version of my site, everything is okay. But when I enter the domain with www, I only see the right panel (which is a static code) and the footer. Everything that is derived from the database is not there. When I log-in to admin panel, on the top bar I can choose between the available sites, when I choose the www version and I navigate to blogs, pages, etc, there are nothing there. What is the problem? What have I done wrong? Can it be due to the following line in local_settings.py?? "DOMAINS": ["myblog.com", "www.myblog.com"] -
Custom templates for custom AdminSite Django
I have two admin sites and I want to have different custom templates on both of them This is my admin.py file: from django.contrib import admin from django.contrib.admin import AdminSite from .models import Equipo @admin.register(Equipo) class EquipoAdmin(admin.ModelAdmin): list_display = ('codigo', 'nombre', 'contador', 'unidades') class AdminMantenimiento(AdminSite): site_header = "MANTENIMIENTO" class EquipoAdminMantenimiento(admin.ModelAdmin): list_display = ('codigo', 'nombre') admin_site = AdminMantenimiento(name='Administrador Mantenimiento') admin_site.register(Equipo, EquipoAdminMantenimiento) This is my urls.py file: from django.contrib import admin from django.urls import path from Mantenimiento.admin import admin_site urlpatterns = [ path('admin/', admin.site.urls), path('admin2/',admin_site.urls) ] If I override the templates as per Django documentation changes would be applied to both AdminSites. How can I set custom templates for the class extending AdminSite? -
Highcharts steps to setup own server for download
I want to create a application which will generate some report based on some data and analysis. And I have to create a graph for this report. I'm using Django framework with python to generate report and Highchart for graphs. But after using highchart,js i realised that .js uses export.highcharts.com I do not want to send the data to export.highcharts.com but use my server. How can i acheive this ? Im very new to this and just started learning Django. Finding it difficult to understand the explaination given here : https://www.highcharts.com/docs/export-module/setting-up-the-server. So once i download highcharts-export-server what are the next steps ? What changes am i supposed to do in highchart.js file so that download options are available. Thanks in advance -
Django render template tags from database to html
How can i render template tags from models.TextField to html. Dango admin dynamic content In wiews i have defind how to render it to html like: Views.py Html: Html And i get this result: Web site resault -
Return a list by a POST Request
I'm new to django and python, I want to return all the objects having the foreign key provided by a post request. this is my model: class Product(models.Model): name = models.CharField(max_length=200) image = models.CharField(max_length=400) price = models.CharField(max_length=200) isFavorite = models.BooleanField(default=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) this is my serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'image', 'price', 'isFavorite') this is my code in views.py: class ListProductsOfCategory(generics.ListAPIView): serializer_class = ProductSerializer() def post(self, request, *args, **kwargs): # catch the category id of the products. category_id = request.data.get("category_id", "") # check if category id not null if not category_id: """ Do action here """ # check if category with this id exists if not Category.objects.filter(id=category_id).exists(): """ Do action here """ selected_category = Category.objects.get(id=category_id) # get products of this provided category. products = Product.objects.filter(category=selected_category) serialized_products = [] # serialize to json all product fetched for product in products: serializer = ProductSerializer(data={ "id": product.id, "name": product.name, "image": product.image, "price": product.price, "isFavorite": product.isFavorite }) if serializer.is_valid(raise_exception=True): serialized_products.append(serializer.data) else: return return Response( data=serialized_products , status=status.HTTP_200_OK ) this code partially worked, its returning the below reponse. the problem is that the primary key "id" of the product is missing, I want the response to … -
Show all data from ManyToMany Fields
I'm try to get all data from relationship manytomany, this is my model class Product(models.Model): name = models.CharField(max_length=100) image = models.FileField(upload_to='products/', null=True) price = models.FloatField(default=0) stock = models.CharField(max_length=15) categories = models.ManyToManyField(Categories) def __str__(self): return self.name class Categories(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name for get the data from products try this: class Products(ListView): model = Product template_name = "products.html" on the template return similar to this: _______________________________ # | name | price | Categories | ________________________________ 1 | Pepsi | 1.25 | | 2 | Choco.| 2.50 | | for generate this table i use a cycle for: {% for product in object_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ product.name }}</td> <td>{{ product.price }}</td> <td>{{ product.categories }}</td> {% endfor %} in this case return empty the categories selected on the product..please any suggest.. thanks !! -
Invalid block tag on line 'else' when trying to extend a template within if, else condition [duplicate]
This question already has an answer here: Any way to make {% extends '…' %} conditional? - Django 4 answers I am building a blog-style django feature (v_posts.html), which I intend to display both as a standalone post-list (if manually requested from the navbar) or as a article adjacent iframe (if requested from another parent url, article-posts). If displayed as standalone blog, it should include all default page elements (i.e. navbar), so I am extending it into the default path (blog/body.html >> base.html) which includes these elements further up the chain. However, if the post-list is displayed within an iframe I don’t need to include things like a navbar, so I am directly extending it into a separate path (blog/base_iframe.html). I am using a "if, else" statement to achieve this. Unfortunately, using the “if, else” statement below, I am receiving an error message: v_posts.html 1 {% if not "article-posts" in request.path %} 2 {% extends "blog/body.html" %} 3 {% else %} 4 {% extends "blog/base_iframe.html" %} 5 {% endif %} Message: Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Please note that the “if, else” statement works fine when I remove the … -
re-run server after updating database in django
I am new to django framework of python, and I have one problem here. I am trying to build a website for a company. There is a feed where I have to write about news in the company. I managed to create a database and am able to make changes. My problem is whenever I make a new post I have to re-run the server in order those changes to be shown for the end-user. Does it only happen in development mode or also in production? If not only in development is there a way to update everything without re-running the server? -
MySQL and Django on Mac - libssl.1.0.0.dylib not loaded
When changing the config to use MySQL as database I'm getting an error trying to start Django server (python manage.py runserver) It is asking me if I installed mysqlclient which I finally was able to do after some digging around on SO. The error it ends with is: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. High up in the Traceback it states that this exception is causing another exception: Traceback (most recent call last): File "/Users/username/PycharmProjects/projectname/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/username/PycharmProjects/projectname/venv/lib/python3.6/site-packages/MySQLdb/__init__.py", line 18, in <module> import _mysql ImportError: dlopen(/Users/username/PycharmProjects/projectname/venv/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libssl.1.0.0.dylib Referenced from: /Users/username/PycharmProjects/projectname/venv/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found There are many questions similar to this and I tried quite a bit but can't seem to get this to work. I tried adding MySQLdb as package directly, but then I get the error: Could not find a version that satisfies the requirement MySQLdb (from versions: ) No matching distribution found for MySQLdb As said; mysqlclient is installed. Any ideas? -
chat() missing 1 required positional argument: 'id'
My url pattern is url(r'^my/<int:id>/', views.chat, name='chat'), and my view function is like this def chat(request, id): snippet = Posted_proj.objects.get(id=id) return render(request, 'chat.html') And getting this error chat() missing 1 required positional argument: 'id' I am unable to figure what I am doing wrong . kindly help -
Django Rest Framework Saying Non-Required Field Is Required
The Backstory In Django I have the models class Company(models.Model): name = models.TextField(null=False,unique=True) date_added = models.DateTimeField(auto_now_add=True) class Address(models.Model): street = models.TextField() class Person(models.Model ): firstname = models.TextField() address = models.ForeignKey(Address,null= True,on_delete=models.SET_NULL) company = models.ForeignKey(Company,null=True,on_delete=models.SET_NULL) Where each person has an address and a company.(both non required fields) In DRF I have the serializers. class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = "__all__" class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('id', 'firstname', 'address','company') def to_representation(self, instance): response = super().to_representation(instance) response['address'] = AddressSerializer(instance.address).data response['company'] = CompanySerializer(instance.company).data return response The Issue When posting the data {"firstname":"foo"} to this serializer, it returns a 400 error code saying. {"company": ["This field is required."]}. The odd thing is, the address field is set up the seemingly exact same way as the company field but does not throw this error. In order to make this work, you must post {"firstname":"foo","company":null} to the serializer, which seems a little silly considering that the address field works just fine. Does anybody have any idea what would be causing this issue and how to prevent this from happening? -
Get data using annotate with joining 3 tables
I have 3 tables:- class Organization(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() ..... #some more field ..... class Billing(models.Model): id = models.AutoField(primary_key=True) organization = models.ForeignKey(Organization) amount = models.IntegerField() ..... #some more field .... . class Payment(models.Model): id = models.AutoField(primary_key=True) billing = models.ForeignKey(Billing) organization = models.ForeignKey(Organization) paymentDate = models.DateTimeField() ..... #some more field .... Whenever payment has done by organization it creates a new entry for payment table every time and updates the billing amount. And there are multiple billing objects are available billing table. So I am calculating the sum of amount and latest payment done for the particular organization using annotate. I have stuck to find the latest payment date for the organization in using annotate query. billing.objects.filter( orgId_id__in = organizationIdList, isCancel=0, billTime__range=(startDate, endDate) ).values('orgId_id').annotate( total_amount = Sum('amount'), lastest_payment_time = "HERE I AM STUCK", ) Please help me out. -
How to load static file in Django Python file
I am trying to load a CSV in my Django project. I have a python file located in /example/hello.py inside hello.py I read a CSV file using Pandas: from django.contrib.staticfiles.templatetags.staticfiles import static productsDF = pd.read_csv(static('example/data/products.csv')) However, for some reason I get a FileNotFoundError: File b'/static/example/data/products.csv' does not exist The CSV file is located in the static directory of my app and it works fine when I want to import static files like CSS in my HTML using {% load staticfiles } <link href="{% static 'example/hello.css' %}" rel="stylesheet"> For some reason, it doesn't work in my Python file. How can I get it to work? -
Django DRF follow relationships
Well, I am trying to follow relationships with Django Rest Framework. Here is a simplified model : class Model1(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Model2(models.Model): title = models.CharField(max_length=12, null=True, blank=True) model1 = models.ForeignKey(Model1, on_delete=models.CASCADE) And Serializers : class Model1Serializer(serializers.ModelSerializer): class Meta: model = Model1 fields = '__all__' class Model2Serializer(serializers.ModelSerializer): class Meta: model = Model2 fields = '__all__' From Model2, I would like to access owner properties, like email... Without DRF and in a standard template, I would do this : {{ instanceOfModel2.model1.owner.email }} This would follow the relationship. Do you have any idea how could I achieve this using Django DRF? I looked at https://www.django-rest-framework.org/api-guide/relations/ But what I want is the opposite way... And I'd like to not expose the Django User model through a REST API.... -
How to use slugs in django url
Have been scared to ask this here, just stated with Stack Overflow and belive me I have tried searching for this question but mostly I saw regex patterns. Please if anyone could be kind enough to guide me through these few issues: How to fill my blog model slug field automatically with the post name without filling it up myself. How to make a link to go to the single post page using the slug WITHOUT regex in Django 2.x Thanks. -
Django automatically add a foreignkey in form
I have the following a form and model: class Book(models.Model): name = models.CharField(max_length=128, null=True, blank=True) author = models.CharField(max_length=128, null=True, blank=True) borrower = models.ForeignKey('core.User') class BookForm(forms.ModelForm) class Meta: model = Book fields = ("name", "author", "borrower") In my website the user can borrow a book. Each book has its own borrower. The problem is that the field "borrower" is translated into a html select, I would like to hide it and set it to the currently logged in user. I would appreciate help implementing this -
django-rest-framework NoReverseMatch at / - using multiple urls.py
I'm using django-rest-framework and having trouble setting up setting up a URL to display a generic view at the project root url (127.0.0.1/) My project has two apps and is structured as such: calendar_app --users --citycalendar urls.py urls.py These are my files #calendarapp/urls.py from rest_framework.authtoken import views as tokenviews from calendar_app.citycalendar import views from .users.views import UserViewSet, UserCreateViewSet from django.conf.urls import url router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'users', UserCreateViewSet) urlpatterns = [ url(r'^$', views.ApiRoot.as_view(), name=views.ApiRoot.name), url(r'^', include('calendar_app.citycalendar.urls')), path('admin/', admin.site.urls), path('/', include(router.urls)), path('api-token-auth/', tokenviews.obtain_auth_token), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # the 'api-root' from django rest-frameworks default router # http://www.django-rest-framework.org/api-guide/routers/#defaultrouter # re_path(r'^$', RedirectView.as_view(url=reverse_lazy('api-root'), permanent=False)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and #calendar_app/citycalendar/urls.py from django.conf.urls import url from calendar_app.citycalendar import views urlpatterns = [ url(r'^event-collections/$', views.EventCollectionList.as_view(), name=views.EventCollectionList.name), url(r'^event-collections/(?P<pk>[0-9]+)$', views.EventCollectionDetail.as_view(), name=views.EventCollectionDetail.name), url(r'^events/$', views.EventList.as_view(), name=views.EventList.name), url(r'^events/(?P<pk>[0-9]+)$', views.EventDetail.as_view(), name=views.EventDetail.name), url(r'^$', views.ApiRoot.as_view(), name=views.ApiRoot.name), ] and #calendar_app/citycalendar/views.py class ApiRoot(generics.GenericAPIView): name = 'api-root' def get(self, request, *args, **kwargs): return Response({ 'event-collections': reverse(EventCollection.name, request=request), 'events': reverse(EventList.name, request=request), }) When I view 127.0.0.1/ I receive a NoReverseMatch at / error. How can I setup my URLs such that when visiting the root of the project I will see class ApiRoot(generics.GenericAPIView): I left in some commented out URLs to show URLs that were merged from other …