Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering issue with Django, MySQL, and JSONField
I'm troubleshooting filtering my model inside of Django. I'm also using the django_mysql JSONField fieldtype for all of my 'categories' for a field inside of my modal. class Image(models.Model): class Meta: verbose_name = "Image" verbose_name_plural = "Images" image = models.ImageField(verbose_name="Image Asset", upload_to='assets/images/', blank=True, null=True) is_published = models.BooleanField(verbose_name="Is this asset published", default=True, null=False) meta_format = models.CharField(verbose_name="Meta Format", max_length=200, blank=True, null=True) meta_width = models.CharField(verbose_name="Meta Width", max_length=200, blank=True, null=True) meta_height = models.CharField(verbose_name="Meta Height", max_length=200, blank=True, null=True) categories = JSONField(default=list) For reference, categories is the field that i'm attempting to filter. Lets say that I have this entry in my feed: { "id": 18, "url": "http://localhost:8001/images/18/", "image": "https://cdn.test.com/assets/images/person.jpg", "is_published": false, "meta_format": "JPEG", "meta_width": "1466", "meta_height": "800", "categories": "[{\"category\": \"staff_gallery\"}]" } The only thing that will return this result is >>> ImageAsset.objects.filter(categories="[{\"category\": \"staff_gallery\"}]") And this isn't feasable, because there will most likely be more than one category. If the entry changes to "categories": "[{\"category\": \"staff_gallery\"},{\"category\": \"test\"}]" then the whole query returns nothing. One way around this was to turn it into just a list, or array... so essentially the category above would turn to "categories": "[\"staff_gallery\"]". By doing this, the following query WILL work and returns my query that I want. >>> ImageAsset.objects.filter(categories__contains="[\"staff_gallery\"]") But ... … -
how to use url in djangoframework
I tried to Django crud operation get, post, delete, show method is working fine but the update method is not working because I tried to click the update button the update URL is not updated (http://localhost:8000/show/4/update/4/) how to handle this error and how to define the URL using Django. index.html <h1> Registration Form </h1> <form action="post/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit"> </form> <h1>List of all user</h1> <table style="width:100%"> <tr> <th>Name</th> <th>Email</th> </tr> {% for i in data %} <tr> <td>{{ i.name }}</td> <td>{{ i.email}}</td> <td><a href="show/{{ i.id }}/">Edit</a></td> <td><a href="delete/{{ i.id }}/">Delete</a></td> </tr> {% endfor %} </table> Edit.html <h1> Update Form </h1> <form action="update/{{ data.id }}/" method="POST"> {% csrf_token %} <label>Name</label> <input type="textbox" name="name" value="{{ data.name }}"> <label>Email</label> <input type="textbox" name="email" value="{{ data.email }}"> <input type="submit" value="Update"> </form> Views.py from django.shortcuts import render from django.http import HttpResponse from .models import CrudOperation from .forms import CrudForm # Create your views here. def get(request): form = CrudForm() data = CrudOperation.objects.all() return render(request,'index.html',{'form':form,'data':data}) def getId(request,id): form = CrudForm() data = CrudOperation.objects.get(id=id) return render(request,'edit.html',{'form':form,'data':data}) def post(request): form = CrudForm(request.POST) if form.is_valid(): form.save() return HttpResponse('<h1>post Method</h1>') def update(request,id): print(id) data = CrudOperation.objects.get(id=id) form = CrudForm(request.POST,instance=data) if(form.is_valid()): form.save() return HttpResponse('<h1>update method</h1>') … -
Uploading Big file is getting stuck - Deployed Django app using Nginx and gunicorn
I have deployed my django app on centos 7 using nginx and gunicorn, when I am trying to upload big file(25MB), it is getting hang after 80-90% upload, I went through many solutions and changed my nginx.conf file accordingly but nothing worked. I am not getting any error or logs regarding same in my nginx log file, Client is not getting any response back from server. I am not getting whats going wrong, please help me in this. - gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=prod Group=nginx WorkingDirectory=/home/prod/myProject1.0/myProject ExecStart=/home/prod/myProjectenv/bin/gunicorn --workers 3 --bind unix:/home/prod/myProject1.0/myProject/myProject.sock myProject.wsgi:application [Install] WantedBy=multi-user.target - nginx.conf user prod; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; server { listen 80; server_name _; client_body_in_file_only clean; client_max_body_size 8000M; client_body_buffer_size 80k; client_body_timeout 300s; client_body_temp_path /home/prod/media; send_timeout 300s; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/prod/myProject1.0/myProject/static/; } location / { proxy_set_header Host $http_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-Proto $scheme; proxy_pass http://unix:/home/prod/myProject1.0/myProject/myProject.sock; } } } My … -
How to disable Stream in Django
I am trying to temporarily prevent stream_django from making any remote API calls for offline development and testing purposes. What is the easiest way to completely disable remote connections to the upstream API servers? I found feed_manager.disable_model_tracking() which seems to prevent Activity updates, but it doesn't prevent all upstream calls (feed_manager.follow_user() for example). -
How can we develop the google earthengine based app in Python in our local machine?
I read the documentation of google earth engine. And I also see the github repo of the Earthengine api. I am exactly following the documentation. In my project file I added config.py file with my service account id and the privatekey.json file. I already write the following code and run it through terminal. import ee service_account = '<my-service-account-id>@tekson.iam.gserviceaccount.com' credentials = ee.ServiceAccountCredentials(service_account, 'privatekey.json') ee.Initialize(credentials) But it doesn't get initialized the earthengine. It always shows the following error. Traceback (most recent call last): File "/home/tekson/gee/lib/python3.6/site-packages/ee/data.py", line 338, in _execute_cloud_call return call.execute(num_retries=num_retries) File "/home/tekson/gee/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper return wrapped(*args, **kwargs) File "/home/tekson/gee/lib/python3.6/site-packages/googleapiclient/http.py", line 856, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: <HttpError 403 when requesting https://earthengine.googleapis.com/v1alpha/projects/earthengine-legacy/algorithms?prettyPrint=false&alt=json returned "Permission denied."> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "config.py", line 4, in <module> ee.Initialize(credentials) File "/home/tekson/gee/lib/python3.6/site-packages/ee/__init__.py", line 123, in Initialize ApiFunction.initialize() File "/home/tekson/gee/lib/python3.6/site-packages/ee/apifunction.py", line 154, in initialize signatures = data.getAlgorithms() File "/home/tekson/gee/lib/python3.6/site-packages/ee/data.py", line 969, in getAlgorithms return _cloud_api_utils.convert_algorithms(_execute_cloud_call(call)) File "/home/tekson/gee/lib/python3.6/site-packages/ee/data.py", line 340, in _execute_cloud_call raise _translate_cloud_exception(e) ee.ee_exception.EEException: Permission denied. I don't understand how to use google service account. I also want to develop this app in Django later. Please anyone help me how can I fix … -
Django download S3 file and include in zip
I've this piece of code to add files to a zip in Django. Works fine when media is local but when using an s3 bucket I get the following error: FileNotFoundError at /en/admin/certification/application/ [Errno 2] No such file or directory: 'https://bucket-name.s3.amazonaws.com/media/application_files/name_of_the_pdf.pdf' Here's the code: with open(csv_filename, 'w') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) for answer in q.answer_set.all(): if answer.question.question_type in ['file', 'files']: if answer.f : if 'RDS_HOSTNAME' in os.environ: res = answer.f.url else: res = settings.BASE_DIR + answer.f.url zf.write(res) elif answer.question.question_type == 'text' : res = answer.text else : res = answer.checkbox.name filewriter.writerow([answer.question.question, res]) And the traceback: Traceback: File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/admin/options.py" in changelist_view 1701. response = self.response_action(request, queryset=cl.get_queryset(request)) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/contrib/admin/options.py" in response_action 1400. response = func(self, request, queryset) … -
How can I run migrate, collectstatic and runserver in docker-compose.yml?
I need to run migrate , collectstatic and runserver from one command. I tried different ways, but nothing happened. version: '3' services: web: build: . ports: - "127.0.0.1:9001:9001" command: - ??? depends_on: - db links: - db:db volumes: - /tmp/transactions/postgresql:/run/postgresql -
Django 'User' object has no attribute 'user' when combining login_required with user_passes_test
I'm trying to combine a custom user_passes_test with a login_required decorator. This works fine: @login_required @user_passes_test(profile_expired, "Main:profile_expired") def home(request): return render(request, "Main/pages/home.html", {}) If I visit /app/ and profile_expired returns True, I get redirected to /app/profile_expired. However, the very same code on all other views, is returning error... @login_required @user_passes_test(profile_expired, "Main:profile_expired") def another_view(request): # some code... return render(request, "Main/pages/another_page.html", context) Error: Traceback (most recent call last): File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view if test_func(request.user): File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\contrib\auth\decorators.py", line 20, in _wrapped_view if test_func(request.user): File "C:\Users\S\PycharmProjects\SO\venv\lib\site-packages\django\utils\functional.py", line 257, in inner return func(self._wrapped, *args) AttributeError: 'User' object has no attribute 'user' While home has just the code above, another_view (and all other views) have more code... But the error cannot be inside the view since I've placed a breakpoint inside of them, started the debugger, and they never get triggered. The error must be somewhere else. I can't pinpoint why is this happening. Any idea? -
what's the purpose of the dependencies array in django migration files
I have a django app with migrations. At one point in the past, I decided to delete a migration because it wasn't necessary, and I assumed it was safe to do that because I just updated the dependency in the next migration to be dependent on the previous migration: migration 1 migration 2 <-- was dependent on 1, but deleted migration 3 <-- was dependent on 2, but now depend on 1 but this was causing weird behavior in django where starting the server kept telling me I have unapplied migrations, and trying to run migrations would attempt to run migrations that already ran. The other weirdness is, when I dropped the db and re-created, and ran migrations, it showed that all migrations ran, but when I checked which migrations actually ran, it only shows 1 to have run: running migrations: Applying banner.0001_initial... OK Applying banner.0003_auto_20180716_1309... OK Applying banner.0004_auto_20180716_1520... OK Applying banner.0005_auto_20180716_1529... OK Applying banner.0006_auto_20180716_2225... OK Applying banner.0007_auto_20180717_1939... OK Applying banner.0008_auto_20180723_1409... OK Applying banner.0009_auto_20180723_1420... OK Applying banner.0010_auto_20180723_1423... OK Applying banner.0011_auto_20180723_1424... OK Applying banner.0012_auto_20180723_1427... OK Applying banner.0013_auto_20180822_0057... OK Applying banner.0014_auto_20180905_1435... OK checking which ran: banner [X] 0001_initial [ ] 0003_auto_20180716_1309 [ ] 0004_auto_20180716_1520 [ ] 0005_auto_20180716_1529 [ ] 0006_auto_20180716_2225 [ ] … -
nginx fails successfully start with error pread() "/etc/nginx/sites-enabled/sites-available" failed (21: Is a directory)
I have a simple django website im trying to load with nginx and uwsgi . When i try to test my nginx configuration i get the following: $ sudo nginx -t nginx: [crit] pread() "/etc/nginx/sites-enabled/sites-available" failed (21: Is a directory) nginx: configuration file /etc/nginx/nginx.conf test failed my sites-available/default config looks like: # the upstream component nginx needs to connect to upstream django { server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name website.com xx.xx.x.x; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 2M; # adjust to taste # Django media #location /media { # alias ; # your Django project's media files - amend as required #} location /static { alias /static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass 127.0.0.1:8001; include uwsgi_params; # the uwsgi_params file you installed } } I viewed nginx error logs in /var/log/nginx/error.log and found: 2019/11/26 14:29:53 [crit] 7702#7702: pread() … -
When to use Admin model_delete/model_save and Model delete/save?
Just curious as to the best practices for using save/delete in Model versus delete_model/save_model in ModelAdmin. Is one preferred over the other? In my particular case, I have a Document model with a JSON field that holds a bunch of metadata (name:value pairs) for Documents (photos, pdfs, etc). The metadata is defined in other models (MetaData for names and MetaDataValue for the value(s)), so I can change the metadata names and values at run time. When an existing MetaData name or value changes or is deleted, I need to "scrub" the metadata stored in the Document model to change/delete the metadata names/values to keep them in sync with what is defined in the MetaData and MetaDataValue models. All these changes are done through the Admin screens. Would it be more appropriate to use model_save and model_delete in the Admin or save and delete in the respective models? Functionally, it does not matter as far as I can see. I am just wondering if there is a preferred way, or a more "django idiomatic" way to do this. Thanks! Mark -
SMTPAuthenticationError while sending email from gmail
settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'abbasgujjar2525@gmail.com' EMAIL_HOST_PASSWORD = 'gujjarabbas2525' views.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings def index(request): subject = 'Thank you for registering to our site' message = ' it means a world to us ' email_from = settings.EMAIL_HOST_USER recipient_list = ['liteno1606@xmail365.net',] send_mail( subject, message, email_from, recipient_list ) return render(request , 'ab/index.html') I have the following code in my settings.py and views.py for sending email but following error occure Following Error occurestrong text -
How to make a reverse lookup from one model to another for admin_order_field
I have two models class Document(Model): document_id = models.AutoField(primary_key=True) ... other fields class DocumentMetaData(Model): documentMetaData_id = models.AutoField(primary_key=True) document_id = models.ForeignKey(Document, on_delete=models.CASCADE, verbose_name="document file name") metadata = JSONField(blank=True) The metadata in the DocumentMetaData model has a key 'Decade' in the JSONField. In the DocumentMetaDataAdmin I have this for a sortable Decade field: def get_decade(self, obj): return obj._decade get_decade.admin_order_field = '_decade' I would like to have a get_decade function in the DocumentAdmin that displays a Decade column in the DocumentAdmin page, and have that field sortable. So far, I can get the Decade column in the DocumentAdmin by doing this: def get_decade(self, obj): result = DocumentMetaData.objects.get(document_id=obj.document_id).metadata['Decade'] return result get_decade.admin_order_field = 'get_decade' But the sorting part does not work - I get a field error as there is no decade field in the Document model. Is there some way to do a reverse lookup on the document_id field to the DocumentMetaData model (since admin_order_field needs a related model) so I can sort on the decade field in the DocumentAdmin? Thanks! Mark -
Modify export data un module export-import django
I want to make a custom export using this module of Python(export-import) I want to modify the value of one colum. Actualy, this colum is like "uXXXXXX" and I want to delete this "u" before export. I justo try to make it overriding before_export and export function, but always queryset make again as default (because my method call super and override again my custom queryset) Any idea? thanks! -
GoDaddy custom domain hosted with Heroku throwing privacy error
I'm having trouble getting the custom domain I bought from GoDaddy to work with the Django app I have hosted on Heroku's free dyno. The Heroku app is accessible from the custom domain, however, I keep getting a privacy error from chrome. See below: My Heroku dashboard confirms that I have added my custom domain. I have tried doing this through both the CLI and GUI, with no different results. My DNS settings on my domain in GoDaddy are configured as follows. Someone had mentioned the CNAME setting should be the .herokudns domain generated by the addition of the custom domain in the Heroku dashboard, but when I make that change the website is not accessible at all. The Heroku app is named: desolate-basin-60228 and can be accessible at https://desolate-basin-60228.herokuapp.com/ and in GoDaddy I have confirmed that my forwarding is set to http (not https as I don't need a security cert. for this site): I also thought that it may be an issue with my Django settings.py file. So I adjusted any line with mention of https. This did not have any effect. Does anyone have any thoughts on what I'm missing here? -
Setup Gunicorn Workers Type Properly
Im using gunicorn + supervisor + nginx to deploy my django, now i already setup for the gunicorn worker to use gevent type so its from sync to async, but in supervisor log it says that the type of worker is sync. Gunicorn Supervisor Service: #!/bin/bash NAME="web" # Name of the application DJANGODIR=/home/webserver/0.1 # Django project directory SOCKFILE=localhost:8000 # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as NUM_WORKERS=9 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=web.settings # which settings file should Django use DJANGO_WSGI_MODULE=web.wsgi # WSGI module name TIMEOUT=30 echo "Menjalankan $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist # RUNDIR=$(dirname $SOCKFILE) # test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec /home/webserver/env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --worker-class=gevent \ --user=$USER --group=$GROUP \ --bind=$SOCKFILE \ --log-level=debug \ --log-file="-" Supervisor Logs: [2019-11-26 23:03:55 +0800] [4802] [INFO] Starting gunicorn 19.9.0 [2019-11-26 23:03:55 +0800] [4802] [INFO] Listening at: http://127.0.0.1:8000 … -
How to write this query sql in a DJANGO ORM
I did this query to tested, but now i need to included this in my view django and i don't know how to do this, SELECT Referencia, Recebido, sum(contas_paga + Salarios_Comissao + encargos) as Contas, sum(Recebido - (contas_paga + Salarios_Comissao + encargos)) as Total FROM( SELECT vrm.mes_referencia as Referencia, vrm.mapa_atual - (vrm.mapa_atual * 0.2) as Recebido, (SELECT SUM(valor) from contas_pagar_contas_pagar where to_char(dt_pagamento, 'MMYYYY') = vrm.mes_referencia) as contas_paga, (SELECT SUM(vl_valor_pago) from func_pagamentos_pagamentos where to_char(data_pagamento, 'MMYYYY') = vrm.mes_referencia) as Salarios_Comissao, (SELECT SUM(salario * 1.8) from func_pagamentos_pagamentos where to_char(data_pagamento, 'MMYYYY') = vrm.mes_referencia) as encargos FROM venda_resumo_mapa as vrm WHERE vrm.mes_referencia like '%2019%' group by (vrm.mes_referencia, vrm.mapa_atual) order by vrm.mes_referencia) as f group by (f.Referencia, f.Recebido) -
Trying to pass two dictionaries but only first one works
views.py: def home(request): return render(request, 'blog/home.html', {'title': 'HOME'}, {'post': posts}) In this code, only title works. when I took {'post': posts} before {'title': 'HOME'} , post works but title don't. I have to use both in templates. I'm a beginner in django. How can i fix this problem ? -
My Django Project doesn't appear in my Docker-Image (Docker toolbox for windows home)
I'm trying to build a django project using docker-compose, such as it is in the Docker Documentation (I use Docker toolbox for Windows 10 Home). But when i execute the command: sudo docker-compose run web django-admin startproject composeexample . I get an bash: sudo: command not found __ Then if i execute the same command without "sudo": docker-compose run web django-admin startproject composeexample . The image is created but the django project folder is not displayed. Finally, when i run the command again i get: The Dockerfile is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db and the requirements.txt: Django>=2.0,<3.0 psycopg2>=2.7,<3.0 -
Ajax.click function button on site not doing anything
can't work out why my button won't do anything on click. Won't even post the console log. Quite new to using ajax so bit confused. Thanks in advance, I hope it's something simple i'm missing. This is the page with the button {% extends "website/base.html" %} {% load staticfiles %} {% block content %} <style> #table td { padding: 0px; margin: 0px; } #table { border-spacing: 0px; } </style> <form id="search-form" method="POST" action="{% url 'searchs' %}"> {% csrf_token %} <div class="active-cyan-3 active-cyan-4 mb-4"> <input class="input" name="username" type="hidden" value="{{ username }}"> <input class="form-control" type="text" placeholder="Search" aria-label="Search" name="search-input" id="search-input"> </div> </form> <div class="text-center"> <button name="search-button" id="searchbut" align="centre" class="btn btn-dark btn-lg">Search</button> </div> <!-- Search form --> <br> <table id="search-tbl" class="table" width="100%" border=1> <thead class="thead-dark"> <tr> <th>Image</th> <th>Title</th> </tr> </thead> <tbody> {% for Auction in results %} <tr class='bg-white' align="center"> <td width="60%" vertical-align="middle" align="center"> {% load static %} <a href="auction/{{ Auction.id}}"> <img width="" href="auction/{{ Auction.id}}" src="{{ Auction.picture }}"> </a> </td> <td align="center"><a href="auction/{{ Auction.id}}">{{ Auction.title }}</a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} <script> $(function () { $('#searchbut').click(function () { console.log("pushed") $.ajax({ url: "{% url 'searchs' %}", method: "POST", data: $("#search-form").serializeArray(), success: function (data) { console.log(data) $("#search-tbl tbody").remove(); for (var i = … -
Ajax call not calling view function in Django
I am trying to build a login form in Django, and when the user hits login, I wish to send the username and password to check which type of user it is as my system has 3 different kinds of users. Following is the code: views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User def index(request): return render(request, "login.html") @csrf_protect def auth_login(request): print("Hello !") username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) group = User.objects.get(username=username).groups.values()[0]['name'] print(username) print(user) print(password) login.html - (I have a simple bootstrap login form) <body class="text-center"> <form class="form-signin" id="login-form">{% csrf_token %} <img class="mb-4" src="{% static "download.png" %}" alt="Logo" align="center" height="112" width="112"> <h1 class="h3 mb-4 font-weight-normal">Please sign in</h1> <label for="inputEmail" class="sr-only">Username</label> <input type="text" id="uname" class="form-control" placeholder="Username" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="passwd" class="form-control" placeholder="Password" required> <div class="checkbox mb-4"> </div> <button class="btn btn-lg btn-primary btn-block" id="loginbutton" type="submit">Sign in</button> <p class="mt-3 mb-5 text-muted">Planning Tool</p> </form> <script type="text/javascript"> $(document).ready(function () { $("#login-form").on('submit', function (e) { e.preventDefault(); login(); }); function login(){ alert($("#uname").val()) $.ajax({ url: {% url 'auth:Login' %}, method : "POST", data : { "username" : $("#uname").val(), "password" : $("#passwd").val(), 'csrfmiddlewaretoken' : "{{ csrf_token }}" }, … -
Django Rest Framework - Nested Serialization not working
model.py class Account(models.Model): name_Account= models.CharField(max_length=50, default='') fecha_nacimiento = models.CharField(max_length=150, default='') phone = models.CharField(max_length=150, default='') mail = models.CharField(max_length=150, default='') user_id = models.ForeignKey(User,on_delete=models.CASCADE) rol_id = models.ForeignKey(Rol,on_delete=models.CASCADE, null =True) class Reclamo(models.Model): nameReclamo= models.CharField(max_length=50, default='') rut = models.CharField(max_length=20, default='') numpoliza = models.CharField(max_length=30, default='') detalle_diagnostico = models.CharField(max_length=200, default='') account_id = models.ForeignKey(Account,on_delete=models.CASCADE,null =True) date = models.DateField(auto_now=True) name_estado= models.CharField(max_length=50, default='Pendiente') num_claim= models.CharField(max_length=30, default=' ' ,blank = True) serializer.py class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'name_Account', 'fecha_nacimiento', 'phone', 'mail', 'user_id', 'rol_id','rolName') class ReclamoSerializer(serializers.ModelSerializer): name_Account = AccountSerializer(many=False) #read_only=True no return, no error class Meta: model = Reclamo fields = ('id','nameReclamo','rut','numpoliza','detalle_diagnostico','account_id','date','name_estado','num_claim', name_Account) error Got AttributeError when attempting to get a value for field name_Account on serializer ReclamoSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Reclamo instance. Original exception text was: 'Reclamo' object has no attribute 'name_Account'. I have tried different examples, but I cannot return what I hope -
How to generate payload using camelCase attributes with DRF serializers
So I need to consume an API that the JSON fields are all camelCase and I want to write them on my code as snake_case. How can I do this? I want something like this: serializer = MySerializer(data={'my_field': 'test'}) if serializer.is_valid(): output_data = serializer.validated_data print(output_data) # {'myField': 'test'} -
What relation should i create in models so that one user can create only one comments for Product?
This is my models. What is the best approach? OneToOneField allows to create only one comments for all time. class Person(models.Model): first_name = models.CharField( max_length=512, blank=True, null=True, ) last_name = models.CharField( max_length=512, blank=True, null=True, ) class Product(models.Model): slug = SlugField() name = NameField() description = DescriptionField() class Comment(models.Model): created_at = models.DateTimeField(auto_now_add=True) person = models.OneToOneField(Person, on_delete=models.CASCADE) text = models.TextField(null=True, blank=True) -
How to add a django application in classic asp website in IIS 7.5?
I am currently working on configuring IIS 7.5 where main website is built with classic ASP and need to implement django application INSIDE of main site. I've taken various ways to configure IIS to run django application in classic ASP webpage but for some reason it kept gives 403 Forbidden error. I've read and researched articles and posts regarding this issue but most of those resources were about permission issue. Here are steps / ways I've taken so far. Option 1 1. Add a folder where django application is located as a virtual directory in IIS 7.5 2. Configure DJANGO_SETTINGS_MODULE, PYTHONPATH, WSGI_HANDLER variables in FastCGI configuration at server level. 3. Add Handler Mapping in application level to run python in IIS. 4. Grant a permission to ASP website's application pool to the django application folder so that ASP website can access django application folder. Option 2 All of steps are same as option 1 except added django application as a application instead of virtual directory. In terms of application pool, I've tried DefaultAppPool, IIS_IUSR, IUSR, ApplicationPoolIdentity, NetworkService but none of them were working. (Btw, whenever I turn on Directory Browsing, I can navigate into django application's folder and see contents) …