Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to pip install psycopg2
I have been trying to google this all over the internet and still can't figure out how to get this package installed. Any help is much appreciated. I have tried numerous examples from google to no avail. Mac OS 10.15.3 pip freeze asgiref==3.2.5 dj-database-url==0.5.0 Django==3.0.4 entrypoints==0.3 flake8==3.7.9 gunicorn==20.0.4 mccabe==0.6.1 postgres==3.0.0 psycopg2-binary==2.8.4 psycopg2-pool==1.1 pycodestyle==2.5.0 pyflakes==2.1.1 pytz==2019.3 sqlparse==0.3.1 whitenoise==5.0.1 pip install psycopg2 Collecting psycopg2 Using cached psycopg2-2.8.4.tar.gz (377 kB) ERROR: Command errored out with exit status 1: command: /Users/keeganleary/Documents/Coding/life_cal/venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '" '"'/private/var/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/setup.py'"'"'; __file__='"'"'/private/va r/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open )(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/pip-egg-info cwd: /private/var/folders/s6/f4q9mnjn7q9b34gw7bz35l680000gn/T/pip-install-qwbzap8s/psycopg2/ Complete output (12 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/__init__.py", line 20, in <mo dule> from setuptools.dist import Distribution, Feature File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/dist.py", line 34, in <module > from setuptools.depends import Require File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/depends.py", line 7, in <modu le> from .py33compat import Bytecode File "/Users/keeganleary/Documents/Coding/life_cal/venv/lib/python3.8/site-packages/setuptools/py33compat.py", line 2, in <m odule> import array ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/array.cpython-38-darwin.so, 2) : no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/array.cpython-38-darwin.so: code signature in (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/array.cpython-38-darwin.so) not valid for use in proc ess using Library Validation: Library load disallowed by System Policy ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info … -
Django+Postgres FATAL: sorry, too many clients already
I get the "FATAL: sorry, too many clients already" every now and then because I have a lot of idle connecions in Postgres, and I cannot understand where they are coming from or how to prevent them. At first I tried the CONN_MAX_AGE setting in Django but it does not seem to have an effect. I also set idle_in_transaction_session_timeout to 5min in Postgres, but I keep seeing a lot of idle transactions: postgres=# select client_addr, state, count(*) from pg_stat_activity group by client_addr, state; client_addr | state | count ---------------+--------+------- | | 5 | active | 1 | idle | 1 172.30.12.148 | idle | 2 172.30.12.74 | idle | 89 (5 rows) postgres=# select client_addr, state, backend_start, query_start from pg_stat_activity order by query_start ; client_addr | state | backend_start | query_start ---------------+--------+-------------------------------+------------------------------- | idle | 2020-03-24 20:03:16.060707+00 | 2020-03-24 20:55:17.020962+00 172.30.12.74 | idle | 2020-03-25 02:05:32.567976+00 | 2020-03-25 02:05:32.613112+00 172.30.12.74 | idle | 2020-03-25 02:05:34.926656+00 | 2020-03-25 02:05:34.945405+00 172.30.12.74 | idle | 2020-03-25 02:05:49.700201+00 | 2020-03-25 02:05:49.717165+00 [...] 172.30.12.74 | idle | 2020-03-25 04:00:51.019892+00 | 2020-03-25 04:01:22.627659+00 172.30.12.74 | idle | 2020-03-25 04:04:18.333413+00 | 2020-03-25 04:04:18.350539+00 172.30.12.74 | idle | 2020-03-25 04:04:35.157547+00 | 2020-03-25 04:05:16.746978+00 172.30.12.74 | idle | 2020-03-25 … -
Indexes in Django PostgreSQL
MY MODEL Below is the code for my model class Email_passwords(models.Model): email = models.CharField(db_index=True, max_length=50) password = models.CharField(db_index=True, max_length=40) source = models.CharField(default='unknown', max_length=150) domain = models.CharField(db_index=True, max_length=50) before_at = models.CharField(max_length=255) username = models.CharField(db_index=True, max_length=150) hash = models.CharField(db_index=True, max_length=255) ipaddress = models.CharField(db_index=True, max_length=50) phonenumber = models.CharField(db_index=True, max_length=100) class Meta: constraints = [ models.UniqueConstraint(fields=['email', 'password', 'source'], name='email password source unique') ] index_together = [ ("domain", "before_at"), ] def __str__(self): return self.email I was expecting total 7 indexes on this table but when i checked in database i got like 17 are there by default indexes on the table As you can see by clicking here the indexes for the table created by above model What i want is to perform search using one field at a time though table.This table my contains billions of record. I want to achieve the maximum performance. -
Choosing a backend web language for a newbie
I'm not sure if this is the appropriate place to put this question, I'm relatively new here, so I apologize if it's not. I'm not a big fan of front end development (or Javascript, but I'd learn it if necessary) and thought I'd learn backend instead, as I think may enjoy that more. My main goal is to obtain a job (I have no issues with moving states/countries either) while also working on my own personal projects like a blog, portfolio, web apps, and such. I have some experience with JS, C#, and Python, but honestly, I'm not even sure where to start, and have no problems delving into a language, even if it's not one I know. I've been debating between node.js, asp.net, django/flask, or ruby on rails, but looking for a more informed opinion. Here are some of the questions rolling around in my head: Which one offers me the most potential for jobs? Which is easiest for a beginner to get into? Which is most recommended in general? All advice and suggestions welcome, or even answers to questions I can't even think of. Thank you all very much for your time and opinions! -
Django serializer not saving data during create
I am trying to save data by creating serializer. I have the data passed in as the serializer's argument, and after validating and saving the serializer, I can see the data when I print (serializer). However, if I print(serializer.data), part of the data is missing. view: class TaskList(generics.ListCreateAPIView): serializer_class = TaskSerializer pagination_class = None permission_classes = [IsAuthenticated ] def get_queryset(self): return TaskProject.objects.all().filter(users=self.request.user) def create(self, request, *args, **kwargs): data=request.data projects = [] for id in request.data['projects'].split(','): projects.append(Project.objects.get(id=id)) data['projects']=projects serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer,projects) headers = {} print("serializer data",serializer.data) print("serializer",serializer) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer, projects): print(projects) obj = serializer.save(users=[self.request.user]) if not self.request.user.is_superuser: ProjectRoleMapping.objects.create(user=self.request.user, task=obj, role=Role.objects.get_or_create(name=settings.ROLE_PROJECT_ADMIN)[0]) serializer: class ProjectSerializer(serializers.ModelSerializer): current_users_role = serializers.SerializerMethodField() def get_current_users_role(self, instance): print("p in serializer") role_abstractor = { "is_project_admin": settings.ROLE_PROJECT_ADMIN, "is_annotator": settings.ROLE_ANNOTATOR, "is_annotation_approver": settings.ROLE_ANNOTATION_APPROVER, } queryset = ProjectRoleMapping.objects.values("role_id__name") if queryset: users_role = get_object_or_404( queryset, project=instance.id, user=self.context.get("request").user.id ) for key, val in role_abstractor.items(): role_abstractor[key] = users_role["role_id__name"] == val return role_abstractor class Meta: model = Project fields = ('id', 'name', 'description', 'guideline', 'users', 'current_users_role', 'project_type', 'image', 'updated_at', 'randomize_document_order', 'collaborative_annotation') read_only_fields = ('image', 'updated_at', 'current_users_role') class TaskSerializer(ProjectSerializer): class Meta: model = TaskProject fields = ('id', 'name', 'description', 'guideline', 'users', 'current_users_role', 'updated_at', 'ignore_unlabeled_files', 'project_type', 'projects') read_only_fields = ('updated_at', 'current_users_role', 'users', 'projects') … -
Django order by custom list
I have problem of ordering the queryset. For example, it will be sorted desc. If they have same priority so can't define specific order, they will use second priority. # list = [[id, priority], ...] list_1 = [[1,2],[2,3],[3,3],[4,4]] # first priority list_2 = [[1,4],[2,5],[3,7],[4,2]] # second priority using first priority : 4 -> (2,3) -> 1 using second priority : 4 -> 3 -> 2 -> 1 result = 4 -> 3 -> 2 -> 1 So i want to get queryset, ordered like result id sequence. -
How Calculate Hours and OT Hours, save to database?
I'm trying to calculate login and logout and convert it into total hours. If the time exceeds 9 hours it should then calculate OThours. Then save both total hours and OThours into my model. How can I go around this? I know it's by using property but I'm not sure how to get the syntax right with this. I just need some advice and insight on what to do, any help is appreciated TIA. Here is my code: testuser = models.ForeignKey(User,on_delete = models.CASCADE,unique_for_date= 'reportDate') status = models.CharField(max_length=30, choices=STATUS_CHOICES,null=True) reportDate = models.DateField(blank=False, null=False) login = models.TimeField(blank=False, null=False) logout = models.TimeField(blank=False, null=False) totalHours = models.DecimalField(max_digits=4,decimal_places=2,null=True) OTHours = models.DecimalField(max_digits=4,decimal_places=2,null=True) mainTasks = models.CharField(max_length=50, blank=False, choices=TASKS_CHOICES, null=True) remarks = models.CharField(max_length=30,null=True) def __str__(self): return f'{self.testuser.full_name} DPR Log' @property def CalculateTotalHours(self): self.totalHours = self.logout.timeDelta - self.login.TimeDelta return self.TotalHours @property def OTHours(self): if self.totalHours > 9.00: self.OTHours = self.totalHours-9.00 -
how to add a custom field that is not present in database in graphene django
so my model looks like class Abcd(models.Model): name = models.CharField(max_length=30, default=False) data = models.CharField(max_length=500, blank=True, default=False) need to pass a dictionary at query time which is not a part of model, query is query { allAbcd(Name: "XYZ") { edges { node { Data } } } } How does one pass such a custom field with the query ?. This custom field is required for other process purpose. -
get user id in Django clas based view
i'm trying to implement the following class View and populate customer field with a filtered list of customers retrieved from Customers Model but filtered by user id class SellCreateView(CreateView): model = Sell fields = [ 'name', 'store', 'customer', ] in function based view i do something like the following: def sell_create(request): customer_list = Customer.objects.filter(belongs_to=request.user.id) ... form.fields['customer'].queryset = customer_list but i can't make this work in class view! Any idea how should i do this? Thanks! -
Using Django how to format fields rendered by __all__
I am using Django. Getting fields from database > models > forms by using all. I would like to place the fields in the html to my convenience. How to go ahead with that? -
mod_wsgi cannot import django, but local python can do
Please help me. What I want to do I want to deploy my Django application. Sample code reproduce probrem import django def application(environ, start_response): start_response("200 OK", [("Content-type", "text/plain")]) return ['hello, world'.encode('utf-8')] This works well when I start python from console, but raise ModuleNotFoundError when I call this from web browser (No module named 'django'). $ python3 Python 3.8.2 (default, Mar 24 2020, 02:28:58) [GCC 7.5.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import wsgi >>> wsgi.application(None, lambda x, y: print(x, y)) 200 OK [('Content-type', 'text/plain')] [b'hello, world'] [Wed Mar 25 02:27:58.115629 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] mod_wsgi (pid=1717): Failed to exec Python script file '/home/ubuntu/grabar/wsgi.py'. [Wed Mar 25 02:27:58.115706 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] mod_wsgi (pid=1717): Exception occurred processing WSGI script '/home/ubuntu/grabar/wsgi.py'. [Wed Mar 25 02:27:58.115888 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] Traceback (most recent call last): [Wed Mar 25 02:27:58.115917 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] File "/home/ubuntu/grabar/wsgi.py", line 1, in <module> [Wed Mar 25 02:27:58.115924 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] import django [Wed Mar 25 02:27:58.115955 2020] [wsgi:error] [pid 1717:tid 140665380144896] [remote 60.65.57.85:53170] ModuleNotFoundError: No module named 'django' [Wed Mar 25 02:27:58.410154 2020] [authz_core:error] [pid … -
How to pass django user authentication data to react app?
I am doing a project by using django as front and back-end. But recently I want to attach another react page on this project. So, what I want to do is passing the user's info and mounting inside react. Below is my django's structure, I bundled my react app and put it on django's front-end (inside a toolbar). Normally, in django front-end, using request.user can get user's auth data. But how can I pass it to my react page? Thanks in advance! **urls.py:** url(r'test/', TestView, name='TestView') **views.py** def TestView(request): template_name = 'test.html' context = {} return render(request, template_name, context) **test.html:** <!DOCTYPE html> <html lang="en"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root" style="height:100%"></div> <script src="../../../test_bundle.js"></script> </html> **main_html.py:** <div class="item"> <div class="ui dropdown" id="test"> <a class="item" onclick="load_test();">Test Component</a> </div> </div> <script> function load_test() { div_reload('#test', '/test/', 'GET', 'html'); } </script> -
drag and drop web page builder that we can export the source code to use in a Django project?
Is there any drag and drop web page builder (same as elementor) that we can export the source code to use in a Django project? -
Remove an item and reverse URL lookup at same time
I am building a calendar application in Django. I have implemented functionality to let a user add/remove Highlights to his/her week. Since the highlights are rendered on each individual week's page, I want to return the user to that page after deleting the highlight from the database. However, my remove_note() method takes 2 parameters (request, note_id). In the method, I query the database for the week associated with that note so that I can redirect the user to the week_view of the corresponding week_number. My thought - is there a way to pass note_id and week_number from the week_view.html to reduce database calls? I tried but couldn't quite get there myself. Thank You! views.py from django.shortcuts import render, get_object_or_404, redirect from week.models import Week, Note from week.forms import NoteForm def index(request): week_list = Week.objects.filter(user_id=request.user.id).order_by('week_number') context = { 'week_list': week_list, 'cal_width': range(52), } return render(request, 'cal/index.html', context) def week_view(request, week_number): if request.method == "POST": week = get_object_or_404(Week, week_number=week_number, user_id=request.user.id) form = NoteForm(request.POST) if form.is_valid(): form = form.cleaned_data new_note = Note(text=form['text'], week=week) new_note.save() context = { 'week': week, 'form': NoteForm(), 'notes': week.note_set.all(), } return render(request, 'cal/week_view.html', context) else: week = get_object_or_404(Week, week_number=week_number, user_id=request.user.id) context = { 'week': week, 'form': NoteForm(), 'notes': week.note_set.all(), … -
How can i handle django nested models in front-end?
I have a User, Post and Tag model in Django. Tag model is not relevant for this topic. I am trying to get all the data in the front end with nested objects. I can succesfully did that.When i want to create a new post i send the post data to django and in django view i update the data with current logged user but when i do that it gives me; {'owner': {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}} error. How can i achive what I want ? models.py; class Post(models.Model): # Post specs title = models.CharField(max_length=100, null=False) place = models.CharField(max_length=100, null=False) notes = models.CharField(max_length=10000, null=False) tags = models.ManyToManyField(Tag) start_date = models.DateField(null=True) end_date = models.DateField(null=True) created_at = models.DateField(auto_now=True) owner = models.ForeignKey(User , null = True, on_delete=models.SET_NULL) serializers.py; class PostSerializer(serializers.ModelSerializer): tags = serializers.SlugRelatedField( many=True, queryset=Tag.objects.all(), slug_field='name' ) owner = UserSerializer() class Meta: model = Post fields = ('title','place','notes','start_date','end_date','created_at','id','owner','tags') and view post function; def post(self, request, format =None): """ Creates a post """ print(request.data) post = request.data post.update( {'owner':request.user.id}) serializer = PostSerializer(data = post) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_201_CREATED) print("not valid->",serializer.errors) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) -
DJANGO: About linkinf wto tables with ForeignKey
Hello all and thanks for all the DAILY support, really. Now, something I swear can not find answred in between many examples and related topics: I have a VEHICLES model, and a TIRES model. Both will be linked by a field, PLATE; class Vehicles(models.Model): Plate= models.CharField(max_length=10) Quantity = models.IntegerField(default=0) Vendor = models.CharField(max_length=50) def __str__(self): return self.matricula class Tires(models.Model): Plate = models.ForeignKey(Vehicle, default=0, on_delete=models.SET_DEFAULT) # --- tires would be placed in an exisiting vehicle (plate), or , if not in use, "Tires.Plate=0" Number = models.IntegerField(unique=True) What I need these two allow me to do, an what they really do or do not: Adding records to Vehicles.................YES Adding tires with predefined Plate numbers in a dropdown menu, from Vehicles.Plates....................YES, CHECK Adding tires with Plate number = 0, indicating the tire is not in use by any vehicle.......NO, NOT CHECKED; the menu offers only the exisiting plates in "Vehicles.Plate": Even if I tried adding DEFAULT value. Deleting registers from TIRES.........CHECK Deleting registers from VEHICLES.......NOT CHECKED; doing so, instead of making the corresponding Tires.Plate default to 0, as I would have expected from "...ForeignKey(Vehicle, default=0, on_delete=models.SET_DEFAULT)", I get a "FOREIGN KEY constraint failed" error. So indeed by removing the vehicle i'm causing the error … -
How to extends html file in Django
I want to extend my html file with base.html from template folder inside main my project folder. When I type: {% extends 'base.html' %} it gives me this: TemplateDoesNotExist at /app/ base.html Request Method: GET Request URL: http://127.0.0.1:8000/app/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: base.html Hope I will get some help :) -
Django HTML template table rendering
I want to render a table look like this: <table> <tr> <td>some data</td> <th>special one</th> <td>some data</td> ... <td>some data</td> </tr> ... </table> There is a solution that can render all in the same tag. <table> {% for rowval in results %} <tr> {% for val in rowval %} <td>{{val}}</td> {% endfor %} </tr> {% endfor %} </table> But in my case, there would be a th at the second place for every row of the data, if there is a record. Is there a way to implement this feature? -
Annotate in subquery django
I have a problem with this query: ProductoModel.objects.annotate(suma=Subquery(ValoracionNModel.objects.filter(producto=OuterRef('pk')).values('puntaje').annotate(sum=Sum('puntaje')).values('sum'))) In SQL: SELECT Negocio_productomodel.id, Negocio_productomodel.nombre, Negocio_productomodel.descripcion, Negocio_productomodel.precio, Negocio_productomodel.foto, Negocio_productomodel.aliado_id, Negocio_productomodel.tipo_producto_id, (SELECT SUM(U0.puntaje) AS sum FROM Negocio_valoracionnmodel U0 WHERE U0.producto_id = Negocio_productomodel.id GROUP BY U0.puntaje ORDER BY NULL) AS suma FROM Negocio_productomodel' Error: django.db.utils.OperationalError: (1242, 'Subquery returns more than 1 row') Can you Help me, please? I know the problem in SQL is the GROUP BY, but I don't know how remove this in Django. -
Debugger Docker Containers with Visual Studio Code
I have a Django project in Visual Studio Code. I start it through a virtual machine (linux) using Docker. I want to be able to debug the project by adding breakpoints. I tried following this tutorial, but can't get it: https://code.visualstudio.com/docs/containers/debug-python The application starts in "localhost: 8000", the private IP of the physical machine is 192.168.0.102 and that of the virtual machine: 192.168.56.1. My file launch.json: { "name": "Python: Remote Attach", "type": "python", "request": "attach", "port": 8000, "host": "localhost", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ] } Thanks! -
Django swapping field values
I have a Django model I am developing locally like: import uuid from django.db import models class MyModel(models.Model): uuid = models.UUIDField( _('Non-sequential key for external lookups'), default=uuid.uuid4, editable=False, null=False, unique=True, ) This resulted in a migration like: from django.db import migrations, models import uuid class Migration(migrations.Migration): operations = [ migrations.CreateModel( name='MyModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uuid', models.UUIDField(unique=True, default=uuid.uuid4, editable=False, verbose_name='Non-sequential key for external lookups')), ] This was working great initially; objects I created had both an incrementing integer id and a uuid property, with id mapped to pk. Fast forward a week, and I need to rebuild the database to retest a migration script I'm writing. The script fails, and when I dig into it, I discover that the ID and UUID fields are swapped: $ ./manage.py shell >>> from my_model import MyModel >>> item = MyModel.objects.first() >>> item.pk UUID('cee60e6b-aa2e-48a2-a34c-4315ebacea0b') >>> item.id UUID('cee60e6b-aa2e-48a2-a34c-4315ebacea0b') >>> item.uuid 45384 Has anyone else ever run into anything like this? I'm baffled over what the heck is going on, or what might have changed. The database side looks fine (primary key on the id column, and unique index on the uuid column); it's just Django's mapping that's all screwy. I'm running Django 2.2.9. -
Django - How to use two queries with select_related and render two different type of values in template?
I have the following models: class BillType(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name and the next one: class Bill(models.Model): bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE, related_name='billtype') month = models.CharField(max_length=200) amount = models.IntegerField() due_date = models.DateField(blank=True) note = models.TextField(blank=True) recurring = models.BooleanField(default=True) currency = models.CharField(max_length=100) created_on = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.month In views.py I am fetching all BillType objects and all objects from the Bill model which are related to BillType. However, I will need to fetch all of the objects in the same Bill model based on the due_date column or objects which are overdue, or in other words older than "today". I have tested the last part and it is returning all objects that are older than "today". def billingOverview(request): bill_types = BillType.objects.all() bills = Bill.objects.select_related('bill_type').all() today = datetime.today() overdue = Bill.objects.select_related('bill_type').filter(due_date__lte=today).all() context = { 'bill_types': bill_types, 'bills': bills, 'overdue': overdue } return render(request, 'management/billing-overview.html', context) In the template, I will need to render BillType objects separately in a different container for each of them, for which I have created For loop and it is working well so far. However, for each rendered BillType object, I have Overdue and Latest Bill areas. The first … -
I've been trying to get my images to upload on my website but can't seem to find the media link
`I have 4 classes. A parent able called Product. I also have Category and Variations. I've already migrated everything successfully. I can't see any issues there, and i can see it in my admin. <pre> class Product(models.Model): name = models.TextField() slug = models.SlugField(null=True, unique=True) description = models.TextField() stock = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category',args=[str(self.slug)]) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', blank=True) featured = models.BooleanField(default=False) thumbnail = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __unicode__(self): return self.product.name Here i tried to link my images to media. When i add images to the product it works as a new file is created with the images I added. STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) CRISPY_TEMPLATE_PACK = 'bootstrap3' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = '/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') `How i got my products to display def product(request, category_id=None): category = None products = Product.objects.all() ccat = Category.objects.annotate(num_products=Count('products')) if(category_id): category = get_object_or_404(Category, slug=category_id) products = products.filter(category=category) return render(request, 'product.html', {'products':products, 'countcat':ccat}) How I tried to display the images on the website ``` {% for product in products %} {% for item in product.productimage_set.all %} <img src="{{ … -
How do i write this code more pythonic way
I am writing Django's views to check if a valid album id is provided or not. But it looks cumbersome and hard to read. I want to make it more readable and short. I cant directly check data['id']. It will give error if its blank. def post(self, request): if len(request.body) > 0: data = json.loads(request.body.decode('utf-8')) else: return Response({'message': 'Album id is required'}) if 'id' not in data: return Response({'message': 'Valid Album id is required'}) try: id = int(data['id']) if id < 1: return Response({'message': 'Valid album id is required'}) album = Album.objects.get(pk=id) except: return Response({'message': 'Valid album id is required'}) -
Django generates too many SQL queries for models.ForeignKey
A Model class has a foreign key (models.ForeignKey) referring to another Model class. Django generates too many SQL queries for this foreign key. When a admin.StackedInline class uses the Model class, it tries to make a select list containing all items in the referred-to table (ProductTemplate in sample code below). Is there a way to limit the foreign key to only list one item, instead of all items in the referred-to table? Any other suggestions will also be highly appreciated. Let me know if you need more details. In file admin.py: ... class TransactionAttributeInlineAttribute(admin.StackedInline): model = models.TransactionAttribute verbose_name = 'Transaction Link' verbose_name_plural = 'Product Links' class MyAttributeAdmin(admin.ModelAdmin): inlines = [TransactionAttributeInlineAttribute] list_display = ['name','datatype','required'] ... In file models.py: ... class TransactionAttribute(models.Model): product_template = models.ForeignKey(ProductTemplate) ...