Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sort products from <option> tag using Django and HTML
I have a list like <select class="selection-2" name="sorting"> <option>Default Sorting</option> <option>Popularity</option> <option>Price: low to high</option> <option>Price: high to low</option> </select> Now i want to sort the products which i have listed to my html page using Django View. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) paginator = Paginator(products, 9) page = request.GET.get('page') products = paginator.get_page(page) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) context = { 'category': category, 'categories': categories, 'products': products } return render(request, 'shop/product/list.html', context) This is my product list view and i want to create a view for the sorting and filtering of the products. -
How to serialize a API response (in JSON) and modify and add fields to it in Django Rest Framework?
I am getting data from different APIs in DRF. However, to enforce modularity I need to serialize the JSON response and make a 'fake' model for each API endpoint I am calling. I have already made a model and a serializer for an endpoint, but I need to make another API call while serializing it and modify some of the fields. from rest_framework import serializers from django.db import models from ..nlp_utils.google_nlp import GoogleNLP class Search(models.Model): title = models.CharField(blank=True, default='') link = models.CharField(blank=True, default='') snippet = models.CharField(blank=True, default='') description = models.CharField(blank=True, default='') sentiment_score = models.FloatField(blank=True, default=0.0) sentiment_magnitude = models.FloatField(blank=True, default=0.0) class SearchResultSerializer(serializers.ModelSerializer): class Meta: model = Search fields = ('title', 'link', 'snippet', 'description','sentiment_score', 'sentiment_magnitude')` here I need to call some more endpoints and populate sentiment_score and sentiment_magnitude -
Django OperationalError: no such column: on pythonanywhere
I am very new to django. and I am not a good English speaker. so I hope you guys understand. thanks. :) first, I was able to fix ImportError. I figured out that it was because django version on pythonanywhere is not updated. so I upgraded django on pythonanywhere from 1.x.x to 2.0.9. The error came out like this: ImportError at / cannot import name 'path' django version: 1.x.x python version: 3.6.6 and, unfortunately, my app gave me another error: OperationalError at / no such column: blog_post.published_date Request Method: GET Request URL: http://*.pythonanywhere.com/ Django Version: 2.0.9 Exception Type: OperationalError Exception Value: no such column: blog_post.published_date Exception Location: /home/*/my-first-blog/myenv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 303 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.6 I thought this error came out because of some data base. so I tried migrate or makemigrations on pythonanywhere. but I could not fix it still. So, is there anyone who knows how to fix this database? If you need more information, I can provide more. -
I have a start_date and end_date in my db table, how do I return all records where current date falls between those 2 values?
I'm trying to see if a contract is currently active, so I need to check if the current date lies between the contract start date and end date. class Contract(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) start_date = models.DateField(null = True, blank = True) end_date = models.DateField(null = True, blank = True) -
Where should I start a new thread when the django server starts
I need a thread running when I start my django server, basically the thread just periodically processes some items from a database. Where is the best place to start this thread. -
Why can't use numbers to reference dictionary in Django
I am trying to render a page with a dictionary, which was created using a loop, and while trying to reference it in the template(.html), it is printing the number inspite of the value for that key view.py dicti={} key = range(len(OPTIONS)) # a tuple for i in key: dicti[i] = polls_model.objects.filter(options=i).count() dicti.update({'len_of_key' : key}) print(dicti) return render(request,'polls/thanks.html', dicti) this prints {0: 1, 1: 1, 2: 0, 3: 0, 'len_of_key': range(0, 4)} thanks.html <div class="row"> {% for i in len_of_key %} <div class="column"> <div class="card"> <h3> {{ i }} </h3> </div> </div> {% endfor %} </div> and when this runs i end up having 1,2,3,4 in my output. a little help would be appreciated please -
Append text after ID in Django
I have a template, which has code, currently saying: <a href="{% url 'vote-time-series' record.id %}">Vote time series</a> I want it to generate URLs matching: path('vote-records/<int:pk>/time-series', vote_time_series, name='vote-time-series') The solution linked in earlier pages only works with straight appending. How do I do this, where the ID is put in the middle? -
How to make reverse url function work when versioning my api
I want to version my api, but cannot make reverse function work. I am following the namespace versioning schema proposed in the DRF website : namespaceversioning I have one app called authentication and inside authentication folder I have : authentication/ | -- models.py, apps.py, admin.py -- api_v1/ | -- views.py -- serializers.py -- urls.py In my main urls.py, I've defined urlpatterns = [ url(r'^api/v1/',include ('tektank.apps.authentication.api_v1.urls',namespace='v1') ) ] This is authentication/api_v1/urls.py from rest_framework.routers import DefaultRouter from authentication.api_v1.views import UserViewSet app_name = 'authentication' router = DefaultRouter() router.register(r'users', UserViewSet, base_name='authentication-user') urlpatterns = router.urls And when I execute ./manage.py show_urls /api/v1/users/ authentication.api_v1.views.UserViewSet v1:authentication-user-list /api/v1/users/<pk>/ authentication.api_v1.views.UserViewSet v1:authentication-user-detail When I am trying to reverse for example from shell, I have the following error: > reverse('v1:authentication-user-detail', kwargs={'pk': '5'}) NoReverseMatch: Reverse for 'authentication-user-detail' not found. 'authentication-user-detail' is not a valid view function or pattern name. BUT, if I do not put namespace='v1' in the app urls, like this: url(r'^api/v1/',include('tektank.apps.authentication.api_v1.urls') Then the reverse functions works > reverse('authentication:authentication-user-detail', kwargs={'pk':5}) > '/api/v1/users/5/' I think I am calling the reverse in the wrong way, or maybe some configuration? Because if I call the api for example via postman, the endpoint is working ok. -
How to optimise similar queries in Django?
Often, I end up using several similar queries in my Django views, with one varying lookup field. This accumulate easily, and lead to severe impacts on page load times. How can one go about optimising this? { "pg1": Product.objects.filter(groups__group="pg1")[:5], "pg2": Product.objects.filter(groups__group="pg2")[:5], "pg3": Product.objects.filter(groups__group="pg3")[:5], "pg4": Product.objects.filter(groups__group="pg4")[:5], } -
Group by Every id and get First date
Somebody help me, I have data like this using postgresqlq : id|Orderid |Note |Date ................................................ 1 |1 |Tes1 | 2018-12-11 2 |1 |Tes1 | 2018-12-12 5 |1 |Tes1 | 2018-12-09 6 |1 |Tes1 | 2018-12-07 i want group orderid and get first date in every orderid,result like this : id|Orderid |Note |Date ................................................ 1 |1 |Tes1 | 2018-12-11 6 |1 |Tes1 | 2018-12-07 How to make orm in django ? -
null value in column "city_id" violates not-null constraint
This error happens when I tried to use Django admin to add a new entry in the database. This error shows even I tried to add a new state. What's wrong with my model? class City(models.Model): city_id = models.AutoField(primary_key=True) city = models.CharField(max_length=100, blank=True, null=True) state = models.ForeignKey('State', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'city' def __str__(self): return self.city class State(models.Model): state_id = models.AutoField(primary_key=True) state = models.CharField(max_length = 10, blank=True, null=True) class Meta: managed = False db_table = 'state' def __str__(self): return self.state -
How to partition a window function over a function in Django?
While trying to solve a parent problem I got to this code: queryset = self.filter_queryset(self.get_queryset()).annotate( min_created=Window(expression=Min('created'), partition_by=F('id')) ).annotate( max_created=Window(expression=Max('created'), partition_by=F('id')) ).annotate( bucket=Func( Extract(F('created'), 'epoch'), Extract(F('min_created'), 'epoch'), Extract(F('max_created'), 'epoch'), Value(request.query_params.get('buckets')), function='width_bucket' ) ).annotate( bucket_min_created=Window( expression=Min('created'), partition_by=F('bucket') ) ) In other words, I'm trying to get the minimum created datetime per bucket. The problem is that running this code results in the following error: django.db.utils.ProgrammingError: window functions are not allowed in window definitions In SQL this would be easy to solve: simply put the width_bucket function in a sub-query. But how do I achieve the same in Django? -
How can I ignore duplicates for one column in multiple rows in a queryset returned to a template?
I have a view that returns a list of products that, for example, a part of a specific collection. For most of these results, I want to iterate through and display all of them, such as images and individual products, etc. I know how to do this using for loops within templates. What I am unsure how to stop specific columns from the queryset being displayed when they are identical. In this picture, the manufacturer and descriptions are identical, and I only want to display them once while showing every image returned. I don't think I need to include my views.py and such given the generic nature of the question, but in case this is an excerpt from my template showing how I grab the description: {% for instance in products %} {{ instance.description }} <br /> {% endfor %} What is the correct way to either check for duplicates, or to show only certain columns from the first row returned from a queryset in a django template? Can this be done in a django template, or must it be done in a view? -
ModuleNotFoundError: Django application name appended to corsheaders
I'm a student trying to teach herself Django by creating a simple(-ish) web application. I'm having trouble with cross-origin requests, specifically with the django-cors-headers app. I'm using client-side JavaScript to parse user input and to send AJAX requests to a Django script. To make sure that my HTTP requests can be completed, I installed django-cors-headers, included corsheaders in INSTALLED_APPS, added corsheaders.middleware.CorsMiddleware and django.middleware.common.CommonMiddleware to MIDDLEWARE, and set CORS_ORIGIN_ALLOW_ALL to True. My JavaScript seems fine, and my HTTP requests are successfully being fired. However, they never reach the views in my Django script, because I get the error ModuleNotFoundError: No module named 'corsheadersmy_app'. That's clearly the reason I'm getting a ModuleNotFoundError--there may be a module named corsheaders, but there certainly isn't one named corsheadersmy_app. I've spent the entire day going over the Django documentation and reading about cross-origin resource sharing, but I can't find anything related to my problem. Why is the name of my application being appended to corsheaders? -
Group By ORM Django and Get First date
I have data like this : order_id | Note |date_rejected --------------------------------------- 1 | Testing 1 | 2018-12-11 1 | Testing 1 | 2018-12-12 2 | Testing 2 | 2018-12-07 2 | Testing 2 | 2018-12-09 and i want make like this : 12 | Testing 1 | 2018-12-11 22 | Testing 2 | 2018-12-07 How to make ORM in django ? -
Django websocket works on local but not in Amazon EC2 server, error during Websocket handshake
I have a project in websockets with angular and django, it works fine locally with Linux, when I have deployed it to Amazon EC2 that is also Linux and did the same with Linux locally, I have attached a screenshot of the server in django in Amazon EC2 that it looks that is running ok, server screenshot, the client that is an angular app, when I'm trying to connect to the server this.globals.socket = new WebSocket('ws://mydomain.com.com/stocks'), I'm getting this error WebSocket connection to 'ws://mydomain.com.com/stocks' failed: Error during WebSocket handshake: Unexpected response code: 404. Do I have to configure something in nginx.conf in Amazon EC2 server?, or do I have to enable something additional in the server?. Any help or clue would really be appreciated. Thank you very much. -
How to use a variable in the django-instagram app : {% instagram_user_recent_media username %}?
I use the django-instagram application (django-instagram) to get the recent media of an user. I pass a variable to the template that I call username. It contains the username of the instagram user. When I try to do this for exemple : <p>{{ username }}</p>. It works perfectly. It's displaying the good username. But when I use the tag {% instagram_user_recent_media username %}, it takes username as a string. So the app search on Instagram with the username "username". Obviously it don't find anything. I also tried to do that : {% instagram_user_recent_media {{ username }} %}, but I receive an error message : django.template.exceptions.TemplateSyntaxError: 'instagram_user_recent_media' tag requires a single argument I really hope that someone can help me on this problem because I spent a lot (yeah ... a lot) of time to figuring out thie issue without success ! Thanks my friends ;) -
How to use PostgreSQL's width_bucket and partitioning in Django?
I've got a Django model Reading with a DateTimeField on it, and for reasons outside of the scope of this question I want to select only the first and last entries in each equally wide "time bucket". This works fine in PostgreSQL, splitting the last 10 years into 1000 buckets and selecting the first and last entries within each: SELECT created, value FROM ( SELECT created, value, min(created) OVER (PARTITION BY bucket) AS first_created, max(created) OVER (PARTITION BY bucket) AS last_created, bucket FROM ( SELECT created, value, width_bucket( extract(EPOCH FROM created), extract(EPOCH FROM now()::TIMESTAMP - INTERVAL '10' YEAR), extract(EPOCH FROM now()::TIMESTAMP), 1000 ) AS bucket FROM readings ) AS bucketed_readings ) AS first_and_last_created_per_bucket WHERE created IN (first_created, last_created); I don't know where to begin to translate this into a Django Rest Framework filter, such that it integrates seamlessly with other filters. That is, the other filters must apply to the inner-most query to avoid completely messing up the bucketing and query runtime. -
How to query non-assigned ForeignKeyField objects in models
community, I have the following model & let's assume we have 5 SouceCode objects & 2 Project objects. out of 5 SouceCode objects i have added 2 objects of SourceCode as ForiegnKeyField to Project Model. Now, How do i print/query the 3 SourceCode objects which haven't used as ForeignKeyField for Project Model. models.py class SourceCode(models.Model): source_description = models.CharField(max_length=80,unique=True) source_urls = ArrayField(ArrayField(models.TextField(blank=True),),blank=True,null=True,default=list) source_results = JSONField(blank=True,null=True,default=dict) class Project(models.Model): project_name = models.CharField(max_length=200,unique=True) project_sourcecode_O2M = models.ForeignKey(SourceCode,on_delete=models.SET_NULL,blank=True, null=True) One possible way I know is the following: project_source_code_list = [] for each_project in Project.objects.all(): project_source_code_list.append(each_project.project_sourcecode_O2M) for each_source_code in SourceCode.objects.all(): if each_source_code not in project_source_code_list: print("YEP Not there") I'm looking for a good alternative solution for this. Thanks. -
Django - populate model with foreignkey via csv import?
I've trying to setup a model to be populated with a csv file, and to use one of the fields as a foreignkey: First, I tried creating a model from an existing postgresql table using inspectdb, migrating and then change the type of the field I want to relate from charfield to foreignkey, but I got errors Then I tried creating an empty model with the inspectdb description, then importing a csv in postgresql, and finally changing the field i want to foreignkey. In the admin site I can view the imported data and the relations, but when I query the model I got another error with the foreignkey field, and it wont let me migrate (cant recognize the charfield, it asks for integer) -the csv column I want for a foreignkey is charfield, when i create the model before importing the csv i got an error, then checking the datatype in the postgres table is says integer, can it be set to charfield?? What workflow work best for importing a csv to a model and use one of the fields as a foreignkey (charfield type)?? Thanks -
Django Whitenoise 500 server error in non debug mode
I am using django in my local machine. Inorder to serve the static files I used WhiteNoise along with it. When DEBUG = True all static files are correctly served. But when I changed DEBUG = False and set ALLOWED_HOSTS = ['*'] I'm getting 500 server error. However admin site loads without any error. Also when I comment out STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I don't get 500 error. I followed the documentation given in http://whitenoise.evans.io/en/stable/django.html to connect whitenoise. I haven't made any changes to wsgi.py file. I ran python manage.py collecststatic and it ran without any errors. The settings.py is given below : import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'fdft&b(xb*!qq3ghjkjhg6789ih8ik!w10$0uscxcpqpmz' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', #Disable Djangos static file server during DEVELOPMENT 'gep_app.apps.GepAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'gep_project.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', ], }, }, ] WSGI_APPLICATION = 'gep_project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '*************', 'USER': '*****', 'PASSWORD': '********', 'HOST': '*****', 'PORT': '5432', } } # User model AUTH_USER_MODEL = 'gep_app.User' … -
URL like tree with 2 models CBV
I have 3 models: 1) dish(fk dishclass) 2) dishtype(fk dishtype) 3) dishclass Dishclass can be without dishtype. Example: 1)obj1 dishtype = Margarita; dishclass = Pizza 2)obj2 dishtype = Alfonso; dishclass = Pizza 3)obj3 dishtype = Burger; dishclass = none Then i make ListView with object on url /dish/: Pizza(if obj have dishclass, show only dishclass) Burger I want this logic: if i click to Pizza -> /dish/pizza/ and have objects Margarita and Alfonso-> clik to name of pizza and go to /dish/pizza/margarita etc. if i click to Burger -> /dish/burger/ Now my code is working only like this: /dish/burger/ and /dishclass/pizza I try this code: Models class DishClass(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() def get_absolute_url(self): return reverse('dishclass_detail', kwargs={'slug': self.slug}) class DishType(models.Model): name = models.CharField(max_length=50, blank=True, null=True, default=None) dishclass = models.ForeignKey(DishClass, blank=True, null=True) slug = models.SlugField() def get_absolute_url(self): return reverse('dish_detail', kwargs={'slug': self.slug}) class Dish(models.Model): dishtype = models.ForeignKey(DishType) name = models.CharField(max_length=100) slug = models.SlugField() Views class DishListView(ListView): model = Dish template_name = 'dish.html' def get_context_data(self, *args, **kwargs): context = super(DishListView, self).get_context_data(*args, **kwargs) alltypes = DishType.objects.all() all_dish = Dish.objects.all() dict = {} k = 0 for category in alltypes: for dishes in all_dish: if dishes.dish.dishtype.name == category.name: k=k+1 if category.dishclass: if category.dishclass … -
How to save a **python-doc** object to a **DRF** model
I have a Django Rest Framework view that generates python-docx objects, and I want to save such files in a model. I read in the documentation of python-docx that you can specify a "file-like" object to save the object, but I don't understand what it means. This is my view: class RoomingWordView(viewsets.ViewSet): def list(self, request, *args, **kwargs): ... some code documents_to_return = self.get_hotel_document(start_date, end_date, confirmed, hotel, bookings) return Response(documents_to_return) def get_hotel_document(self, start_date, end_date, confirmed, hotel, bookings): from django.core.files import File from docx import Document from docx.shared import Inches, Pt document = Document() section = document.sections[-1] section.left_margin = Inches(0.5) section.right_margin = Inches(0.5) style = document.styles['Normal'] font = style.font font.name ='Arial' font.size = Pt(10) document.add_heading("MY COMPANY") if confirmed: document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019 INCLUYE RESERVAS CONFIRMADAS") else: document.add_paragraph("ROOMING LIST DEL 01-12-2018 AL 31-01-2019") document.add_paragraph("Hotel: {}".format(hotel)) table = document.add_table(rows=len(bookings), cols=10) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Booking' hdr_cells[1].text = 'Reservado a' hdr_cells[2].text = '# Pax' hdr_cells[3].text = 'Agencia' hdr_cells[4].text = 'Habs' hdr_cells[5].text = 'Hab./Plan' hdr_cells[6].text = 'Entrada' hdr_cells[7].text = 'Salida' hdr_cells[8].text = 'Confirmación' hdr_cells[9].text = 'Producción' for cell in table.rows[0].cells: paragraphs = cell.paragraphs for paragraph in paragraphs: for run in paragraph.runs: run.underline = True for booking in bookings['bookings']: row_cells = table.add_row().cells row_cells[0].text = … -
How to add database routers to a Django project
I'm following the instructions on how to handle multiple databases within one Django project from here topics/db/multi-db I've created the two routers required. They are saved as ./database_routers/discourse.py and ./database_routers/wordpress.py I created an empty database_routers/init.py file The database router settings in api/settings I've set to DATABASE_ROUTERS = ['database_routers.DiscourseRouter', 'database_routers.WordpressRouter'] When I attempt to look at the project using shell plus I with ./manage.py shell_plus I get ImportError: Module "database_routers" does not define a "DiscourseRouter" attribute/class How do you add classes to a module such that python recognises the path directory_name.ClassName? -
Django, edit existing model istance and associated by foregin key other models
I have to do very complicated form: For edititing Gate instance and connected by ForeginKey GateFile instances Changes could be applied also for other Gate instances (with other Tram-ForeginKey) models.py class Gate(models.Model): CAR_SYMBOLS = ( ('C1', u'C1'), ('C2', u'C2'), ('C3', u'C3'), ('C4', u'C4') ) GATE_STATUSES = ( ('R', u'Realizacja'), ('O', u'Ocena DZJ'), ('P', u'Ponowna realizacja'), ('A', u'Archiwum') ) GATE_GRADES = ( ('OK', u'Zaakceptowany'), ('NOK', u'Odrzucony') ) tram = models.ForeignKey(Tram, null=True, on_delete=models.CASCADE) car = models.CharField(choices=CAR_SYMBOLS, max_length=2) area = models.ForeignKey(OperationArea, null=True, on_delete=models.CASCADE) operation_no = models.CharField(max_length=6) name = models.CharField(max_length=200) content = models.TextField() gate_status = models.CharField(choices=GATE_STATUSES, default='R', max_length=1) gate_rating = models.CharField(choices=GATE_GRADES, blank=True, max_length=3) reject_counter = models.IntegerField(default='0') author = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='author') creation_date = models.DateTimeField(default=datetime.now(), blank=True) modify_date = models.DateTimeField(default='', blank=True, null=True) objects = models.Manager class Meta: ordering = ('-tram',) permissions = ( ('can_change_gate_status', u'Może zmenić status bramki'), ('can_change_gate_rating', u'Może zmienić ocenę bramki'), ('can_add_new_gate', u'Może dodać nową bramkę') ) unique_together = ('tram', 'car', 'area', 'operation_no') def __str__(self): return self.name def get_absolute_url(self): return reverse('qapp:gate_details', args=[ self.tram, self.car, self.area, self.operation_no, ]) class GateFile(models.Model): file_rel_gate = models.ForeignKey(Gate, on_delete=models.CASCADE) file = models.FileField(upload_to='uploads_g', blank=True, null=True) def filename(self): return ntpath.basename(self.file.name) forms.py class GateChangeForm(forms.ModelForm): trams_to_apply = forms.ModelMultipleChoiceField(queryset=Tram.objects.all(), label=u'Tramwaje do wprowadzenia zmiany') class Meta: model = Gate fields = ['tram', 'car', 'area', 'name', …