Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django if statement has an error. What should I fix?
a.html <div> {%for r in rank%} {%if r.nickname==nickname%} <div style="color: aqua;">{{r.nickname}}</div> {%else%} <div>{{r.nickname}}</div> {%endif%} <hr> {%endfor%} </div> views.py def ranking(request): user = request.user rank = Profile.objects.all().order_by('-user_test_point') profile_obj = Profile.objects.get(user=user) nickname = profile_obj.nickname context = {"rank": rank, "nickname": nickname} return render(request, "a.html", context) I want to change the color if the nicknames of the current user and the ones in the context are the same. Context contains the nicknames of users. But error is "Could not parse the remainder: '==nickname' from 'r.nickname==nickname'" -
How to solve this error ERROR: Command errored out with exit status 1: command: 'c:\users\sanid\appdata\local\pr
**This happened when i tried to install mysqlclient via typing pip install mysqlclient ** earlier also i had an error which i solved by installing Visual studio c++ , But what should i do ???? I also saw some solutions but they don't seem to work so if anyone can tell what to do, Please explain in detail as i am new to programming Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\sanid\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\sanid\\AppData\\Local\\Temp\\pip-install-koqe6sxg\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\sanid\\AppData\\Local\\Temp\\pip-install-koqe6sxg\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\sanid\AppData\Local\Temp\pip-wheel-j4e3bxnr' cwd: C:\Users\sanid\AppData\Local\Temp\pip-install-koqe6sxg\mysqlclient\ Complete output (29 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.27.29110\bin\HostX86\x86\cl.exe … -
Django Model designing with M2M
I need some help regarding models designing. I have two models like this (with M2M Field) class Control(models.Model): id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default=NOT_PLANNED, blank=True, null=True) class Vulnerability(models.Model): id = models.CharField(max_length=25, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) level = models.PositiveSmallIntegerField() controls = models.ManyToManyField("Control", verbose_name="control",) What I want to do : When I create a vulnerability with several controls, each control have a weight for the vulnerability. So I can't create a weight field in my control, since it'll be a weight for each vulnerability. The only thing I found is to create a new "linking" class : class VulnerabilityControl(models.Model) vulnerability = models.ForeignKey(....) control = models.ForeignKey(...) weight = models.PositiveSmallIntegerField() But it create a new table etc.. Is there a better way to do this ? Thanks ! -
Django download files
I'm working in a project which I want display many images in a website, so the user can download them. I can display the name of the images, but the download isn't working. I think it's something on my views, because I'm using Django, and getting the error the current path ... didn't match any of this. The name of the directory with the images is Images, and has others sub directories inside, and inside those sub directories, there are the images. My views page, I think the problem is here, in the download function: from django.shortcuts import render import os from django.http import HttpResponse, Http404 from django.http import FileResponse def index(request): flPath = os.listdir('Images/') fl4 = [] for root, dirs, files in os.walk("Images/", topdown=False): for name in files: fl4.append(os.path.join(root, name)) for name in dirs: fl4.append(os.path.join(root, name)) return render(request, 'catalog/index.html', {'path': fl4}) def downloadImage(request, path): imagePath = 'Images/' file_path = os.path.join(imagePath, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type='text/csv') response['Content-Disposition'] = 'inline; filename=' + file_path return response raise Http404 My app urls, catalog.urls: from django.urls import path, include from .views import * urlpatterns = [ path('', index, name='index'), path('Images/<str:path>', downloadImage, name='download'), ] My project urls, SiteSmu4Img: … -
How to integrate any payment gateway for website?
Can someone tell me how to build a website that allows only paid users? I have searched in several sites, I need some sample to create a website, I have a beautiful concept but I couldn't find anything related to mine! waiting for your explanation techies! -
How to manage manytomany field on admin page in Django?
I have two class, class Activity(LTIModel, Position): name = models.CharField(max_length=255, null=False) parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True) student = models.ManyToManyField(User, related_name="learn", blank=True) @admin.register(Activity) class ActivityAdmin(admin.ModelAdmin): list_display = ('name',) I want to manage (add, delete , modify ...) the student field of an activity on the admin page. manytomany student list When i click on a student nothing is happening. Thank you for your help. -
Django base64 TypeError __str__ returned non-string (type bytes)
i got this error: TypeError at /productos/productos/ str returned non-string (type bytes) i think is a problem from convert from base64bits to str, but i dont know how to fix it, im using Procedures on oracle but its dont seem to be an issue. Im ussing django 3.1, oracle database 18c. all works perfectly since i implement the image blob, its a requeriment so i have to use it. At line 56: return render(request, "productos/productos.html", data) views.py def product(request): data = { 'product':() } if request.method == 'POST': id_producto = request.POST.get('id_producto') nombre = request.POST.get('nombre') tipo = request.POST.get('tipo') descripcion = request.POST.get('descripcion') stock = request.POST.get('stock') precio = request.POST.get('precio') catalogo = request.POST.get('catalogo') imagen = request.FILES['imagen'].read() salida = agregar_producto(id_producto,nombre,tipo,descripcion,stock,precio,catalogo,imagen) if salida == 1: data['mensaje'] = 'added sucessfully' data['productos'] = product_list() else: data['mensaje'] = 'cannot save' return render(request, "productos/productos.html", data) def product_list(): django_cursor = connection.cursor() cursor = django_cursor.connection.cursor() out_cur = django_cursor.connection.cursor() cursor.callproc("sp_product_list", [out_cur]) row = [] for row in out_cur: data = { 'data':row, 'imagen':str(base64.b64encode(row[7].read()), 'utf-8') } lista.append(data) return row productos.html Error during template rendering In template C:\Users\galli\desarrollo-web-36sk8mafia\trisix\plantillas\plantilla.html, error at line 0 str returned non-string (type bytes) {% extends "plantilla.html" %} {% load static %} <title>{% block title %}Productos {% endblock %}</title> {% block content … -
Converting Django BooleanField to NullBooleanField and changing default
I need to change a field from my_boolean = models.BooleanField(verbose_name="Safe Visiting Space", default=False) to my_boolean = models.NullBooleanField(verbose_name="Safe Visiting Space", default=None, blank=True, null=True) So I've made the above change within the model and run makemigrations to create from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', '0164_auto_20201027_0820'), ] operations = [ migrations.AlterField( model_name='mymodel', name='my_boolean', field=models.NullBooleanField(default=None, verbose_name='Safe Visiting Space'), ), ] But this will not set the default of the current 70k records to None but will leave them as False, so I amended the migrations file to from django.db import migrations, models from my_app.models import MyModel def set_my_boolean_default(apps, schema_editor): objects= MyModel.objects.active().filter(my_boolean=False) for object in objectss: object.my_boolean = None object.save() class Migration(migrations.Migration): dependencies = [ ('providers', '0164_auto_20201027_0820'), ] operations = [ migrations.AlterField( model_name='organisation', name='infection_control_safe_visiting_space', field=models.NullBooleanField(default=None, verbose_name='Safe Visiting Space'), ), migrations.RunPython(set_my_boolean_default), ] This will take hours to run. Also, a random check of the database and it doesn't seem to be updating any of the records. What is the right / better way to do this? -
How can I order a DRF queryset by a column computed by multiple relations?
My data model is based on the following relationships: Every Person belongs to an Organization. People can have multiple Addresses. An Organization can have multiple Addresses. Here is the model definition: from django.db.models import ( Model, ForeignKey, CASCADE, CharField, FloatField, ) class Organization(Model): name = CharField(max_length=100) class Person(Model): organization = ForeignKey(Organization, on_delete=models.SET_NULL, related_name='people') class Address(Model): street_number = models.CharField(max_length=20) route = models.CharField(max_length=100) locality = models.ForeignKey(Locality, on_delete=models.CASCADE, related_name='addresses') geometry = PointField(geography=True) class PersonAddress(Model): subject = ForeignKey(Person, on_delete=CASCADE, related_name='person_addresses') value = ForeignKey(Address, on_delete=CASCADE, related_name='person_addresses') class OrganizationAddress(Model): subject = ForeignKey(Organization, on_delete=CASCADE, related_name='organization_addresses') value = ForeignKey(Address, on_delete=CASCADE, related_name='organization_addresses') In a DRF ListCreateAPIView I want to generate a queryset with the following logic: Given a target location (say, lon=10.3, lat= 50.6), list people ordered by distance to either their closest address or their organization's closest address (whichever is closer). So, something along the lines of this SQL query: select distinct round(ST_Distance(ST_GeogFromText('SRID=4326;POINT(10.3 50.6)'), a.geometry))/1000 as "distance", p.id, p.first_name, p.last_name, o.name, a.id, a.route, a.street_number from person p, organization o, personaddress pa, organizationaddress oa, address a where p.organization_id = o.id and p.id = pa.subject_id and o.id = oa.subject_id and ( pa.value_id = a.id or oa.value_id = a.id) order by distance, p.id I think this can be achieved using annotations. … -
How to Calculate days between two dates using Python?
I want to calculate Number of days Between Two Dates using Python Django. Here is my code In my Html, <form method='post' action="something"> <input type="date" name="firstdate"> <input type="date" " name="lastdate"> <input type="submit"> </form> i am sending this form data to view function,i am getting date overthere in dd-mm-yy formet. and if i print overthere, i am getting firstdate and lastdate in below formet, 2020-01-01 2020-02-01 i want to calculate number of days between these two dates.How to Do that? i will be thankfull if anyone can help me with this issue. -
How to create uuid4 file names for uploaded file?
I want to create file names with uuid4 but after saving file and i checked file name, i found it not correct: lets say uuid.uuid4() = 49b9301e-d479-480b-bd41-3054a32d1cf0 so filename should be 49b9301e-d479-480b-bd41-3054a32d1cf0.jpg for example, but if found file name 49b9301e-d479-480b-bd41-30_qJw5Wee.jpg file name ex my model class Attachment(models.Model): file = models.FileField(upload_to=get_upload_path) get_upload_path function:- def get_upload_path(instance, filename): file_extension = filename.split('.') file_extension = file_extension[-1] filename = "%s.%s" % (uuid.uuid4(), file_extension) date = arrow.get(instance.date_created).date() return os.path.join("%s/%s/%s" % (str(date.year), str(date.month), filename)) -
I want to send weekly emails in my Django app. Where should the code that pulls the data from the database and sends the email message live?
The title contains the question - I want to send weekly emails in my Django app. Where should the code that pulls the data from the database and sends the email message live? I have seen examples of code that sends emails, such as this and this, but it is not specified in which file it resides and what's its relationship to the rest of the Django elements. -
Django Cache can I partially clear the cache for specific object view?
I use Django and Redis for caching. from django.views.decorators.cache import cache_page @cache_page(60 * 3) def user_detail(request, id): ... some data return and example url path('users/<int:pk>/', user_detail, name='user-detail') How do I clear the cache for a specific user (for ID = 10 for example) ? http://localhost:8000/users/10/ -
If and or operator django admin models
Im trying to make some kind of logic function " sufficient_information_provided " which returns boolean. As for now im new to python syntax.. i would appreciate if anyone could help figure this out, here is the model in django app class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=models.PROTECT) dependant_child_age_range = models.ForeignKey(DependantChildAgeRange, null=True, blank=True, on_delete=models.PROTECT) care_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) income = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) and here is the function in same .py folder @property def sufficient_information_provided(self): b = ('Tenant', 'Partner') if ( self.name and self.date_of_birth and self.relationship and( ( self.relationship.name not in b and self.dependant_child_age_range ) or ( self.relationship.name in b and self.income ) ) ): return True return False what im trying to do is when relationship.name not in the tuple and dependant_age_range is not null and when relationship.name is in the tuple and self.income is not null returns true else returns false here is the admin looks returns true when it should return false. -
Django Rest Framework: Unable to see view or individual files
I am trying to upload file and then trying to see the files in the list view. For example, I would like my uploaded files to show at /files/upload/ and I would like to see each individual item at files/upload/1 or files/upload/file-name. I have created a model and view but I cant seem to find the url to access it. For instance, the pattern Django gives is api/v1/files ^upload/$ [name='lessonpdfmodel-list'] api/v1/files ^upload/(?P<pk>[^/.]+)/$ [name='lessonpdfmodel-detail' The only thing I saved is a file called pokemon.pdf what is that url? is it localhost:8000/files/upload/pokemon.pdf? My Model is: class LessonPDFModel(models.Model): title = models.CharField(max_length=80) description = models.CharField(max_length=225) upload_date = models.DateTimeField(auto_now_add=True) pdf = models.FileField(blank=False, null=False, upload_to='pdfs/') icon = models.ImageField(blank=False, null=False, upload_to='images/') class Meta: ordering = ['upload_date'] def __str__(self): return f"{self.title}" My View is: class LessonPDFViewSet(ModelViewSet): queryset = LessonPDFModel.objects.all() serializer_class = LessonPDFModelSerializer My serializers is: class LessonPDFModelSerializer(serializers.ModelSerializer): # file_uploaded = FileField() class Meta: model = LessonPDFModel fields = ('pdf', 'description', 'upload_date') def create(self, validated_data): return LessonPDFModel.object, create(**validated_data) my urls is: router = routers.SimpleRouter() router.register('upload', LessonPDFViewSet) urlpatterns = [ path('', include(router.urls)), ] -
Django two separate project under one domain as sub directories
I am trying to config Two separate Django project under one domain name as subdirectories, So I can open project1 as https://mycompany.example.com/project1 and project 2 as https://mycompany.example.com/project2 here is my Nginx configuration server { server_name mycompany.example.com; location /static { alias /home/username/project1/static; } location /media { alias /home/username/project1/media; } location /project1/ { rewrite ^/project1/(.*)$ /$1 break; proxy_set_header X-Script-Name /project1; proxy_pass http://unix:/run/project1.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /project2/ { rewrite ^/project2/(.*)$ /$1 break; proxy_set_header X-Script-Name /project2; proxy_pass http://unix:/run/project2.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mycompany.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mycompany.example.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 } This configuration works and I can open it as I mentioned it above, here the problem is static and media location. Only one project's static and media location can be defined here. I need to config static and media location for both the projects, is there any workaround to make … -
how to fix ModuleNotFoundError in django?
I have one project called mysite and two apps (projects, search). I want to import the models from my projects app to my search app views. search.views.py from django.db import models from django.db.models import Q from django.shortcuts import render from projects.models import Project projects.models.py from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") def __str__(self): return (f"{self.title}, {self.description}, {self.technology}") error Traceback (most recent call last): File "d:/firstwebapp/mysite/search/views.py", line 9, in <module> from projects.models import Project ModuleNotFoundError: No module named 'projects' -
In template,I'm passing an object in a loop to show all items in the list
I have created a model object called Store and passed it to a django template and called it in a for loop within a POST form as the following: ` {% csrf_token %} <br/><br/> <br/> <div class="row"> {% for store in stores %} <input type="hidden" name="store_id" value="{{store.id}}"> <input type="submit" value="{{store.store_name}}{{store.id}}" class="button store-button" type="button"> {% endfor %} </div> </form>` It works fine, shows all the buttons with each store name and id on clickinig the button it submits the form and takes me to next template where I have captured the POST store id and student id and passed them to next page template. But the problem is that the store shown is always the last added stor, no matter which button I press in the first page of the POST form, but the buttons show the different stores and their ids perfectly, I can't understand why this is happening as not even an error is shown, please help me, thanks in advance. -
Django queryset. Retrieve only the last 3 created objects for all stores
My platform have a Product and a Store models and I want to retrieve only the last 3 created products for all stores. I don't want to iterate over all queryset as in the future there will be many products and stores. I've tried to get the number of newer products and then filter by 0, 1 and 2: products_queryset.annotate(newer_products=Count(Q(store=F('store')) & Q(created__gt=F('created')))).filter(newer_products__lte=3) With this query I'm always getting newer_products=1, so the filter is returning all products. -
DJANGO - how can I filter an object filtering by another object filtered
I'm trying to make an advanced filter with django objects but I just have no clue of how to do it. I'll try to explain myself: I have 2 objects: Consumptions: class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" STATES = [ ('not-prevalidated', 'No prevalidado'), ('prevalidated', 'Prevalidado'), ('pendant', 'Pendiente validación cliente'), ('accepted', 'Aceptado'), ] client = models.ForeignKey('authentication.Client', verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) access_date = models.DateField("Fecha de acceso", auto_now=False, auto_now_add=False) status = models.CharField("Estado", max_length=20, choices=STATES, null=False, blank=False) and Clients class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) And now I want to count all clients that has some consumption in 'pendant' state and in certain date. As you can see consumptions has one client related. I've checked the docs https://docs.djangoproject.com/en/3.1/topics/db/queries/ but I just can't get what I want. Could someone help me? :( -
How to set up Gcloud Flex Environment custom container pylibmc
I am trying to set up memcached for my application. Locally it works just fine. Now time to deploy to a real server, I am using Google cloud app engine flex environment. It's a custom runtime. I am able to install my app just fine, but when it comes time to running, I get a 500 for views that I use Memcached. My first thinking is because of the caches settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } I am thinking it has something to do with this location setting. Being that this '127.0.0.1:11211' works for a local environment, how do I setup a location for gcloud custom runtime flex environment? If that's not why I am getting the 500, what could be the better setup. Here is my docker file: FROM python:3.8 EXPOSE 8080 RUN apt-get update && apt-get install --reinstall -y \ binutils \ libproj-dev \ libmemcached11 \ libmemcachedutil2 \ libmemcached-dev \ libz-dev ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt ADD . . # Run a WSGI server to serve the application. gunicorn must be declared as CMD exec gunicorn --bind :8080 --workers 1 --threads 8 main:app --timeout 0 --preload and app.yaml file: runtime: … -
how to download an uploaded file in django
am creating an option to download a file (pdf) uploaded.just through searching i have across with some instruction (a view) and (url) ,when i try to pass the named url to my template i get this error Reverse for 'download' with no arguments not found. 1 pattern(s) tried: ['download/(?P<filepath>[^/]+)/$'] Just i cant figure a way to download the file.what i want to achieve is that once a download button is place should open a new tab and preview the file and give an option to print or download the file(pdf) using the chrome features. here are the codes views.py import os from django.conf import settings from django.http import HttpResponse, Http404 def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 models.py class Cv(models.Model): filename = models.CharField(max_length=20) upload = models.FileField(upload_to='cv') def __str__(self): return self.filename urls.py path('download/<str:filepath>/', views.download, name="download"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template <a href="{% url 'download' %}" class="btn btn-fill wow fadeInUp" data-wow-duration="0.8s" data-wow-delay="0.4s">Downlaod <i class="fa fa-download"></i></a> help please -
I am unable to loaddata json into my postgres database
Im trying to do the below command but im getting this long error. I have also tried to do go into the dbshell to trucanate as i saw suggested elsewhere but im getting the error that psql is not install or path found even though it should be. I have been succesful in managing to get my tables in the postgres database but their are all empty except a few, which i find strange. My Json dump file has everything it needs in it but it wont transfer over. Anyone have any ideas? (venv) DEMOPROJECT>python manage.py loaddata "datadump.json" Traceback (most recent call last): File "\PycharmProjects\WebP1\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(admin, logentry) already exists. django.db.utils.IntegrityError: Problem installing fixture '\DEMOPROJECT\datadump.json': Could not load contenttypes.ContentType(pk=1): duplicate key value violates unique constraint "django_content_type_app_label_model_76bd3 d3b_uniq" DETAIL: Key (app_label, model)=(admin, logentry) already exists. -
How to pass javascript variable in ajax django url
<script> $(document).ready(function () { $(window).on('beforeunload', function () { $.ajax({ // type: 'GET', url: "{% url 'size_reducer:data_delete' id %}", dataType: 'json', success: function (data) { console.log('ok'); } }) }); }); </script> I want to pass id in ajax URL but it is giving me an error because it's not getting id -
Group by, annotate and display extra data from parent model in Django REST Framework
I have two models related with a foreign key (employee): class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) site = models.CharField(max_length=100) wage = models.DecimalField(max_digits=4, decimal_places=0, default=0) class Record(models.Model): employee = models.ForeignKey(Employee, related_name='employee', on_delete=models.DO_NOTHING) date = models.DateField() cash = models.DecimalField(max_digits=4, decimal_places=0, default=0) I would like to obtain a JSON aggregation for an employee describing total cash he earned and the date_ranges: { "id": 0, "name": "John Doe", "position": "", "site": "", "total_cash": 1500.0, "start_date": "", "end_date": "" } I would like to filter the results based on a date range in the future, so annotating the Employee objects is not an option. Or am I wrong here? What I've done: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['id', 'name', 'position', 'site', 'wage'] class RecordSerializer(serializers.ModelSerializer): employee__id = serializers.ReadOnlyField(source='employee.id') employee__name = serializers.ReadOnlyField(source='employee.name') start_date = serializers.DateField() end_date = serializers.DateField() total_cash = serializers.FloatField() class Meta: model = Record fields = ['employee__id', 'employee__name', 'total_cash', 'start_date', 'end_date'] In the view I'm overriding the .get_queryset() method class RecordView(viewsets.ModelViewSet): serializer_class = RecordSerializer queryset = Record.objects.all() def get_queryset(self): return Record.objects.values('employee__id', 'employee__name')\ .annotate(total_cash=Sum('cash'), start_date=Min('date'), end_date=Max('date')) I'm getting the right query result, but I cannot get the serializer to recognize the employee__name or employee__id fields. This is the JSON response: …