Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django ajax get model data in JS variable
Trying to get my model data from django views.py in home.html javascript variable using AJAX. So far I'm at : Views.py: def flights_list(request): flights = serializers.serialize("json", Flights.objects.all()) return JsonResponse({"flights": flights}) Ajax: function get_data() { $.ajax({ url: '', //Not sure what to put here. datatype: 'json', type: 'GET', success: function (data) { alert("Got data!") locations = {{ flights }}; } }); }; $(document).ready(function(){ setInterval(get_data,5000); }); Every 5 seconds i'm getting alert "Got data!" But when I'm trying to pass variable location = {{ flights }}; Then locations is empty. in ajax url:'' i suppose to have my views.py location? as when trying to alert("Got data!" + data) then my whole html is in that data variable.. Am i doing something wrong here? -
Problem using Python client library for Plaid
I'm following the tutorial, but I get an error when I use item_public_token_exchange. itempublic_tokenexchange exchange_request = ItemPublicTokenExchangeRequest( public_token=plaid_token ) exchange_response = CLIENT.item_public_token_exchange(exchange_request) the error: urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='sandbox', port=80): Max retries exceeded with url: /item/public_token/exchange (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x10f1493a0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known')) Not sure what is happening. -
How to pass data to modal from database in Django?
I know there are too many questios like that but I couldn't figure out passing data to modal form from database in Django. I can do it in another url by using form but I want adding and updating datas in same page by using modal. cekler.html <button style = "float:right; width:10%; " type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Çek Ekle </button> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Çek Ekle</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form class="modal-content animate" method = "post" name="CekEklemeFormu" enctype="multipart/form-data"> {{form|crispy}} {% csrf_token %} <button type="submit">Ekle</button> <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Vazgeç</button> </form> </div> </div> </div> </div> <br><br><br> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Çek Listesi</h6> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="Cek" width="100%" cellspacing="0"> <thead> <tr> <th scope="col"></th> <th scope="col">Çek No</th> <th scope="col">Banka</th> <th scope="col">Şirket</th> <th scope="col">Alıcı</th> <th scope="col">Tarih</th> <th scope="col">Tutar</th> <th scope="col">Vade</th> <th scope="col">Durum</th> <th scope="col">Ertelenen Tarih</th> <th scope="col">Bilgi Güncelle</th> </tr> </thead> <tfoot> <tr> <th colspan="6" style="text-align:right" >Toplam:</th> <th></th> <th></th> </tr> </tfoot> <tbody> {% for cek in ceklistesi %} <tr> <th scope="row"></th> <td>{{cek.no}}</td> <td>{{cek.banka}}</td> <td>{{cek.sirket}}</td> <td>{{cek.alici}}</td> <td>{{cek.tarih|date:'d F Y'}}</td> <td class="tutar">{{cek.tutar}}</td> <td>{{cek.vade_hesabi}} Gün</td > … -
Django - From inline to list display
For code below I'd like to display last 10 tasks (TaskInline) in UserAdmin and to have a button under those 10 tasks (in inline) that would lead to TaskAdmin with tasks filtered by the user. from django.contrib import admin from django.contrib.auth.models import User from django.db import models class Task(models.Model): title = models.CharField(max_length=50) description = models.TextField() performer = models.ForeignKey(User, on_delete=models.CASCADE) class TaskInline(admin.TabularInline): max_num = 10 # display last 10 tasks @admin.register(User) class UserAdmin(admin.ModelAdmin): inlines = TaskInline, @admin.register(Task) class TaskAdmin(admin.ModelAdmin): list_filter = 'performer', How can I do this? Should I change template for TaskInline? -
Upload image to Firebase using Django
I have a Django rest API, in which there is an API to get an image from formdata. from django.shortcuts import render from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from rest_framework import status from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.conf import settings import os import io from rest_framework.decorators import api_view import firebase_admin from firebase_admin import credentials, firestore, storage cred = credentials.Certificate("JSON FILE PATH") firebase_admin.initialize_app(cred,{'storageBucket': 'BUCKET URL'}) @api_view(['GET','POST']) def login(request): if request.method == 'POST': data = request.data if(type(data)!=dict): data=data.dict() file_obj=data['image'] fileName=file_obj.name blob=bucket.blob(fileName) blob.upload_from_file(file_obj.file) blob.make_public() print("File url", blob.public_url) return JsonResponse({'username':'Testing post response'}) elif request.method == 'GET': return JsonResponse({'username':'Testing get response'}) Now, when I send an image in formdata, it is uploading in firebase but not in image format, instead, it is uploading as application/octet-stream type and image is not being displayed. can anyone please help me with this? -
Get Specific Value to Next Page
.I am new to django. please help me with the solution.I want to get specific event name and number at a particular page. It has to same id and same name on next page. But, the input is showing me the last value of database.eventlist.html <form method="post"> {% csrf_token %} <label for="">Event Name</label> <input type="text" name="eventname"> <input type="submit"> </form> my view.py def eventlist(request): if request.method == 'POST': eventname = request.POST.get('eventname') eventid = str(random.randint(100000000, 999999999)) eventlistdata = EventList(eventname = eventname,eventid=eventid) eventlistdata.save() return render(request,"adminsys/eventlistlist.html",{'eventname': eventname,'eventid':eventid}) return render(request, 'adminsys/eventlist.html') my eventlistlist.html file only for passing values <form method="post"> {% csrf_token %} <table> <tr> <th>Event Name</th> <th>Event ID</th> <th>Submit</th> </tr> {% for post in post %} <tr> <td><input type="text" name="eventname" id="eventname" value="{{post.eventname}}"></td> <td><input type="text" name="eventid" id="eventid" value="{{post.eventid}}"></td> <td><button type="submit">Submit</button></td> </tr> {%endfor%} </table> </form> my views.py of eventlistlist file <form method="post"> {% csrf_token %} <label for="">Event Name</label> <input type="text" value="{{eventname}}" id="eventn"> <label for="">Event Id</label> <input type="text" value="{{eventid}}" id="eventi"> </form> And the last page where I want to get my same value as given in eventlistlist.html <form method="post"> {% csrf_token %} <label for="">Event Name</label> <input type="text" value="{{eventname}}" id="eventn"> <label for="">Event Id</label> <input type="text" value="{{eventid}}" id="eventi"> </form> I am always getting the data which is last in … -
Python 3.8.10 on local server but 3.8.12 on Azure server when I print "sys.version", would that cause problem?
I have 2 questions. I have depoloyed Django project in Azure Web App service. def index(request): return HttpResponse("Hello Nicholai! This is just for testing!" + platform.platform() + "\n " + sys.version) With the code above, it shows Python version is 3.8.12 In my local Windows Subsystem for Linux it is Python version 3.8.10. Would it cause problems to use different Python releases (3.8.10 vs 3.8.12) between Azure and local PC? I didn't found out how to change Azure server Python to 3.8.10. There are different guides on how to install 3.8.12 on Linux but it may not be optimal and I don't want to deal with that (as I'm don't have much clue about installing Python manually). My 2nd question is: when I run Kudus bash and type python3 --version it shows 3.5.3 but in the "ENVIRONMENT" page and when I run the code above (with sys.version) it prints it's 3.8.12 (I did choose 3.8 when setting up the web app service). Which one is the true Python version for the Azure server? -
rest_framework_simplejwt.token_blacklist fails with mongodb
Goal: Trying to blacklist token on on refresh or logout using mongodb. Issue: token_blacklist_outstandingtoken is The Collection In Mongodb Database Which Django REST Framework Use To Store Tokens Assigned To Recently Registered Users, It Stores Access Token Well in outstandingtoken table on First User Register, But It Errors While requesting or refreshing on Second try. This only happened after using black listing module ('rest_framework_simplejwt.token_blacklist'). Error: Traceback (most recent call last): File "C:\Users\schristian\Desktop\schristian\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "C:\Users\schristian\Desktop\schristian\lib\site-packages\djongo\sql2mongo\query.py", line 929, in _insert query.execute() File "C:\Users\schristian\Desktop\schristian\lib\site-packages\djongo\sql2mongo\query.py", line 397, in execute res = self.db[self.left_table].insert_many(docs, ordered=False) File "C:\Users\schristian\Desktop\schristian\lib\site-packages\pymongo\collection.py", line 770, in insert_many blk.execute(write_concern, session=session) File "C:\Users\schristian\Desktop\schristian\lib\site-packages\pymongo\bulk.py", line 533, in execute return self.execute_command(generator, write_concern, session) File "C:\Users\schristian\Desktop\schristian\lib\site-packages\pymongo\bulk.py", line 366, in execute_command _raise_bulk_write_error(full_result) File "C:\Users\schristian\Desktop\schristian\lib\site-packages\pymongo\bulk.py", line 140, in _raise_bulk_write_error raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred, full error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'jti_hex': 1}, 'keyValue': {'jti_hex': None}, 'errmsg': 'E11000 duplicate key error collection: ESI.token_blacklist_outstandingtoken index: token_blacklist_outstandingtoken_jti_hex_d9bdf6f7_uniq dup key: { jti_hex: null }', 'op': {'id': 31, 'user_id': 1, 'jti': '59a67c1bbd544864b12801d300cc031a', 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1NDgwMzYwMSwiaWF0IjoxNjQ3MDI3NjAxLCJqdGkiOiI1OWE2N2MxYmJkNTQ0ODY0YjEyODAxZDMwMGNjMDMxYSIsInVzZXJfaWQiOjF9.h-V5vK0OhEU7k0igook2nZHhQemFsy4OTfOdZWg-BD8', 'created_at': datetime.datetime(2022, 3, 11, 19, 40, 1, 373427), 'expires_at': datetime.datetime(2022, 6, 9, 19, 40, 1), '_id': ObjectId('622ba5914051a1f1923996f9')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, … -
Paginator and POST request for SearchForm
I've an issue with Paginator in Django, I tried several solution but none is working as I want... Views def order_list(request) form = SearchOrderForm() if 'search-order-post' in request.session: form = SearchOrderForm(request.session['search-order-post']) is_cookie_set = 1 if request.method == 'POST': form = SearchOrderForm(request.POST) request.session['search-order-post'] = request.POST is_cookie_set = 1 if is_cookie_set == 1: if form.is_valid(): statut = form.cleaned_data['statut'] clients = form.cleaned_data['clients'] [...] paginator = Paginator(orders, 50) page = request.GET.get('page') try: orders_page = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. orders_page = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. orders_page = paginator.page(paginator.num_pages) context = {'clients': clients, 'orders': orders_page, 'orders_list': orders, 'paginate': True, 'form': form, } return render(request, 'order/list.html', context) When I use Paginator in GET, to go to page 2 for exemple ... I lost all my query :( Is there any other way ? form.is_valid() return False when i change page -
Override djoser for swagger custom name with drf-yasg
I'm trying to set custom tag and custom name id and description to the endpoint of djoser. I tried to override to define later @swagger_auto_schema but without success. -
Add a style in css depending on the value of the field with django
I'm trying to style my line of code: <td class="{% if inven < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{inven.quantityInventory}}</span></td> It should change color depending on the value that is presented. The bad thing is that it always shows it to me in red (in else). what am I doing wrong? {% for inven in inventory %} <tr> <td><strong>{{inven.codigoInventory}}</strong></td> <td>{{inven.descriptionInventory}}</td> <td>${{inven.unitPriceInventory}}</td> <td class="{% if inven < 10 %}color-green-primary{% else %}color-red-primary{% endif %}">{{inven.quantityInventory}}</span></td> <td>{{inven.dealer}}</td> <td>{{inven.invoiceNumber}}</td> <td> <div class="badge bg-soft-danger font-size-12">{{inven.status}}</div> </td> <td><a href="{% url 'inventory:inventory_detail' inven.id%}">Detail</a></td> <td><a href="{% url 'inventory:edit_inventory' inven.id%}">Edit</a></td> <td><a href="{% url 'inventory:eliminar_inventory' inven.id%}" class="text-danger" >Delete</a></td> </tr> {% endfor %} -
Multiple websites on single VPS (nginx + centos + django)
I'm using VPS with nginx + centos + django. I already have one website running on it. Now i want to add one more domain, but after reading a lot of articles i still have troubles with it. Here is my nginx.conf file: user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. 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; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/sites-enabled/*.conf; server_names_hash_bucket_size 64; server { listen 443 ssl; server_name website1.com www.website1.com; ssl_certificate /etc/ssl/www.website1.com.crt; ssl_certificate_key /etc/ssl/www.website1.com.key; location /static/ { root /var/www/website1; index index.html index.htm index.php; } location / { root /var/www/website1; proxy_pass http://127.0.0.1:8888; index index.html index.htm index.php; proxy_connect_timeout 300s; proxy_read_timeout 300s; } } server { listen 80; server_name website1.com www.website1.com; return 301 https://$host:443$request_uri; location = /favicon.ico { alias /var/www/website1/static/img/favicon.png; } location /static/ { root /var/www/website1; index index.html index.htm index.php; } location / { root /var/www/website1; proxy_pass http://127.0.0.1:8888; index index.html index.htm index.php; proxy_connect_timeout 300s; proxy_read_timeout 300s; } } … -
Update default widget for Django Smart Selects - ChainedManyToManyField
I am using Django-Smart-Selects library for ManytoMany field. By default, in the templates, this field is rendered as Multiple Select instead of normal select. from smart_selects.db_fields import ChainedManyToManyField class Publication(models.Model): name = models.CharField(max_length=255) class Writer(models.Model): name = models.CharField(max_length=255) publications = models.ManyToManyField('Publication', blank=True, null=True) class Book(models.Model): publication = models.ForeignKey(Publication) writer = ChainedManyToManyField( Writer, horizontal=True, verbose_name='writer', chained_field="publication", chained_model_field="publications") name = models.CharField(max_length=255) How can I update the default widget to be a normal select drop down in this case? Looking at the source code (form_fields.py), I could see ChainedSelectMultiple being used as default widget. If I update the source code to use ChainedSelect, then it works fine as desired. I am just looking for a way to override this without updating the source code for smart select library itself. I tried updating it through my project's app form but was not successfull. #writer = ChainedManyToManyField(attrs={'widget': ChainedSelect}) Any hints or pointers would be appreciated. -
Running Django test gives "psycopg2.errors.DuplicateTable: relation already exists" error
I restored a database from a text (sql) file: psql ideatree < ideatree.sql which works with no errors. After running migrations I bring up the Django development server and the site comes up fine. But when I run tests: python manage.py test I get the error: psycopg2.errors.DuplicateTable: relation "ideatree_colors" already exists "ideatree_colors" is a table in the db, but test is creating its own separate test database, and indeed after this error the test database is left behind (I delete it before running tests again). I completely dropped the cluster, re-installed Postgresql-13, restored the database, and ran migrations again. Same error. -
Multiple choice form within an advanced search form
I am trying to create a multiple choice form where any combination of languages can be chosen. It's within a search form field: class AdvancedSearchForm(SearchForm): terms_show_partial_matches = forms.BooleanField(required=False, label=_("Show partial matches in terms") ) definitions_show_partial_matches = forms.BooleanField(required=False, label=_("Show partial matches in definitions") ) case_sensitive = forms.BooleanField(required=False, label=_("Case sensitive") ) ... I would like to implement something like this: filter_by_part_of_speech = forms.ModelChoiceField( queryset=PartOfSpeech.objects.all(), required=False, label=_("Filter by part of speech") ) However, it needs to be a multiple choice field so that any of the values can be chosen. Ideally though, I'm looking for a form where checkboxes are already checked. So something like this: LANG_CHOICES = ( ("1", "lang1"), ("2", "lang2"), ("3", "lang3"), ("4", "lang4"), ) filter_by_language = forms.MultipleChoiceField(choices=Language.objects.all().filter(name__in=LANG_CHOICES).values(), required=False, label=_("Filter by language")) The filter is called from the view with something like this: tqs = tqs.filter(language=language_filter) Now although the search works fine, the values are not displayed. On the other hand, they are displayed if I fill up a list and simply write: choices=list(lang_list) But then, obviously, the search is not actually performed. Therefore, my questions are: Can the constructor be adapted to display the values correctly? Should I rather implement the filter in the view? If so, how? Am … -
Apache + Django - No module named 'project'
I'm trying to deploy my django project on Ubuntu 20.04 using Apache. The virtual environment in /var/www/st-backend/stenv is working and I can succesfully host the server using the runserver command. However when I try to host it using Apache I'm getting a code 500 Internal server error when I browse the URL. Looking at the logs it seems like this is the problem ModuleNotFoundError: No module named 'project' But I have no idea what's wrong. wsgi.py is located in /var/www/st-backend/project. Below is my 000-default.conf setup (which is enabled), and I've modified ports.conf such that it will host on port 8080. /etc/apache2/sites-available/000-default.conf <VirtualHost *:8080> ServerAdmin webmaster@localhost ServerName example.stratoserver.net ServerAlias www.example.stratoserver.net DocumentRoot /var/www/st-backend ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/st-backend/static <Directory /var/www/st-backend/static> Require all granted </Directory> Alias /static /var/www/st-backend/media <Directory /var/www/st-backend/media> Require all granted </Directory> <Directory /var/www/st-backend/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess st-backend python-home=/var/www/st-backend/stenv python-path=/var/www/st-backend> WSGIProcessGroup st-backend WSGIScriptAlias / /var/www/st-backend/project/wsgi.py </VirtualHost> /etc/apache2/ports.conf Listen 8080 <IfModule ssl_module> Listen 443 </IfModule> <IfModule mod_gnutls.c> Listen 443 </IfModule> /var/log/apache2/error.log [Fri Mar 11 18:36:54.023232 2022] [wsgi:error] [pid 1237593:tid 139688904931072] [remote 85.---.230.141:63691] ModuleNotFoundError: No module named 'project' [Fri Mar 11 18:37:08.067473 2022] [wsgi:error] [pid 1237593:tid 139688913323776] [remote 34.---.162.3:32813] mod_wsgi (pid=1237593): Failed to exec Python … -
Can't login with Django Knox using Fetch POST request
I'm trying to login from the react front end via a Fetch POST request to the Knox endpoint but I am unable to. I can login normally from http://localhost:8000/api/login/ so I assume something must be wrong with my fetch but I can't figure it out. On the Knox docs it says that the LoginView only accepts an empty body so I can't just put the login info in there either. View (copy pasted from the docs and I added BasicAuthentication) class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) authentication_classes = [BasicAuthentication] def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) Fetch: const handleSubmit = (event) => { event.preventDefault(); const data = new FormData(event.currentTarget); const credentials = btoa(`${data.get('username')}:${data.get('password')}`); const requestOptions = { method: "POST", headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "Authorization": `Basic ${credentials}` }, body: JSON.stringify({}) } fetch('http://127.0.0.1:8000/api/login/', requestOptions) .then(response => console.log(response)) .catch(error => console.log(error)) Would appreciate any help as to what I'm doing wrong here -
How to mock reponse of instantiated mocked object with python pytest
I'm trying to mock a function that calls the sendgrid API. I want to mock the API library but can't work out where I'm going wrong. Function which calls the API: def mailing_list_signup(data: dict): email_address = data["email"] name = data["contact_name"] API_KEY = settings.SENDGRID_API_KEY sg = SendGridAPIClient(API_KEY) # https://docs.sendgrid.com/api-reference/contacts/add-or-update-a-contact data = { "contacts": [ { "email": email_address, "name": name, } ] } response = sg.client.marketing.contacts.put(request_body=data) return response my bad test: @dataclass class APIResponse: status_code: int = 202 body: bytes = b"example" @override_settings(SENDGRID_API_KEY='123') def test_mailing_list_signup(): response = APIResponse() with mock.patch("myapp.apps.base.business.SendGridAPIClient") as sendgridAPI: sendgridAPI.client.marketing.contacts.put.return_value = response data = { "email": "name@example.com", "contact_name": None, } result = mailing_list_signup(data) assert result == response Pytest tells me the test failed with the following message: FAILED myapp/apps/base/tests/test_business.py::test_mailing_list_signup - AssertionError: assert <MagicMock name='SendGridAPIClient().client.marketing.contacts.put()' id='4622453344'> == APIClient(status_code=202, body=b'example') -
Does Django+ReactJs refresh just like react by itself?
I am currently trying to teach myself django+reactjs. I have been able to get react to load with django run server but it doesn't live update. I can only see updates after I build and re-run django server. Is that how it is suppose to be or am I missing something? Please forgive me I am still much a noob at programming. -
How do I display only the checked checkboxes in a forms.CheckboxSelectMultiple?
I get list of all checkboxes in CheckboxSelectMultiple (checked and unchecked) but I need to get list only checked checboxes. How to do it? I have a form.py: class ProfileForm(forms.ModelForm): class Meta : fields = [ 'categories', ] widgets = {'categories': forms.CheckboxSelectMultiple(attrs = { "class": "column-checkbox"})} models.py: class Profile(models.Model): categories = models.ManyToManyField(Category, max_length=50, blank=True, verbose_name='Category') -
How to get user instance while registration in django?
I am creating ecommerce website. I am using django auth model to create Registration and Login, and now, I wanted to add phone number in another model with user instance, in order to implement otp. But, I am having trouble to get user instance while registration. So, how can I get request.user while registration. Looking for your please. views.py def Register(request): form = CreateUserForm() phonenumber = request.POST.get('phone') if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() ***Profile.objects.create(user=request.user,phonenumber=phonenumber)*** return redirect('login') context = { 'form':form, } models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phonenumber = models.CharField(verbose_name="Номер телефона", max_length=15) verified = models.BooleanField(default=False, verbose_name="Подтверждено", null=True, blank=True) Please help! -
Can't get Django Template Inheritance to work
This seems so simple and yet it refuses to work... I have my base.html file: {% load static %} <html> <head> <meta charset="utf-8"> <title> {% block title %} Simple Skeleton {% endblock title %} </title> and my home.html file: {% extends "base.html" %} <% block title %> Resource List <% endblock %> (they are both a bit longer but I feel this is all that is necessary) The home.html completely fails to overwrite the sections within the code blocks - the page title remains "Simple Skeleton" and not "Resource List" despite me accessing the home.html file. What am I doing wrong? -
Adding static file directory in django 2.2
I have tried ta add static file directory in django 2.2 as followed: My JS files are in project_name/src/app_name/static.... But the trick is not working guys. any suggestion? STATICFILES_DIRS = [os.path.join(LOCAL_ROOT, "project_name/src/app_name/static"), -
django migrations issues with postgres
I'm working on a Django project which dockerized and using Postgres for the database, but we are facing migrations issues, every time someone made changes in the model so if the other dev took a pull from git and try to migrate the migrations using python manage.py migrate because we already have the migrations file so sometimes the error is table already exists or table doesn't exists so every time I need to apply migrations using --fake but I guess that's not a good approach to migrate every time using --fake flag. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - dev.env ports: - "5432:5432" environment: - POSTGRES_DB=POSTGRES_DB - POSTGRES_USER=POSTGRES_USER - POSTGRES_PASSWORD=POSTGRES_PASSWORD app: container_name: app build: context: . command: bash -c "python manage.py runserver 0.0.0.0:8000" volumes: - ./core:/app - ./data/web:/vol/web env_file: - dev.env ports: - "8000:8000" depends_on: - db volumes: postgres_data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts # installing nano and cron service RUN apt-get update RUN apt-get install -y cron RUN apt-get install nano RUN pip install --upgrade pip COPY requirements.txt /app/ # install dependencies and manage assets RUN pip install … -
Best Practice accessing Azure Blob Images in Python
I am currently working on an AI webpage that enables users to upload datasets and do all kinds of stuff with that data in the cloud. I am using a react frontend with a django backend linked to a PostgreSQL and a blob storage on Azure. Now my question is: What is the common way to efficiently get the images as arrays from the blob storage into my django backend to run further python scripts (like augmentation) on them, while using my database models (so not by directly connecting to the blob storage)? This line of code works to retrieve the images from blob using the url that was saved in my database and perform a simple rotation. But the "request.urlopen" takes very very long. There must be a better way... class Image(models.Model): name = models.CharField(default='', max_length=100) image = models.FileField(upload_to='data', default='') dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) img = Image.objects.filter(dataset=somedataset, user=someuser) im = np.rot90(np.asarray(Image.open(BytesIO(request.urlopen(img['image']).read()))))